text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k β |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def should_execute(self, workload):
""" If we have been suspended by i3bar, only execute those modules that set the keep_alive flag to a truthy value. See the docs on the suspend_signal_handler method of the io module for more information. """ |
if not self._suspended.is_set():
return True
workload = unwrap_workload(workload)
return hasattr(workload, 'keep_alive') and getattr(workload, 'keep_alive') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_sensors():
""" Detect and return a list of Sensor objects """ |
import sensors
found_sensors = list()
def get_subfeature_value(feature, subfeature_type):
subfeature = chip.get_subfeature(feature, subfeature_type)
if subfeature:
return chip.get_value(subfeature.number)
for chip in sensors.get_detected_chips():
for feature in chip.get_features():
if feature.type == sensors.FEATURE_TEMP:
try:
name = chip.get_label(feature)
max = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_MAX)
current = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_INPUT)
critical = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_CRIT)
if critical:
found_sensors.append(Sensor(name=name, current=current, maximum=max, critical=critical))
except sensors.SensorsException:
continue
return found_sensors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_output_original(self):
""" Build the output the original way. Requires no third party libraries. """ |
with open(self.file, "r") as f:
temp = float(f.read().strip()) / 1000
if self.dynamic_color:
perc = int(self.percentage(int(temp), self.alert_temp))
if (perc > 99):
perc = 99
color = self.colors[perc]
else:
color = self.color if temp < self.alert_temp else self.alert_color
return {
"full_text": self.format.format(temp=temp),
"color": color,
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_urgent(self, sensors):
""" Determine if any sensors should set the urgent flag. """ |
if self.urgent_on not in ('warning', 'critical'):
raise Exception("urgent_on must be one of (warning, critical)")
for sensor in sensors:
if self.urgent_on == 'warning' and sensor.is_warning():
return True
elif self.urgent_on == 'critical' and sensor.is_critical():
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_sensor(self, sensor):
""" Format a sensor value. If pango is enabled color is per sensor. """ |
current_val = sensor.current
if self.pango_enabled:
percentage = self.percentage(sensor.current, sensor.critical)
if self.dynamic_color:
color = self.colors[int(percentage)]
return self.format_pango(color, current_val)
return current_val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_sensor_bar(self, sensor):
""" Build and format a sensor bar. If pango is enabled bar color is per sensor.""" |
percentage = self.percentage(sensor.current, sensor.critical)
bar = make_vertical_bar(int(percentage))
if self.pango_enabled:
if self.dynamic_color:
color = self.colors[int(percentage)]
return self.format_pango(color, bar)
return bar |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" Returns the sum of unread messages across all registered backends """ |
unread = 0
current_unread = 0
for id, backend in enumerate(self.backends):
temp = backend.unread or 0
unread = unread + temp
if id == self.current_backend:
current_unread = temp
if not unread:
color = self.color
urgent = "false"
if self.hide_if_null:
self.output = None
return
else:
color = self.color_unread
urgent = "true"
format = self.format
if unread > 1:
format = self.format_plural
account_name = getattr(self.backends[self.current_backend], "account", "No name")
self.output = {
"full_text": format.format(unread=unread, current_unread=current_unread, account=account_name),
"urgent": urgent,
"color": color,
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_output(self, line):
"""Convert output to key value pairs""" |
try:
key, value = line.split(":")
self.update_value(key.strip(), value.strip())
except ValueError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_value(self, key, value):
"""Parse key value pairs to update their values""" |
if key == "Status":
self._inhibited = value != "Enabled"
elif key == "Color temperature":
self._temperature = int(value.rstrip("K"), 10)
elif key == "Period":
self._period = value
elif key == "Brightness":
self._brightness = value
elif key == "Location":
location = []
for x in value.split(", "):
v, d = x.split(" ")
location.append(float(v) * (1 if d in "NE" else -1))
self._location = (location) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_inhibit(self, inhibit):
"""Set inhibition state""" |
if self._pid and inhibit != self._inhibited:
os.kill(self._pid, signal.SIGUSR1)
self._inhibited = inhibit |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(command, detach=False):
""" Runs a command in background. No output is retrieved. Useful for running GUI applications that would block click events. :param command: A string or a list of strings containing the name and arguments of the program. :param detach: If set to `True` the program will be executed using the `i3-msg` command. As a result the program is executed independent of i3pystatus as a child of i3 process. Because of how i3-msg parses its arguments the type of `command` is limited to string in this mode. """ |
if detach:
if not isinstance(command, str):
msg = "Detached mode expects a string as command, not {}".format(
command)
logging.getLogger("i3pystatus.core.command").error(msg)
raise AttributeError(msg)
command = ["i3-msg", "exec", command]
else:
if isinstance(command, str):
command = shlex.split(command)
try:
subprocess.Popen(command, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError:
logging.getLogger("i3pystatus.core.command").exception("")
except subprocess.CalledProcessError:
logging.getLogger("i3pystatus.core.command").exception("") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_hex_color_range(start_color, end_color, quantity):
""" Generates a list of quantity Hex colors from start_color to end_color. :param start_color: Hex or plain English color for start of range :param end_color: Hex or plain English color for end of range :param quantity: Number of colours to return :return: A list of Hex color values """ |
raw_colors = [c.hex for c in list(Color(start_color).range_to(Color(end_color), quantity))]
colors = []
for color in raw_colors:
# i3bar expects the full Hex value but for some colors the colour
# module only returns partial values. So we need to convert these colors to the full
# Hex value.
if len(color) == 4:
fixed_color = "#"
for c in color[1:]:
fixed_color += c * 2
colors.append(fixed_color)
else:
colors.append(color)
return colors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_method_of(method, object):
"""Decide whether ``method`` is contained within the MRO of ``object``.""" |
if not callable(method) or not hasattr(method, "__name__"):
return False
if inspect.ismethod(method):
return method.__self__ is object
for cls in inspect.getmro(object.__class__):
if cls.__dict__.get(method.__name__, None) is method:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_click(self, button, **kwargs):
""" Maps a click event with its associated callback. Currently implemented events are: ============ ================ ========= Event Callback setting Button ID ============ ================ ========= Left click on_leftclick 1 Middle click on_middleclick 2 Right click on_rightclick 3 Scroll up on_upscroll 4 Scroll down on_downscroll 5 Others on_otherclick > 5 ============ ================ ========= The action is determined by the nature (type and value) of the callback setting in the following order: 1. If null callback (``None``), no action is taken. 2. If it's a `python function`, call it and pass any additional arguments. 3. If it's name of a `member method` of current module (string), call it and pass any additional arguments. 4. If the name does not match with `member method` name execute program with such name. .. seealso:: :ref:`callbacks` for more information about callback settings and examples. :param button: The ID of button event received from i3bar. :param kwargs: Further information received from i3bar like the positions of the mouse where the click occured. :return: Returns ``True`` if a valid callback action was executed. ``False`` otherwise. """ |
actions = ['leftclick', 'middleclick', 'rightclick',
'upscroll', 'downscroll']
try:
action = actions[button - 1]
except (TypeError, IndexError):
self.__log_button_event(button, None, None, "Other button")
action = "otherclick"
m_click = self.__multi_click
with m_click.lock:
double = m_click.check_double(button)
double_action = 'double%s' % action
if double:
action = double_action
# Get callback function
cb = getattr(self, 'on_%s' % action, None)
double_handler = getattr(self, 'on_%s' % double_action, None)
delay_execution = (not double and double_handler)
if delay_execution:
m_click.set_timer(button, cb, **kwargs)
else:
self.__button_callback_handler(button, cb, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def text_to_pango(self):
""" Replaces all ampersands in `full_text` and `short_text` attributes of `self.output` with `&`. It is called internally when pango markup is used. Can be called multiple times (`&` won't change to `&amp;`). """ |
def replace(s):
s = s.split("&")
out = s[0]
for i in range(len(s) - 1):
if s[i + 1].startswith("amp;"):
out += "&" + s[i + 1]
else:
out += "&" + s[i + 1]
return out
if "full_text" in self.output.keys():
self.output["full_text"] = replace(self.output["full_text"])
if "short_text" in self.output.keys():
self.output["short_text"] = replace(self.output["short_text"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_protected_settings(self, settings_source):
""" Attempt to retrieve protected settings from keyring if they are not already set. """ |
user_backend = settings_source.get('keyring_backend')
found_settings = dict()
for setting_name in self.__PROTECTED_SETTINGS:
# Nothing to do if the setting is already defined.
if settings_source.get(setting_name):
continue
setting = None
identifier = "%s.%s" % (self.__name__, setting_name)
if hasattr(self, 'required') and setting_name in getattr(self, 'required'):
setting = self.get_setting_from_keyring(identifier, user_backend)
elif hasattr(self, setting_name):
setting = self.get_setting_from_keyring(identifier, user_backend)
if setting:
found_settings.update({setting_name: setting})
return found_settings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, module, *args, **kwargs):
""" Register a new module. :param module: Either a string module name, or a module class, or a module instance (in which case args and kwargs are invalid). :param kwargs: Settings for the module. :returns: module instance """ |
from i3pystatus.text import Text
if not module:
return
# Merge the module's hints with the default hints
# and overwrite any duplicates with the hint from the module
hints = self.default_hints.copy() if self.default_hints else {}
hints.update(kwargs.get('hints', {}))
if hints:
kwargs['hints'] = hints
try:
return self.modules.append(module, *args, **kwargs)
except Exception as e:
log.exception(e)
return self.modules.append(Text(
color="#FF0000",
text="{i3py_mod}: Fatal Error - {ex}({msg})".format(
i3py_mod=module,
ex=e.__class__.__name__,
msg=e
)
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" Run main loop. """ |
if self.click_events:
self.command_endpoint.start()
for j in io.JSONIO(self.io).read():
for module in self.modules:
module.inject(j) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Initialize the URL used to connect to SABnzbd.""" |
self.url = self.url.format(host=self.host, port=self.port,
api_key=self.api_key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Connect to SABnzbd and get the data.""" |
try:
answer = urlopen(self.url + "&mode=queue").read().decode()
except (HTTPError, URLError) as error:
self.output = {
"full_text": str(error.reason),
"color": "#FF0000"
}
return
answer = json.loads(answer)
# if answer["status"] exists and is False, an error occured
if not answer.get("status", True):
self.output = {
"full_text": answer["error"],
"color": "#FF0000"
}
return
queue = answer["queue"]
self.status = queue["status"]
if self.is_paused():
color = self.color_paused
elif self.is_downloading():
color = self.color_downloading
else:
color = self.color
if self.is_downloading():
full_text = self.format.format(**queue)
else:
full_text = self.format_paused.format(**queue)
self.output = {
"full_text": full_text,
"color": color
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pause_resume(self):
"""Toggle between pausing or resuming downloading.""" |
if self.is_paused():
urlopen(self.url + "&mode=resume")
else:
urlopen(self.url + "&mode=pause") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_browser(self):
"""Open the URL of SABnzbd inside a browser.""" |
webbrowser.open(
"http://{host}:{port}/".format(host=self.host, port=self.port)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_click(self, button, **kwargs):
""" Capture scrollup and scorlldown to move in groups Pass everthing else to the module itself """ |
if button in (4, 5):
return super().on_click(button, **kwargs)
else:
activemodule = self.get_active_module()
if not activemodule:
return
return activemodule.on_click(button, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _get_system_tz(self):
'''
Get the system timezone for use when no timezone is explicitly provided
Requires pytz, if not available then no timezone will be set when not
explicitly provided.
'''
if not HAS_PYTZ:
return None
def _etc_localtime():
try:
with open('/etc/localtime', 'rb') as fp:
return pytz.tzfile.build_tzinfo('system', fp)
except OSError as exc:
if exc.errno != errno.ENOENT:
self.logger.error(
'Unable to read from /etc/localtime: %s', exc.strerror
)
except pytz.UnknownTimeZoneError:
self.logger.error(
'/etc/localtime contains unrecognized tzinfo'
)
return None
def _etc_timezone():
try:
with open('/etc/timezone', 'r') as fp:
tzname = fp.read().strip()
return pytz.timezone(tzname)
except OSError as exc:
if exc.errno != errno.ENOENT:
self.logger.error(
'Unable to read from /etc/localtime: %s', exc.strerror
)
except pytz.UnknownTimeZoneError:
self.logger.error(
'/etc/timezone contains unrecognized timezone \'%s\'',
tzname
)
return None
return _etc_localtime() or _etc_timezone() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_weather(self):
'''
Check the weather using the configured backend
'''
self.output['full_text'] = \
self.refresh_icon + self.output.get('full_text', '')
self.backend.check_weather()
self.refresh_display() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_color_data(self, condition):
'''
Disambiguate similarly-named weather conditions, and return the icon
and color that match.
'''
if condition not in self.color_icons:
# Check for similarly-named conditions if no exact match found
condition_lc = condition.lower()
if 'cloudy' in condition_lc or 'clouds' in condition_lc:
if 'partly' in condition_lc:
condition = 'Partly Cloudy'
else:
condition = 'Cloudy'
elif condition_lc == 'overcast':
condition = 'Cloudy'
elif 'thunder' in condition_lc or 't-storm' in condition_lc:
condition = 'Thunderstorm'
elif 'snow' in condition_lc:
condition = 'Snow'
elif 'rain' in condition_lc or 'showers' in condition_lc:
condition = 'Rainy'
elif 'sunny' in condition_lc:
condition = 'Sunny'
elif 'clear' in condition_lc or 'fair' in condition_lc:
condition = 'Fair'
elif 'fog' in condition_lc:
condition = 'Fog'
return self.color_icons['default'] \
if condition not in self.color_icons \
else self.color_icons[condition] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_format_all(self, usage):
""" generates string for format all """ |
format_string = " "
core_strings = []
for core, usage in usage.items():
if core == 'usage_cpu' and self.exclude_average:
continue
elif core == 'usage':
continue
core = core.replace('usage_', '')
string = self.formatter.format(self.format_all,
core=core,
usage=usage)
core_strings.append(string)
core_strings = sorted(core_strings)
return format_string.join(core_strings) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh_events(self):
""" Retrieve the next N events from Google. """ |
now = datetime.datetime.now(tz=pytz.UTC)
try:
now, later = self.get_timerange_formatted(now)
events_result = self.service.events().list(
calendarId='primary',
timeMin=now,
timeMax=later,
maxResults=10,
singleEvents=True,
orderBy='startTime',
timeZone='utc'
).execute()
self.events.clear()
for event in events_result.get('items', []):
self.events.append(GoogleCalendarEvent(event))
except HttpError as e:
if e.resp.status in (500, 503):
self.logger.warn("GoogleCalendar received %s while retrieving events" % e.resp.status)
else:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lchop(string, prefix):
"""Removes a prefix from string :param string: String, possibly prefixed with prefix :param prefix: Prefix to remove from string :returns: string without the prefix """ |
if string.startswith(prefix):
return string[len(prefix):]
return string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def popwhile(predicate, iterable):
"""Generator function yielding items of iterable while predicate holds for each item :param predicate: function taking an item returning bool :param iterable: iterable :returns: iterable (generator function) """ |
while iterable:
item = iterable.pop()
if predicate(item):
yield item
else:
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def round_dict(dic, places):
""" Rounds all values in a dict containing only numeric types to `places` decimal places. If places is None, round to INT. """ |
if places is None:
for key, value in dic.items():
dic[key] = round(value)
else:
for key, value in dic.items():
dic[key] = round(value, places) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten(l):
""" Flattens a hierarchy of nested lists into a single list containing all elements in order :param l: list of arbitrary types and lists :returns: list of arbitrary types """ |
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], list):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
i += 1
return l |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formatp(string, **kwargs):
""" Function for advanced format strings with partial formatting This function consumes format strings with groups enclosed in brackets. A group enclosed in brackets will only become part of the result if all fields inside the group evaluate True in boolean contexts. Groups can be nested. The fields in a nested group do not count as fields in the enclosing group, i.e. the enclosing group will evaluate to an empty string even if a nested group would be eligible for formatting. Nesting is thus equivalent to a logical or of all enclosing groups with the enclosed group. Escaped brackets, i.e. \\\\[ and \\\\] are copied verbatim to output. :param string: Format string :param kwargs: keyword arguments providing data for the format string :returns: Formatted string """ |
def build_stack(string):
"""
Builds a stack with OpeningBracket, ClosingBracket and String tokens.
Tokens have a level property denoting their nesting level.
They also have a string property containing associated text (empty for
all tokens but String tokens).
"""
class Token:
string = ""
class OpeningBracket(Token):
pass
class ClosingBracket(Token):
pass
class String(Token):
def __init__(self, str):
self.string = str
TOKENS = {
"[": OpeningBracket,
"]": ClosingBracket,
}
stack = []
# Index of next unconsumed char
next = 0
# Last consumed char
prev = ""
# Current char
char = ""
# Current level
level = 0
while next < len(string):
prev = char
char = string[next]
next += 1
if prev != "\\" and char in TOKENS:
token = TOKENS[char]()
token.index = next
if char == "]":
level -= 1
token.level = level
if char == "[":
level += 1
stack.append(token)
else:
if stack and isinstance(stack[-1], String):
stack[-1].string += char
else:
token = String(char)
token.level = level
stack.append(token)
return stack
def build_tree(items, level=0):
"""
Builds a list-of-lists tree (in forward order) from a stack (reversed order),
and formats the elements on the fly, discarding everything not eligible for
inclusion.
"""
subtree = []
while items:
nested = []
while items[0].level > level:
nested.append(items.pop(0))
if nested:
subtree.append(build_tree(nested, level + 1))
item = items.pop(0)
if item.string:
string = item.string
if level == 0:
subtree.append(string.format(**kwargs))
else:
fields = re.findall(r"({(\w+)[^}]*})", string)
successful_fields = 0
for fieldspec, fieldname in fields:
if kwargs.get(fieldname, False):
successful_fields += 1
if successful_fields == len(fields):
subtree.append(string.format(**kwargs))
else:
return []
return subtree
def merge_tree(items):
return "".join(flatten(items)).replace(r"\]", "]").replace(r"\[", "[")
stack = build_stack(string)
tree = build_tree(stack, 0)
return merge_tree(tree) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require(predicate):
"""Decorator factory for methods requiring a predicate. If the predicate is not fulfilled during a method call, the method call is skipped and None is returned. :param predicate: A callable returning a truth value :returns: Method decorator .. seealso:: :py:class:`internet` """ |
def decorator(method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
if predicate():
return method(*args, **kwargs)
return None
return wrapper
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_graph(values, lower_limit=0.0, upper_limit=100.0, style="blocks"):
""" Draws a graph made of unicode characters. :param values: An array of values to graph. :param lower_limit: Minimum value for the y axis (or None for dynamic). :param upper_limit: Maximum value for the y axis (or None for dynamic). :param style: Drawing style ('blocks', 'braille-fill', 'braille-peak', or 'braille-snake'). :returns: Bar as a string """ |
values = [float(n) for n in values]
mn, mx = min(values), max(values)
mn = mn if lower_limit is None else min(mn, float(lower_limit))
mx = mx if upper_limit is None else max(mx, float(upper_limit))
extent = mx - mn
if style == 'blocks':
bar = '_βββββ
βββ'
bar_count = len(bar) - 1
if extent == 0:
graph = '_' * len(values)
else:
graph = ''.join(bar[int((n - mn) / extent * bar_count)] for n in values)
elif style in ['braille-fill', 'braille-peak', 'braille-snake']:
# idea from https://github.com/asciimoo/drawille
# unicode values from http://en.wikipedia.org/wiki/Braille
vpad = values if len(values) % 2 == 0 else values + [mn]
vscale = [round(4 * (vp - mn) / extent) for vp in vpad]
l = len(vscale) // 2
# do the 2-character collapse separately for clarity
if 'fill' in style:
vbits = [[0, 0x40, 0x44, 0x46, 0x47][vs] for vs in vscale]
elif 'peak' in style:
vbits = [[0, 0x40, 0x04, 0x02, 0x01][vs] for vs in vscale]
else:
assert('snake' in style)
# there are a few choices for what to put last in vb2.
# arguable vscale[-1] from the _previous_ call is best.
vb2 = [vscale[0]] + vscale + [0]
vbits = []
for i in range(1, l + 1):
c = 0
for j in range(min(vb2[i - 1], vb2[i], vb2[i + 1]), vb2[i] + 1):
c |= [0, 0x40, 0x04, 0x02, 0x01][j]
vbits.append(c)
# 2-character collapse
graph = ''
for i in range(0, l, 2):
b1 = vbits[i]
b2 = vbits[i + 1]
if b2 & 0x40:
b2 = b2 - 0x30
b2 = b2 << 3
graph += chr(0x2800 + b1 + b2)
else:
raise NotImplementedError("Graph drawing style '%s' unimplemented." % style)
return graph |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_vertical_bar(percentage, width=1):
""" Draws a vertical bar made of unicode characters. :param value: A value between 0 and 100 :param width: How many characters wide the bar should be. :returns: Bar as a String """ |
bar = ' _βββββ
βββ'
percentage //= 10
percentage = int(percentage)
if percentage < 0:
output = bar[0]
elif percentage >= len(bar):
output = bar[-1]
else:
output = bar[percentage]
return output * width |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_module(function):
"""Function decorator for retrieving the ``self`` argument from the stack. Intended for use with callbacks that need access to a modules variables, for example: .. code:: python from i3pystatus import Status, get_module from i3pystatus.core.command import execute # other modules etc. @get_module def display_ip_verbose(module):
execute('sh -c "ip addr show dev {dev} | xmessage -file -"'.format(dev=module.interface)) status.register("network", interface="wlan1", on_leftclick=display_ip_verbose) """ |
@functools.wraps(function)
def call_wrapper(*args, **kwargs):
stack = inspect.stack()
caller_frame_info = stack[1]
self = caller_frame_info[0].f_locals["self"]
# not completly sure whether this is necessary
# see note in Python docs about stack frames
del stack
function(self, *args, **kwargs)
return call_wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_fundamental_types(self):
"""Registers all fundamental typekind handlers""" |
for _id in range(2, 25):
setattr(self, TypeKind.from_id(_id).name,
self._handle_fundamental_types) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_fundamental_types(self, typ):
""" Handles POD types nodes. see init_fundamental_types for the registration. """ |
ctypesname = self.get_ctypes_name(typ.kind)
if typ.kind == TypeKind.VOID:
size = align = 1
else:
size = typ.get_size()
align = typ.get_align()
return typedesc.FundamentalType(ctypesname, size, align) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def TYPEDEF(self, _cursor_type):
""" Handles TYPEDEF statement. """ |
_decl = _cursor_type.get_declaration()
name = self.get_unique_name(_decl)
if self.is_registered(name):
obj = self.get_registered(name)
else:
log.debug('Was in TYPEDEF but had to parse record declaration for %s', name)
obj = self.parse_cursor(_decl)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ENUM(self, _cursor_type):
""" Handles ENUM typedef. """ |
_decl = _cursor_type.get_declaration()
name = self.get_unique_name(_decl)
if self.is_registered(name):
obj = self.get_registered(name)
else:
log.warning('Was in ENUM but had to parse record declaration ')
obj = self.parse_cursor(_decl)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def POINTER(self, _cursor_type):
""" Handles POINTER types. """ |
#
# FIXME catch InvalidDefinitionError and return a void *
#
#
# we shortcut to canonical typedefs and to pointee canonical defs
comment = None
_type = _cursor_type.get_pointee().get_canonical()
_p_type_name = self.get_unique_name(_type)
# get pointer size
size = _cursor_type.get_size() # not size of pointee
align = _cursor_type.get_align()
log.debug(
"POINTER: size:%d align:%d typ:%s",
size, align, _type.kind)
if self.is_fundamental_type(_type):
p_type = self.parse_cursor_type(_type)
elif self.is_pointer_type(_type) or self.is_array_type(_type):
p_type = self.parse_cursor_type(_type)
elif _type.kind == TypeKind.FUNCTIONPROTO:
p_type = self.parse_cursor_type(_type)
elif _type.kind == TypeKind.FUNCTIONNOPROTO:
p_type = self.parse_cursor_type(_type)
else: # elif _type.kind == TypeKind.RECORD:
# check registration
decl = _type.get_declaration()
decl_name = self.get_unique_name(decl)
# Type is already defined OR will be defined later.
if self.is_registered(decl_name):
p_type = self.get_registered(decl_name)
else: # forward declaration, without looping
log.debug(
'POINTER: %s type was not previously declared',
decl_name)
try:
p_type = self.parse_cursor(decl)
except InvalidDefinitionError as e:
# no declaration in source file. Fake a void *
p_type = typedesc.FundamentalType('None', 1, 1)
comment = "InvalidDefinitionError"
log.debug("POINTER: pointee type_name:'%s'", _p_type_name)
# return the pointer
obj = typedesc.PointerType(p_type, size, align)
obj.location = p_type.location
if comment is not None:
obj.comment = comment
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _array_handler(self, _cursor_type):
""" Handles all array types. Resolves it's element type and makes a Array typedesc. """ |
# The element type has been previously declared
# we need to get the canonical typedef, in some cases
_type = _cursor_type.get_canonical()
size = _type.get_array_size()
if size == -1 and _type.kind == TypeKind.INCOMPLETEARRAY:
size = 0
# FIXME: Incomplete Array handling at end of record.
# https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
# FIXME VARIABLEARRAY DEPENDENTSIZEDARRAY
_array_type = _type.get_array_element_type() # .get_canonical()
if self.is_fundamental_type(_array_type):
_subtype = self.parse_cursor_type(_array_type)
elif self.is_pointer_type(_array_type):
# code.interact(local=locals())
# pointers to POD have no declaration ??
# FIXME test_struct_with_pointer x_n_t g[1]
_subtype = self.parse_cursor_type(_array_type)
elif self.is_array_type(_array_type):
_subtype = self.parse_cursor_type(_array_type)
else:
_subtype_decl = _array_type.get_declaration()
_subtype = self.parse_cursor(_subtype_decl)
# if _subtype_decl.kind == CursorKind.NO_DECL_FOUND:
# pass
#_subtype_name = self.get_unique_name(_subtype_decl)
#_subtype = self.get_registered(_subtype_name)
obj = typedesc.ArrayType(_subtype, size)
obj.location = _subtype.location
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FUNCTIONPROTO(self, _cursor_type):
"""Handles function prototype.""" |
# id, returns, attributes
returns = _cursor_type.get_result()
# if self.is_fundamental_type(returns):
returns = self.parse_cursor_type(returns)
attributes = []
obj = typedesc.FunctionType(returns, attributes)
for i, _attr_type in enumerate(_cursor_type.argument_types()):
arg = typedesc.Argument(
"a%d" %
(i),
self.parse_cursor_type(_attr_type))
obj.add_argument(arg)
self.set_location(obj, None)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FUNCTIONNOPROTO(self, _cursor_type):
"""Handles function with no prototype.""" |
# id, returns, attributes
returns = _cursor_type.get_result()
# if self.is_fundamental_type(returns):
returns = self.parse_cursor_type(returns)
attributes = []
obj = typedesc.FunctionType(returns, attributes)
# argument_types cant be asked. no arguments.
self.set_location(obj, None)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def UNEXPOSED(self, _cursor_type):
""" Handles unexposed types. Returns the canonical type instead. """ |
_decl = _cursor_type.get_declaration()
name = self.get_unique_name(_decl) # _cursor)
if self.is_registered(name):
obj = self.get_registered(name)
else:
obj = self.parse_cursor(_decl)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def INIT_LIST_EXPR(self, cursor):
"""Returns a list of literal values.""" |
values = [self.parse_cursor(child)
for child in list(cursor.get_children())]
return values |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ENUM_CONSTANT_DECL(self, cursor):
"""Gets the enumeration values""" |
name = cursor.displayname
value = cursor.enum_value
pname = self.get_unique_name(cursor.semantic_parent)
parent = self.get_registered(pname)
obj = typedesc.EnumValue(name, value, parent)
parent.add_value(obj)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ENUM_DECL(self, cursor):
"""Gets the enumeration declaration.""" |
name = self.get_unique_name(cursor)
if self.is_registered(name):
return self.get_registered(name)
align = cursor.type.get_align()
size = cursor.type.get_size()
obj = self.register(name, typedesc.Enumeration(name, size, align))
self.set_location(obj, cursor)
self.set_comment(obj, cursor)
# parse all children
for child in cursor.get_children():
self.parse_cursor(child) # FIXME, where is the starElement
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FUNCTION_DECL(self, cursor):
"""Handles function declaration""" |
# FIXME to UT
name = self.get_unique_name(cursor)
if self.is_registered(name):
return self.get_registered(name)
returns = self.parse_cursor_type(cursor.type.get_result())
attributes = []
extern = False
obj = typedesc.Function(name, returns, attributes, extern)
for arg in cursor.get_arguments():
arg_obj = self.parse_cursor(arg)
# if arg_obj is None:
# code.interact(local=locals())
obj.add_argument(arg_obj)
# code.interact(local=locals())
self.register(name, obj)
self.set_location(obj, cursor)
self.set_comment(obj, cursor)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PARM_DECL(self, cursor):
"""Handles parameter declarations.""" |
# try and get the type. If unexposed, The canonical type will work.
_type = cursor.type
_name = cursor.spelling
if (self.is_array_type(_type) or
self.is_fundamental_type(_type) or
self.is_pointer_type(_type) or
self.is_unexposed_type(_type)):
_argtype = self.parse_cursor_type(_type)
else: # FIXME: Which UT/case ? size_t in stdio.h for example.
_argtype_decl = _type.get_declaration()
_argtype_name = self.get_unique_name(_argtype_decl)
if not self.is_registered(_argtype_name):
log.info('This param type is not declared: %s', _argtype_name)
_argtype = self.parse_cursor_type(_type)
else:
_argtype = self.get_registered(_argtype_name)
obj = typedesc.Argument(_name, _argtype)
self.set_location(obj, cursor)
self.set_comment(obj, cursor)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def VAR_DECL(self, cursor):
"""Handles Variable declaration.""" |
# get the name
name = self.get_unique_name(cursor)
log.debug('VAR_DECL: name: %s', name)
# Check for a previous declaration in the register
if self.is_registered(name):
return self.get_registered(name)
# get the typedesc object
_type = self._VAR_DECL_type(cursor)
# transform the ctypes values into ctypeslib
init_value = self._VAR_DECL_value(cursor, _type)
# finished
log.debug('VAR_DECL: _type:%s', _type.name)
log.debug('VAR_DECL: _init:%s', init_value)
log.debug('VAR_DECL: location:%s', getattr(cursor, 'location'))
obj = self.register(name, typedesc.Variable(name, _type, init_value))
self.set_location(obj, cursor)
self.set_comment(obj, cursor)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _VAR_DECL_type(self, cursor):
"""Generates a typedesc object from a Variable declaration.""" |
# Get the type
_ctype = cursor.type.get_canonical()
log.debug('VAR_DECL: _ctype: %s ', _ctype.kind)
# FIXME: Need working int128, long_double, etc.
if self.is_fundamental_type(_ctype):
ctypesname = self.get_ctypes_name(_ctype.kind)
_type = typedesc.FundamentalType(ctypesname, 0, 0)
elif self.is_unexposed_type(_ctype):
st = 'PATCH NEEDED: %s type is not exposed by clang' % (
self.get_unique_name(cursor))
log.error(st)
raise RuntimeError(st)
elif self.is_array_type(_ctype) or _ctype.kind == TypeKind.RECORD:
_type = self.parse_cursor_type(_ctype)
elif self.is_pointer_type(_ctype):
# for example, extern Function pointer
if self.is_unexposed_type(_ctype.get_pointee()):
_type = self.parse_cursor_type(
_ctype.get_canonical().get_pointee())
elif _ctype.get_pointee().kind == TypeKind.FUNCTIONPROTO:
# Function pointers
# Arguments are handled in here
_type = self.parse_cursor_type(_ctype.get_pointee())
else: # Pointer to Fundamental types, structs....
_type = self.parse_cursor_type(_ctype)
else:
# What else ?
raise NotImplementedError(
'What other type of variable? %s' %
(_ctype.kind))
log.debug('VAR_DECL: _type: %s ', _type)
return _type |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _VAR_DECL_value(self, cursor, _type):
"""Handles Variable value initialization.""" |
# always expect list [(k,v)] as init value.from list(cursor.get_children())
# get the init_value and special cases
init_value = self._get_var_decl_init_value(cursor.type,
list(cursor.get_children()))
_ctype = cursor.type.get_canonical()
if self.is_unexposed_type(_ctype):
# string are not exposed
init_value = '%s # UNEXPOSED TYPE. PATCH NEEDED.' % (init_value)
elif (self.is_pointer_type(_ctype) and
_ctype.get_pointee().kind == TypeKind.FUNCTIONPROTO):
# Function pointers argument are handled at type creation time
# but we need to put a CFUNCTYPE as a value of the name variable
init_value = _type
elif self.is_array_type(_ctype):
# an integer litteral will be the size
# an string litteral will be the value
# any list member will be children of a init_list_expr
# FIXME Move that code into typedesc
def countof(k, l):
return [item[0] for item in l].count(k)
if (countof(CursorKind.INIT_LIST_EXPR, init_value) == 1):
init_value = dict(init_value)[CursorKind.INIT_LIST_EXPR]
elif (countof(CursorKind.STRING_LITERAL, init_value) == 1):
# we have a initialised c_array
init_value = dict(init_value)[CursorKind.STRING_LITERAL]
else:
# ignore size alone
init_value = []
# check the array size versus elements.
if _type.size < len(init_value):
_type.size = len(init_value)
elif init_value == []:
# catch case.
init_value = None
else:
log.debug('VAR_DECL: default init_value: %s', init_value)
if len(init_value) > 0:
init_value = init_value[0][1]
return init_value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_var_decl_init_value(self, _ctype, children):
""" Gathers initialisation values by parsing children nodes of a VAR_DECL. """ |
# FIXME TU for INIT_LIST_EXPR
# FIXME: always return [(child.kind,child.value),...]
# FIXME: simplify this redondant code.
init_value = []
children = list(children) # weird requirement, list iterator error.
log.debug('_get_var_decl_init_value: children #: %d', len(children))
for child in children:
# early stop cases.
_tmp = None
try:
_tmp = self._get_var_decl_init_value_single(_ctype, child)
except CursorKindException:
log.debug(
'_get_var_decl_init_value: children init value skip on %s',
child.kind)
continue
if _tmp is not None:
init_value.append(_tmp)
return init_value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_var_decl_init_value_single(self, _ctype, child):
""" Handling of a single child for initialization value. Accepted types are expressions and declarations """ |
init_value = None
# FIXME: always return (child.kind, child.value)
log.debug(
'_get_var_decl_init_value_single: _ctype: %s Child.kind: %s',
_ctype.kind,
child.kind)
# shorcuts.
if not child.kind.is_expression() and not child.kind.is_declaration():
raise CursorKindException(child.kind)
if child.kind == CursorKind.CALL_EXPR:
raise CursorKindException(child.kind)
# POD init values handling.
# As of clang 3.3, int, double literals are exposed.
# float, long double, char , char* are not exposed directly in level1.
# but really it depends...
if child.kind.is_unexposed():
# recurse until we find a literal kind
init_value = self._get_var_decl_init_value(_ctype,
child.get_children())
if len(init_value) == 0:
init_value = None
elif len(init_value) == 1:
init_value = init_value[0]
else:
log.error('_get_var_decl_init_value_single: Unhandled case')
assert len(init_value) <= 1
else: # literal or others
_v = self.parse_cursor(child)
if isinstance(
_v, list) and child.kind not in [CursorKind.INIT_LIST_EXPR, CursorKind.STRING_LITERAL]:
log.warning(
'_get_var_decl_init_value_single: TOKENIZATION BUG CHECK: %s',
_v)
_v = _v[0]
init_value = (child.kind, _v)
log.debug(
'_get_var_decl_init_value_single: returns %s',
str(init_value))
return init_value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _literal_handling(self, cursor):
"""Parse all literal associated with this cursor. Literal handling is usually useful only for initialization values. We can't use a shortcut by getting tokens # init_value = ' '.join([t.spelling for t in children[0].get_tokens() # if t.spelling != ';']) because some literal might need cleaning.""" |
# use a shortcut - does not work on unicode var_decl
# if cursor.kind == CursorKind.STRING_LITERAL:
# value = cursor.displayname
# value = self._clean_string_literal(cursor, value)
# return value
tokens = list(cursor.get_tokens())
log.debug('literal has %d tokens.[ %s ]', len(tokens),
str([str(t.spelling) for t in tokens]))
final_value = []
# code.interact(local=locals())
log.debug('cursor.type:%s', cursor.type.kind.name)
for i, token in enumerate(tokens):
value = token.spelling
log.debug('token:%s tk.kd:%11s tk.cursor.kd:%15s cursor.kd:%15s',
token.spelling, token.kind.name, token.cursor.kind.name,
cursor.kind.name)
# Punctuation is probably not part of the init_value,
# but only in specific case: ';' endl, or part of list_expr
if (token.kind == TokenKind.PUNCTUATION and
(token.cursor.kind == CursorKind.INVALID_FILE or
token.cursor.kind == CursorKind.INIT_LIST_EXPR)):
log.debug('IGNORE token %s', value)
continue
elif token.kind == TokenKind.COMMENT:
log.debug('Ignore comment %s', value)
continue
# elif token.cursor.kind == CursorKind.VAR_DECL:
elif token.location not in cursor.extent:
log.debug(
'FIXME BUG: token.location not in cursor.extent %s',
value)
# FIXME
# there is most probably a BUG in clang or python-clang
# when on #define with no value, a token is taken from
# next line. Which break stuff.
# example:
# #define A
# extern int i;
# // this will give "extern" the last token of Macro("A")
# Lexer is choking ?
# FIXME BUG: token.location not in cursor.extent
# code.interact(local=locals())
continue
# Cleanup specific c-lang or c++ prefix/suffix for POD types.
if token.cursor.kind == CursorKind.INTEGER_LITERAL:
# strip type suffix for constants
value = value.replace('L', '').replace('U', '')
value = value.replace('l', '').replace('u', '')
if value[:2] == '0x' or value[:2] == '0X':
value = '0x%s' % value[2:] # "int(%s,16)"%(value)
else:
value = int(value)
elif token.cursor.kind == CursorKind.FLOATING_LITERAL:
# strip type suffix for constants
value = value.replace('f', '').replace('F', '')
value = float(value)
elif (token.cursor.kind == CursorKind.CHARACTER_LITERAL or
token.cursor.kind == CursorKind.STRING_LITERAL):
value = self._clean_string_literal(token.cursor, value)
elif token.cursor.kind == CursorKind.MACRO_INSTANTIATION:
# get the macro value
value = self.get_registered(value).body
# already cleaned value = self._clean_string_literal(token.cursor, value)
elif token.cursor.kind == CursorKind.MACRO_DEFINITION:
if i == 0:
# ignore, macro name
pass
elif token.kind == TokenKind.LITERAL:
# and just clean it
value = self._clean_string_literal(token.cursor, value)
elif token.kind == TokenKind.IDENTIFIER:
# parse that, try to see if there is another Macro in there.
value = self.get_registered(value).body
# add token
final_value.append(value)
# return the EXPR
# code.interact(local=locals())
if len(final_value) == 1:
return final_value[0]
# Macro definition of a string using multiple macro
if isinstance(final_value, list) and cursor.kind == CursorKind.STRING_LITERAL:
final_value = ''.join(final_value)
return final_value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _operator_handling(self, cursor):
"""Returns a string with the literal that are part of the operation.""" |
values = self._literal_handling(cursor)
retval = ''.join([str(val) for val in values])
return retval |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def STRUCT_DECL(self, cursor, num=None):
""" Handles Structure declaration. Its a wrapper to _record_decl. """ |
return self._record_decl(cursor, typedesc.Structure, num) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def UNION_DECL(self, cursor, num=None):
""" Handles Union declaration. Its a wrapper to _record_decl. """ |
return self._record_decl(cursor, typedesc.Union, num) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fixup_record_bitfields_type(self, s):
"""Fix the bitfield packing issue for python ctypes, by changing the bitfield type, and respecting compiler alignement rules. This method should be called AFTER padding to have a perfect continuous layout. There is one very special case: struct bytes3 { unsigned int b1:23; // 0-23 // 1 bit padding char a2; // 24-32 }; where we would need to actually put a2 in the int32 bitfield. We also need to change the member type to the smallest type possible that can contains the number of bits. Otherwise ctypes has strange bitfield rules packing stuff to the biggest type possible. ** but at the same time, if a bitfield member is from type x, we need to respect that """ |
# phase 1, make bitfield, relying upon padding.
bitfields = []
bitfield_members = []
current_bits = 0
for m in s.members:
if m.is_bitfield:
bitfield_members.append(m)
if m.is_padding:
# compiler says this ends the bitfield
size = current_bits
bitfields.append((size, bitfield_members))
bitfield_members = []
current_bits = 0
else:
# size of padding is not included
current_bits += m.bits
elif len(bitfield_members) == 0:
# no opened bitfield
continue
else:
# we reach the end of the bitfield. Make calculations.
size = current_bits
bitfields.append((size, bitfield_members))
bitfield_members = []
current_bits = 0
if current_bits != 0:
size = current_bits
bitfields.append((size, bitfield_members))
# compilers tend to reduce the size of the bitfield
# to the bf_size
# set the proper type name for the bitfield.
for bf_size, members in bitfields:
name = members[0].type.name
pad_bits = 0
if bf_size <= 8: # use 1 byte - type = char
# prep the padding bitfield size
pad_bits = 8 - bf_size
elif bf_size <= 16: # use 2 byte
pad_bits = 16 - bf_size
elif bf_size <= 32: # use 2 byte
pad_bits = 32 - bf_size
elif bf_size <= 64: # use 2 byte
name = 'c_uint64' # also the 3 bytes + char thing
pad_bits = 64 - bf_size
else:
name = 'c_uint64'
pad_bits = bf_size % 64 - bf_size
# change the type to harmonise the bitfield
log.debug('_fixup_record_bitfield_size: fix type to %s', name)
# set the whole bitfield to the appropriate type size.
for m in members:
m.type.name = name
if m.is_padding:
# this is the last field.
# reduce the size of this padding field to the
m.bits = pad_bits
# and remove padding if the size is 0
if members[-1].is_padding and members[-1].bits == 0:
s.members.remove(members[-1])
# phase 2 - integrate the special 3 Bytes + char fix
for bf_size, members in bitfields:
if True or bf_size == 24:
# we need to check for a 3bytes + char corner case
m = members[-1]
i = s.members.index(m)
if len(s.members) > i + 1:
# has to exists, no arch is aligned on 24 bits.
next_member = s.members[i + 1]
if next_member.bits == 8:
# next_member field is a char.
# it will be aggregated in a 32 bits space
# we need to make it a member of 32bit bitfield
next_member.is_bitfield = True
next_member.comment = "Promoted to bitfield member and type (was char)"
next_member.type = m.type
log.info("%s.%s promoted to bitfield member and type", s.name, next_member.name)
continue
#
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fixup_record(self, s):
"""Fixup padding on a record""" |
log.debug('FIXUP_STRUCT: %s %d bits', s.name, s.size * 8)
if s.members is None:
log.debug('FIXUP_STRUCT: no members')
s.members = []
return
if s.size == 0:
log.debug('FIXUP_STRUCT: struct has size %d', s.size)
return
# try to fix bitfields without padding first
self._fixup_record_bitfields_type(s)
# No need to lookup members in a global var.
# Just fix the padding
members = []
member = None
offset = 0
padding_nb = 0
member = None
prev_member = None
# create padding fields
# DEBUG FIXME: why are s.members already typedesc objet ?
# fields = self.fields[s.name]
for m in s.members: # s.members are strings - NOT
# we need to check total size of bitfield, so to choose the right
# bitfield type
member = m
log.debug('Fixup_struct: Member:%s offsetbits:%d->%d expecting offset:%d',
member.name, member.offset, member.offset + member.bits, offset)
if member.offset < 0:
# FIXME INCOMPLETEARRAY (clang bindings?)
# All fields have offset == -2. No padding will be done.
# But the fields are ordered and code will be produces with typed info.
# so in most cases, it will work. if there is a structure with incompletearray
# and padding or alignement issue, it will produce wrong results
# just exit
return
if member.offset > offset:
# create padding
length = member.offset - offset
log.debug(
'Fixup_struct: create padding for %d bits %d bytes',
length, length // 8)
padding_nb = self._make_padding(
members,
padding_nb,
offset,
length,
prev_member)
if member.type is None:
log.error('FIXUP_STRUCT: %s.type is None', member.name)
members.append(member)
offset = member.offset + member.bits
prev_member = member
# tail padding if necessary
if s.size * 8 != offset:
length = s.size * 8 - offset
log.debug(
'Fixup_struct: s:%d create tail padding for %d bits %d bytes',
s.size, length, length // 8)
padding_nb = self._make_padding(
members,
padding_nb,
offset,
length,
prev_member)
if len(members) > 0:
offset = members[-1].offset + members[-1].bits
# go
s.members = members
log.debug("FIXUP_STRUCT: size:%d offset:%d", s.size * 8, offset)
# if member and not member.is_bitfield:
## self._fixup_record_bitfields_type(s)
# , assert that the last field stop at the size limit
assert offset == s.size * 8
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_padding( self, members, padding_nb, offset, length, prev_member=None):
"""Make padding Fields for a specifed size.""" |
name = 'PADDING_%d' % padding_nb
padding_nb += 1
log.debug("_make_padding: for %d bits", length)
if (length % 8) != 0 or (prev_member is not None and prev_member.is_bitfield):
# add a padding to align with the bitfield type
# then multiple bytes if required.
# pad_length = (length % 8)
typename = prev_member.type.name
padding = typedesc.Field(name,
typedesc.FundamentalType(typename, 1, 1),
# offset, pad_length, is_bitfield=True)
offset, length, is_bitfield=True, is_padding=True)
members.append(padding)
# check for multiple bytes
# if (length//8) > 0:
# padding_nb = self._make_padding(members, padding_nb, offset+pad_length,
# (length//8)*8, prev_member=padding)
return padding_nb
elif length > 8:
pad_bytes = length // 8
padding = typedesc.Field(name,
typedesc.ArrayType(
typedesc.FundamentalType(
self.get_ctypes_name(TypeKind.CHAR_U), length, 1),
pad_bytes),
offset, length, is_padding=True)
members.append(padding)
return padding_nb
# simple char padding
padding = typedesc.Field(name,
typedesc.FundamentalType(
self.get_ctypes_name(
TypeKind.CHAR_U),
1,
1),
offset, length, is_padding=True)
members.append(padding)
return padding_nb |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MACRO_DEFINITION(self, cursor):
""" Parse MACRO_DEFINITION, only present if the TranslationUnit is used with TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD. """ |
# TODO: optionalize macro parsing. It takes a LOT of time.
# ignore system macro
if (not hasattr(cursor, 'location') or cursor.location is None or
cursor.location.file is None):
return False
name = self.get_unique_name(cursor)
# if name == 'A':
# code.interact(local=locals())
# Tokens !!! .kind = {IDENTIFIER, KEYWORD, LITERAL, PUNCTUATION,
# COMMENT ? } etc. see TokenKinds.def
comment = None
tokens = self._literal_handling(cursor)
# Macro name is tokens[0]
# get Macro value(s)
value = True
if isinstance(tokens, list):
if len(tokens) == 2:
value = tokens[1]
else:
# just merge the list of tokens
value = ''.join(tokens[1:])
# macro comment maybe in tokens. Not in cursor.raw_comment
for t in cursor.get_tokens():
if t.kind == TokenKind.COMMENT:
comment = t.spelling
# special case. internal __null
# FIXME, there are probable a lot of others.
# why not Cursor.kind GNU_NULL_EXPR child instead of a token ?
if name == 'NULL' or value == '__null':
value = None
log.debug('MACRO: #define %s %s', tokens[0], value)
obj = typedesc.Macro(name, None, value)
try:
self.register(name, obj)
except DuplicateDefinitionException:
log.info(
'Redefinition of %s %s->%s',
name, self.parser.all[name].args, value)
# HACK
self.parser.all[name] = obj
self.set_location(obj, cursor)
# set the comment in the obj
obj.comment = comment
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_location(self, obj, cursor):
""" Location is also used for codegeneration ordering.""" |
if (hasattr(cursor, 'location') and cursor.location is not None and
cursor.location.file is not None):
obj.location = (cursor.location.file.name, cursor.location.line)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_comment(self, obj, cursor):
""" If a comment is available, add it to the typedesc.""" |
if isinstance(obj, typedesc.T):
obj.comment = cursor.brief_comment
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_python_name(self, name):
"""Transforms an USR into a valid python name.""" |
# FIXME see cindex.SpellingCache
for k, v in [('<', '_'), ('>', '_'), ('::', '__'), (',', ''), (' ', ''),
("$", "DOLLAR"), (".", "DOT"), ("@", "_"), (":", "_"),
('-', '_')]:
if k in name: # template
name = name.replace(k, v)
# FIXME: test case ? I want this func to be neutral on C valid
# names.
if name.startswith("__"):
return "_X" + name
if len(name) == 0:
pass
elif name[0] in "01234567879":
return "_" + name
return name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _make_unknown_name(self, cursor):
'''Creates a name for unname type'''
parent = cursor.lexical_parent
pname = self.get_unique_name(parent)
log.debug('_make_unknown_name: Got parent get_unique_name %s',pname)
# we only look at types declarations
_cursor_decl = cursor.type.get_declaration()
# we had the field index from the parent record, as to differenciate
# between unnamed siblings of a same struct
_i = 0
found = False
# Look at the parent fields to find myself
for m in parent.get_children():
# FIXME: make the good indices for fields
log.debug('_make_unknown_name child %d %s %s %s',_i,m.kind, m.type.kind,m.location)
if m.kind not in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL,
CursorKind.CLASS_DECL]:#,
#CursorKind.FIELD_DECL]:
continue
if m == _cursor_decl:
found = True
break
_i+=1
if not found:
raise NotImplementedError("_make_unknown_name BUG %s"%cursor.location)
# truncate parent name to remove the first part (union or struct)
_premainer = '_'.join(pname.split('_')[1:])
name = '%s_%d'%(_premainer,_i)
return name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_unique_name(self, cursor):
"""get the spelling or create a unique name for a cursor""" |
name = ''
if cursor.kind in [CursorKind.UNEXPOSED_DECL]:
return ''
# covers most cases
name = cursor.spelling
# if its a record decl or field decl and its type is unnamed
if cursor.spelling == '':
# a unnamed object at the root TU
if (cursor.semantic_parent
and cursor.semantic_parent.kind == CursorKind.TRANSLATION_UNIT):
name = self.make_python_name(cursor.get_usr())
log.debug('get_unique_name: root unnamed type kind %s',cursor.kind)
elif cursor.kind in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL,
CursorKind.CLASS_DECL,CursorKind.FIELD_DECL]:
name = self._make_unknown_name(cursor)
log.debug('Unnamed cursor type, got name %s',name)
else:
log.debug('Unnamed cursor, No idea what to do')
#import code
#code.interact(local=locals())
return ''
if cursor.kind in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL,
CursorKind.CLASS_DECL]:
names= {CursorKind.STRUCT_DECL: 'struct',
CursorKind.UNION_DECL: 'union',
CursorKind.CLASS_DECL: 'class',
CursorKind.TYPE_REF: ''}
name = '%s_%s'%(names[cursor.kind],name)
log.debug('get_unique_name: name "%s"',name)
return name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_literal_kind_affinity(self, literal_kind):
''' return the list of fundamental types that are adequate for which
this literal_kind is adequate'''
if literal_kind == CursorKind.INTEGER_LITERAL:
return [TypeKind.USHORT, TypeKind.UINT, TypeKind.ULONG,
TypeKind.ULONGLONG, TypeKind.UINT128,
TypeKind.SHORT, TypeKind.INT, TypeKind.LONG,
TypeKind.LONGLONG, TypeKind.INT128, ]
elif literal_kind == CursorKind.STRING_LITERAL:
return [TypeKind.CHAR16, TypeKind.CHAR32, TypeKind.CHAR_S,
TypeKind.SCHAR, TypeKind.WCHAR] # DEBUG
elif literal_kind == CursorKind.CHARACTER_LITERAL:
return [TypeKind.CHAR_U, TypeKind.UCHAR]
elif literal_kind == CursorKind.FLOATING_LITERAL:
return [TypeKind.FLOAT, TypeKind.DOUBLE, TypeKind.LONGDOUBLE]
elif literal_kind == CursorKind.IMAGINARY_LITERAL:
return []
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_newer(source, target):
"""Return true if 'source' exists and is more recently modified than 'target', or if 'source' exists and 'target' doesn't. Return false if both exist and 'target' is the same age or younger than 'source'. Raise ValueError if 'source' does not exist. """ |
if not os.path.exists(source):
raise ValueError("file '%s' does not exist" % source)
if not os.path.exists(target):
return 1
from stat import ST_MTIME
mtime1 = os.stat(source)[ST_MTIME]
mtime2 = os.stat(target)[ST_MTIME]
return mtime1 > mtime2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def startElement(self, node):
"""Recurses in children of this node""" |
if node is None:
return
if self.__filter_location is not None:
# dont even parse includes.
# FIXME: go back on dependencies ?
if node.location.file is None:
return
elif node.location.file.name not in self.__filter_location:
return
# find and call the handler for this element
log.debug(
'%s:%d: Found a %s|%s|%s',
node.location.file,
node.location.line,
node.kind.name,
node.displayname,
node.spelling)
# build stuff.
try:
stop_recurse = self.parse_cursor(node)
# Signature of parse_cursor is:
# if the fn returns True, do not recurse into children.
# anything else will be ignored.
if stop_recurse is not False: # True:
return
# if fn returns something, if this element has children, treat
# them.
for child in node.get_children():
self.startElement(child)
except InvalidDefinitionError:
# if the definition is invalid
pass
# startElement returns None.
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, name, obj):
"""Registers an unique type description""" |
if name in self.all:
log.debug('register: %s already existed: %s', name, obj.name)
# code.interact(local=locals())
raise DuplicateDefinitionException(
'register: %s already existed: %s' % (name, obj.name))
log.debug('register: %s ', name)
self.all[name] = obj
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_tu(source, lang='c', all_warnings=False, flags=None):
"""Obtain a translation unit from source and language. By default, the translation unit is created from source file "t.<ext>" where <ext> is the default file extension for the specified language. By default it is C, so "t.c" is the default file name. Supported languages are {c, cpp, objc}. all_warnings is a convenience argument to enable all compiler warnings. """ |
args = list(flags or [])
name = 't.c'
if lang == 'cpp':
name = 't.cpp'
args.append('-std=c++11')
elif lang == 'objc':
name = 't.m'
elif lang != 'c':
raise Exception('Unknown language: %s' % lang)
if all_warnings:
args += ['-Wall', '-Wextra']
return TranslationUnit.from_source(name, args, unsaved_files=[(name,
source)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_cursor(source, spelling):
"""Obtain a cursor from a source object. This provides a convenient search mechanism to find a cursor with specific spelling within a source. The first argument can be either a TranslationUnit or Cursor instance. If the cursor is not found, None is returned. """ |
children = []
if isinstance(source, Cursor):
children = source.get_children()
else:
# Assume TU
children = source.cursor.get_children()
for cursor in children:
if cursor.spelling == spelling:
return cursor
# Recurse into children.
result = get_cursor(cursor, spelling)
if result is not None:
return result
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_cursors(source, spelling):
"""Obtain all cursors from a source object with a specific spelling. This provides a convenient search mechanism to find all cursors with specific spelling within a source. The first argument can be either a TranslationUnit or Cursor instance. If no cursors are found, an empty list is returned. """ |
cursors = []
children = []
if isinstance(source, Cursor):
children = source.get_children()
else:
# Assume TU
children = source.cursor.get_children()
for cursor in children:
if cursor.spelling == spelling:
cursors.append(cursor)
# Recurse into children.
cursors.extend(get_cursors(cursor, spelling))
return cursors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_fundamental_type_wrappers(self):
""" If a type is a int128, a long_double_t or a void, some placeholders need to be in the generated code to be valid. """ |
# 2015-01 reactivating header templates
#log.warning('enable_fundamental_type_wrappers deprecated - replaced by generate_headers')
# return # FIXME ignore
self.enable_fundamental_type_wrappers = lambda: True
import pkgutil
headers = pkgutil.get_data(
'ctypeslib',
'data/fundamental_type_name.tpl').decode()
from clang.cindex import TypeKind
size = str(self.parser.get_ctypes_size(TypeKind.LONGDOUBLE) // 8)
headers = headers.replace('__LONG_DOUBLE_SIZE__', size)
print(headers, file=self.imports)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_pointer_type(self):
""" If a type is a pointer, a platform-independent POINTER_T type needs to be in the generated code. """ |
# 2015-01 reactivating header templates
#log.warning('enable_pointer_type deprecated - replaced by generate_headers')
# return # FIXME ignore
self.enable_pointer_type = lambda: True
import pkgutil
headers = pkgutil.get_data('ctypeslib', 'data/pointer_type.tpl').decode()
import ctypes
from clang.cindex import TypeKind
# assuming a LONG also has the same sizeof than a pointer.
word_size = self.parser.get_ctypes_size(TypeKind.POINTER) // 8
word_type = self.parser.get_ctypes_name(TypeKind.ULONG)
# pylint: disable=protected-access
word_char = getattr(ctypes, word_type)._type_
# replacing template values
headers = headers.replace('__POINTER_SIZE__', str(word_size))
headers = headers.replace('__REPLACEMENT_TYPE__', word_type)
headers = headers.replace('__REPLACEMENT_TYPE_CHAR__', word_char)
print(headers, file=self.imports)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Alias(self, alias):
"""Handles Aliases. No test cases yet""" |
# FIXME
if self.generate_comments:
self.print_comment(alias)
print("%s = %s # alias" % (alias.name, alias.alias), file=self.stream)
self._aliases += 1
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_undeclared_type(self, item):
""" Checks if a typed has already been declared in the python output or is a builtin python type. """ |
if item in self.done:
return None
if isinstance(item, typedesc.FundamentalType):
return None
if isinstance(item, typedesc.PointerType):
return self.get_undeclared_type(item.typ)
if isinstance(item, typedesc.ArrayType):
return self.get_undeclared_type(item.typ)
# else its an undeclared structure.
return item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FundamentalType(self, _type):
"""Returns the proper ctypes class name for a fundamental type 1) activates generation of appropriate headers for ## int128_t ## c_long_double_t 2) return appropriate name for type """ |
log.debug('HERE in FundamentalType for %s %s', _type, _type.name)
if _type.name in ["None", "c_long_double_t", "c_uint128", "c_int128"]:
self.enable_fundamental_type_wrappers()
return _type.name
return "ctypes.%s" % (_type.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate(self, item, *args):
""" wraps execution of specific methods.""" |
if item in self.done:
return
# verbose output with location.
if self.generate_locations and item.location:
print("# %s:%d" % item.location, file=self.stream)
if self.generate_comments:
self.print_comment(item)
log.debug("generate %s, %s", item.__class__.__name__, item.name)
#
#log.debug('generate: %s( %s )', type(item).__name__, name)
#if name in self.known_symbols:
# log.debug('item is in known_symbols %s'% name )
# mod = self.known_symbols[name]
# print >> self.imports, "from %s import %s" % (mod, name)
# self.done.add(item)
# if isinstance(item, typedesc.Structure):
# self.done.add(item.get_head())
# self.done.add(item.get_body())
# return
#
# to avoid infinite recursion, we have to mark it as done
# before actually generating the code.
self.done.add(item)
# go to specific treatment
mth = getattr(self, type(item).__name__)
mth(item, *args)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def example():
"""Plot random phase and Gaussian random variable spectra.""" |
ldata = 200
degrees = np.arange(ldata+1, dtype=float)
degrees[0] = np.inf
power = degrees**(-1)
clm1 = pyshtools.SHCoeffs.from_random(power, exact_power=False)
clm2 = pyshtools.SHCoeffs.from_random(power, exact_power=True)
fig, ax = plt.subplots()
ax.plot(clm1.spectrum(unit='per_l'), label='Normal distributed power')
ax.plot(clm2.spectrum(unit='per_l'), label='Exact power')
ax.set(xscale='log', yscale='log', xlabel='degree l',
ylabel='power per degree l')
ax.grid(which='both')
ax.legend()
plt.show() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_rad(self, colorbar=True, cb_orientation='vertical', cb_label='$g_r$, m s$^{-2}$', ax=None, show=True, fname=None, **kwargs):
""" Plot the radial component of the gravity field. Usage ----- x.plot_rad([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$g_r$, m s$^{-2}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ |
if ax is None:
fig, axes = self.rad.plot(colorbar=colorbar,
cb_orientation=cb_orientation,
cb_label=cb_label, show=False, **kwargs)
if show:
fig.show()
if fname is not None:
fig.savefig(fname)
return fig, axes
else:
self.rad.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_theta(self, colorbar=True, cb_orientation='vertical', cb_label='$g_\\theta$, m s$^{-2}$', ax=None, show=True, fname=None, **kwargs):
""" Plot the theta component of the gravity field. Usage ----- x.plot_theta([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$g_\\theta$, m s$^{-2}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ |
if ax is None:
fig, axes = self.theta.plot(colorbar=colorbar,
cb_orientation=cb_orientation,
cb_label=cb_label, show=False,
**kwargs)
if show:
fig.show()
if fname is not None:
fig.savefig(fname)
return fig, axes
else:
self.theta.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_phi(self, colorbar=True, cb_orientation='vertical', cb_label='$g_\phi$, m s$^{-2}$', ax=None, show=True, fname=None, **kwargs):
""" Plot the phi component of the gravity field. Usage ----- x.plot_phi([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$g_\phi$, m s$^{-2}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ |
if ax is None:
fig, axes = self.phi.plot(colorbar=colorbar,
cb_orientation=cb_orientation,
cb_label=cb_label, show=False, **kwargs)
if show:
fig.show()
if fname is not None:
fig.savefig(fname)
return fig, axes
else:
self.phi.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_total(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs):
""" Plot the total gravity disturbance. Usage ----- x.plot_total([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = 'gravity disturbance' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. Notes ----- If the normal gravity is removed from the total gravitational acceleration, the output will be displayed in mGals. """ |
if self.normal_gravity is True:
if cb_label is None:
cb_label = 'Gravity disturbance, mGal'
else:
if cb_label is None:
cb_label = 'Gravity disturbance, m s$^{-2}$'
if ax is None:
if self.normal_gravity is True:
fig, axes = (self.total*1.e5).plot(
colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, show=False, **kwargs)
else:
fig, axes = self.total.plot(
colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, show=False, **kwargs)
if show:
fig.show()
if fname is not None:
fig.savefig(fname)
return fig, axes
else:
if self.normal_gravity is True:
(self.total*1.e5).plot(
colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs)
else:
self.total.plot(
colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_pot(self, colorbar=True, cb_orientation='vertical', cb_label='Potential, m$^2$ s$^{-2}$', ax=None, show=True, fname=None, **kwargs):
""" Plot the gravitational potential. Usage ----- x.plot_pot([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = 'potential, m s$^{-1}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ |
if ax is None:
fig, axes = self.pot.plot(colorbar=colorbar,
cb_orientation=cb_orientation,
cb_label=cb_label, show=False, **kwargs)
if show:
fig.show()
if fname is not None:
fig.savefig(fname)
return fig, axes
else:
self.pot.plot(colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(self, colorbar=True, cb_orientation='horizontal', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs):
""" Plot the three vector components of the gravity field and the gravity disturbance. Usage ----- x.plot([tick_interval, minor_tick_interval, xlabel, ylabel, colorbar, cb_orientation, cb_label, axes_labelsize, tick_labelsize, show, fname, **kwargs]) Parameters tick_interval : list or tuple, optional, default = [60, 60] Intervals to use when plotting the major x and y ticks. If set to None, major ticks will not be plotted. minor_tick_interval : list or tuple, optional, default = [20, 20] Intervals to use when plotting the minor x and y ticks. If set to None, minor ticks will not be plotted. xlabel : str, optional, default = 'Longitude' Label for the longitude axis. ylabel : str, optional, default = 'Latitude' Label for the latitude axis. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = None Text label for the colorbar. axes_labelsize : int, optional, default = 9 The font size for the x and y axes labels. tick_labelsize : int, optional, default = 8 The font size for the x and y tick labels. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ |
if colorbar is True:
if cb_orientation == 'horizontal':
scale = 0.8
else:
scale = 0.5
else:
scale = 0.6
figsize = (_mpl.rcParams['figure.figsize'][0],
_mpl.rcParams['figure.figsize'][0] * scale)
fig, ax = _plt.subplots(2, 2, figsize=figsize)
self.plot_rad(colorbar=colorbar, cb_orientation=cb_orientation,
ax=ax.flat[0], tick_interval=tick_interval,
xlabel=xlabel, ylabel=ylabel,
axes_labelsize=axes_labelsize,
tick_labelsize=tick_labelsize,
minor_tick_interval=minor_tick_interval,
**kwargs)
self.plot_theta(colorbar=colorbar, cb_orientation=cb_orientation,
ax=ax.flat[1], tick_interval=tick_interval,
xlabel=xlabel, ylabel=ylabel,
axes_labelsize=axes_labelsize,
tick_labelsize=tick_labelsize,
minor_tick_interval=minor_tick_interval,
**kwargs)
self.plot_phi(colorbar=colorbar, cb_orientation=cb_orientation,
ax=ax.flat[2], tick_interval=tick_interval,
xlabel=xlabel, ylabel=ylabel,
axes_labelsize=axes_labelsize,
minor_tick_interval=minor_tick_interval,
tick_labelsize=tick_labelsize,**kwargs)
self.plot_total(colorbar=colorbar, cb_orientation=cb_orientation,
ax=ax.flat[3], tick_interval=tick_interval,
xlabel=xlabel, ylabel=ylabel,
axes_labelsize=axes_labelsize,
tick_labelsize=tick_labelsize,
minor_tick_interval=minor_tick_interval,
**kwargs)
fig.tight_layout(pad=0.5)
if show:
fig.show()
if fname is not None:
fig.savefig(fname)
return fig, ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand(self, nmax=None, grid='DH2', zeros=None):
""" Expand the function on a grid using the first n Slepian coefficients. Usage ----- f = x.expand([nmax, grid, zeros]) Returns ------- f : SHGrid class instance Parameters nmax : int, optional, default = x.nmax The number of expansion coefficients to use when calculating the spherical harmonic coefficients. grid : str, optional, default = 'DH2' 'DH' or 'DH1' for an equisampled lat/lon grid with nlat=nlon, 'DH2' for an equidistant lat/lon grid with nlon=2*nlat, or 'GLQ' for a Gauss-Legendre quadrature grid. zeros : ndarray, optional, default = None The cos(colatitude) nodes used in the Gauss-Legendre Quadrature grids. """ |
if type(grid) != str:
raise ValueError('grid must be a string. ' +
'Input type was {:s}'
.format(str(type(grid))))
if nmax is None:
nmax = self.nmax
if self.galpha.kind == 'cap':
shcoeffs = _shtools.SlepianCoeffsToSH(self.falpha,
self.galpha.coeffs, nmax)
else:
shcoeffs = _shtools.SlepianCoeffsToSH(self.falpha,
self.galpha.tapers, nmax)
if grid.upper() in ('DH', 'DH1'):
gridout = _shtools.MakeGridDH(shcoeffs, sampling=1,
norm=1, csphase=1)
return SHGrid.from_array(gridout, grid='DH', copy=False)
elif grid.upper() == 'DH2':
gridout = _shtools.MakeGridDH(shcoeffs, sampling=2,
norm=1, csphase=1)
return SHGrid.from_array(gridout, grid='DH', copy=False)
elif grid.upper() == 'GLQ':
if zeros is None:
zeros, weights = _shtools.SHGLQ(self.galpha.lmax)
gridout = _shtools.MakeGridGLQ(shcoeffs, zeros,
norm=1, csphase=1)
return SHGrid.from_array(gridout, grid='GLQ', copy=False)
else:
raise ValueError(
"grid must be 'DH', 'DH1', 'DH2', or 'GLQ'. " +
"Input value was {:s}".format(repr(grid))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_shcoeffs(self, nmax=None, normalization='4pi', csphase=1):
""" Return the spherical harmonic coefficients using the first n Slepian coefficients. Usage ----- s = x.to_shcoeffs([nmax]) Returns ------- s : SHCoeffs class instance The spherical harmonic coefficients obtained from using the first n Slepian expansion coefficients. Parameters nmax : int, optional, default = x.nmax The maximum number of expansion coefficients to use when calculating the spherical harmonic coefficients. normalization : str, optional, default = '4pi' Normalization of the output class: '4pi', 'ortho' or 'schmidt' for geodesy 4pi-normalized, orthonormalized, or Schmidt semi-normalized coefficients, respectively. csphase : int, optional, default = 1 Condon-Shortley phase convention: 1 to exclude the phase factor, or -1 to include it. """ |
if type(normalization) != str:
raise ValueError('normalization must be a string. ' +
'Input type was {:s}'
.format(str(type(normalization))))
if normalization.lower() not in set(['4pi', 'ortho', 'schmidt']):
raise ValueError(
"normalization must be '4pi', 'ortho' " +
"or 'schmidt'. Provided value was {:s}"
.format(repr(normalization))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be 1 or -1. Input value was {:s}"
.format(repr(csphase))
)
if nmax is None:
nmax = self.nmax
if self.galpha.kind == 'cap':
shcoeffs = _shtools.SlepianCoeffsToSH(self.falpha,
self.galpha.coeffs, nmax)
else:
shcoeffs = _shtools.SlepianCoeffsToSH(self.falpha,
self.galpha.tapers, nmax)
temp = SHCoeffs.from_array(shcoeffs, normalization='4pi', csphase=1)
if normalization != '4pi' or csphase != 1:
return temp.convert(normalization=normalization, csphase=csphase)
else:
return temp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _shtools_status_message(status):
'''
Determine error message to print when a SHTOOLS Fortran 95 routine exits
improperly.
'''
if (status == 1):
errmsg = 'Improper dimensions of input array.'
elif (status == 2):
errmsg = 'Improper bounds for input variable.'
elif (status == 3):
errmsg = 'Error allocating memory.'
elif (status == 4):
errmsg = 'File IO error.'
else:
errmsg = 'Unhandled Fortran 95 error.'
return errmsg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_cap(cls, theta, lmax, clat=None, clon=None, nmax=None, theta_degrees=True, coord_degrees=True, dj_matrix=None):
""" Construct spherical cap Slepian functions. Usage ----- x = Slepian.from_cap(theta, lmax, [clat, clon, nmax, theta_degrees, coord_degrees, dj_matrix]) Returns ------- x : Slepian class instance Parameters theta : float Angular radius of the spherical-cap localization domain (default in degrees). lmax : int Spherical harmonic bandwidth of the Slepian functions. clat, clon : float, optional, default = None Latitude and longitude of the center of the rotated spherical-cap Slepian functions (default in degrees). nmax : int, optional, default (lmax+1)**2 Number of Slepian functions to compute. theta_degrees : bool, optional, default = True True if theta is in degrees. coord_degrees : bool, optional, default = True True if clat and clon are in degrees. dj_matrix : ndarray, optional, default = None The djpi2 rotation matrix computed by a call to djpi2. """ |
if theta_degrees:
tapers, eigenvalues, taper_order = _shtools.SHReturnTapers(
_np.radians(theta), lmax)
else:
tapers, eigenvalues, taper_order = _shtools.SHReturnTapers(
theta, lmax)
return SlepianCap(theta, tapers, eigenvalues, taper_order, clat, clon,
nmax, theta_degrees, coord_degrees, dj_matrix,
copy=False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_mask(cls, dh_mask, lmax, nmax=None):
""" Construct Slepian functions that are optimally concentrated within the region specified by a mask. Usage ----- x = Slepian.from_mask(dh_mask, lmax, [nmax]) Returns ------- x : Slepian class instance Parameters dh_mask :ndarray, shape (nlat, nlon) A Driscoll and Healy (1994) sampled grid describing the concentration region R. All elements should either be 1 (for inside the concentration region) or 0 (for outside the concentration region). The grid must have dimensions nlon=nlat or nlon=2*nlat, where nlat is even. lmax : int The spherical harmonic bandwidth of the Slepian functions. nmax : int, optional, default = (lmax+1)**2 The number of best-concentrated eigenvalues and eigenfunctions to return. """ |
if nmax is None:
nmax = (lmax + 1)**2
else:
if nmax > (lmax + 1)**2:
raise ValueError('nmax must be less than or equal to ' +
'(lmax + 1)**2. lmax = {:d} and nmax = {:d}'
.format(lmax, nmax))
if dh_mask.shape[0] % 2 != 0:
raise ValueError('The number of latitude bands in dh_mask ' +
'must be even. nlat = {:d}'
.format(dh_mask.shape[0]))
if dh_mask.shape[1] == dh_mask.shape[0]:
_sampling = 1
elif dh_mask.shape[1] == 2 * dh_mask.shape[0]:
_sampling = 2
else:
raise ValueError('dh_mask must be dimensioned as (n, n) or ' +
'(n, 2 * n). Input shape is ({:d}, {:d})'
.format(dh_mask.shape[0], dh_mask.shape[1]))
mask_lm = _shtools.SHExpandDH(dh_mask, sampling=_sampling, lmax_calc=0)
area = mask_lm[0, 0, 0] * 4 * _np.pi
tapers, eigenvalues = _shtools.SHReturnTapersMap(dh_mask, lmax,
ntapers=nmax)
return SlepianMask(tapers, eigenvalues, area, copy=False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand(self, flm, nmax=None):
""" Return the Slepian expansion coefficients of the input function. Usage ----- s = x.expand(flm, [nmax]) Returns ------- s : SlepianCoeff class instance The Slepian expansion coefficients of the input function. Parameters flm : SHCoeffs class instance The input function to expand in Slepian functions. nmax : int, optional, default = (x.lmax+1)**2 The number of Slepian expansion coefficients to compute. Description The global function f is input using its spherical harmonic expansion coefficients flm. The expansion coefficients of the function f using Slepian functions g is given by f_alpha = sum_{lm}^{lmax} f_lm g(alpha)_lm """ |
if nmax is None:
nmax = (self.lmax+1)**2
elif nmax is not None and nmax > (self.lmax+1)**2:
raise ValueError(
"nmax must be less than or equal to (lmax+1)**2 " +
"where lmax is {:s}. Input value is {:s}"
.format(repr(self.lmax), repr(nmax))
)
coeffsin = flm.to_array(normalization='4pi', csphase=1, lmax=self.lmax)
return self._expand(coeffsin, nmax) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spectra(self, alpha=None, nmax=None, convention='power', unit='per_l', base=10.):
""" Return the spectra of one or more Slepian functions. Usage ----- spectra = x.spectra([alpha, nmax, convention, unit, base]) Returns ------- spectra : ndarray, shape (lmax+1, nmax) A matrix with each column containing the spectrum of a Slepian function, and where the functions are arranged with increasing concentration factors. If alpha is set, only a single vector is returned, whereas if nmax is set, the first nmax spectra are returned. Parameters alpha : int, optional, default = None The function number of the output spectrum, where alpha=0 corresponds to the best concentrated Slepian function. nmax : int, optional, default = 1 The number of best concentrated Slepian function power spectra to return. convention : str, optional, default = 'power' The type of spectrum to return: 'power' for power spectrum, 'energy' for energy spectrum, and 'l2norm' for the l2 norm spectrum. unit : str, optional, default = 'per_l' If 'per_l', return the total contribution to the spectrum for each spherical harmonic degree l. If 'per_lm', return the average contribution to the spectrum for each coefficient at spherical harmonic degree l. If 'per_dlogl', return the spectrum per log interval dlog_a(l). base : float, optional, default = 10. The logarithm base when calculating the 'per_dlogl' spectrum. Description This function returns either the power spectrum, energy spectrum, or l2-norm spectrum of one or more of the Slepian funtions. Total power is defined as the integral of the function squared over all space, divided by the area the function spans. If the mean of the function is zero, this is equivalent to the variance of the function. The total energy is the integral of the function squared over all space and is 4pi times the total power. The l2-norm is the sum of the magnitude of the coefficients squared. The output spectrum can be expresed using one of three units. 'per_l' returns the contribution to the total spectrum from all angular orders at degree l. 'per_lm' returns the average contribution to the total spectrum from a single coefficient at degree l. The 'per_lm' spectrum is equal to the 'per_l' spectrum divided by (2l+1). 'per_dlogl' returns the contribution to the total spectrum from all angular orders over an infinitessimal logarithmic degree band. The contrubution in the band dlog_a(l) is spectrum(l, 'per_dlogl')*dlog_a(l), where a is the base, and where spectrum(l, 'per_dlogl) is equal to spectrum(l, 'per_l')*l*log(a). """ |
if alpha is None:
if nmax is None:
nmax = self.nmax
spectra = _np.zeros((self.lmax+1, nmax))
for iwin in range(nmax):
coeffs = self.to_array(iwin)
spectra[:, iwin] = _spectrum(coeffs, normalization='4pi',
convention=convention, unit=unit,
base=base)
else:
coeffs = self.to_array(alpha)
spectra = _spectrum(coeffs, normalization='4pi',
convention=convention, unit=unit, base=base)
return spectra |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _taper2coeffs(self, alpha):
""" Return the spherical harmonic coefficients of the unrotated Slepian function i as an array, where i = 0 is the best concentrated function. """ |
taperm = self.orders[alpha]
coeffs = _np.zeros((2, self.lmax + 1, self.lmax + 1))
if taperm < 0:
coeffs[1, :, abs(taperm)] = self.tapers[:, alpha]
else:
coeffs[0, :, abs(taperm)] = self.tapers[:, alpha]
return coeffs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_total(self, colorbar=True, cb_orientation='vertical', cb_label='$|B|$, nT', ax=None, show=True, fname=None, **kwargs):
""" Plot the total magnetic intensity. Usage ----- x.plot_total([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$|B|$, nT' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ |
if ax is None:
fig, axes = self.total.plot(
colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, show=False, **kwargs)
if show:
fig.show()
if fname is not None:
fig.savefig(fname)
return fig, axes
else:
self.total.plot(
colorbar=colorbar, cb_orientation=cb_orientation,
cb_label=cb_label, ax=ax, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spharm_lm(l, m, theta, phi, normalization='4pi', kind='real', csphase=1, degrees=True):
""" Compute the spherical harmonic function for a specific degree and order. Usage ----- ylm = spharm (l, m, theta, phi, [normalization, kind, csphase, degrees]) Returns ------- ylm : float or complex The spherical harmonic function ylm, where l and m are the spherical harmonic degree and order, respectively. Parameters l : integer The spherical harmonic degree. m : integer The spherical harmonic order. theta : float The colatitude in degrees. phi : float The longitude in degrees. normalization : str, optional, default = '4pi' '4pi', 'ortho', 'schmidt', or 'unnorm' for geodesy 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. kind : str, optional, default = 'real' 'real' or 'complex' spherical harmonic coefficients. csphase : optional, integer, default = 1 If 1 (default), the Condon-Shortley phase will be excluded. If -1, the Condon-Shortley phase of (-1)^m will be appended to the spherical harmonic functions. degrees : optional, bool, default = True If True, colat and phi are expressed in degrees. Description spharm_lm will calculate the spherical harmonic function for a specific degree l and order m, and for a given colatitude theta and longitude phi. Three parameters determine how the spherical harmonic functions are defined. normalization can be either '4pi' (default), 'ortho', 'schmidt', or 'unnorm' for 4pi normalized, orthonormalized, Schmidt semi-normalized, or unnormalized spherical harmonic functions, respectively. kind can be either 'real' or 'complex', and csphase determines whether to include or exclude (default) the Condon-Shortley phase factor. The spherical harmonic functions are calculated using the standard three-term recursion formula, and in order to prevent overflows, the scaling approach of Holmes and Featherstone (2002) is utilized. The resulting functions are accurate to about degree 2800. See Wieczorek and Meschede (2018) for exact definitions on how the spherical harmonic functions are defined. References Holmes, S. A., and W. E. Featherstone, A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions, J. Geodesy, 76, 279-299, doi:10.1007/s00190-002-0216-2, 2002. Wieczorek, M. A., and M. Meschede. SHTools β Tools for working with spherical harmonics, Geochem., Geophys., Geosyst., 19, 2574-2592, doi:10.1029/2018GC007529, 2018. """ |
if l < 0:
raise ValueError(
"The degree l must be greater or equal than 0. Input value was {:s}."
.format(repr(l))
)
if m > l:
raise ValueError(
"The order m must be less than or equal to the degree l. " +
"Input values were l={:s} and m={:s}.".format(repr(l), repr(m))
)
if normalization.lower() not in ('4pi', 'ortho', 'schmidt', 'unnorm'):
raise ValueError(
"The normalization must be '4pi', 'ortho', 'schmidt', " +
"or 'unnorm'. Input value was {:s}."
.format(repr(normalization))
)
if kind.lower() not in ('real', 'complex'):
raise ValueError(
"kind must be 'real' or 'complex'. " +
"Input value was {:s}.".format(repr(kind))
)
if csphase != 1 and csphase != -1:
raise ValueError(
"csphase must be either 1 or -1. Input value was {:s}."
.format(repr(csphase))
)
if normalization.lower() == 'unnorm' and lmax > 85:
_warnings.warn("Calculations using unnormalized coefficients " +
"are stable only for degrees less than or equal " +
"to 85. lmax for the coefficients will be set to " +
"85. Input value was {:d}.".format(lmax),
category=RuntimeWarning)
lmax = 85
ind = (l*(l+1))//2 + abs(m)
if degrees is True:
theta = _np.deg2rad(theta)
phi = _np.deg2rad(phi)
if kind.lower() == 'real':
p = _legendre(l, _np.cos(theta), normalization=normalization,
csphase=csphase, cnorm=0, packed=True)
if m >= 0:
ylm = p[ind] * _np.cos(m*phi)
else:
ylm = p[ind] * _np.sin(abs(m)*phi)
else:
p = _legendre(l, _np.cos(theta), normalization=normalization,
csphase=csphase, cnorm=1, packed=True)
ylm = p[ind] * (_np.cos(m*phi) + 1j * _np.sin(abs(m)*phi)) # Yl|m|
if m < 0:
ylm = ylm.conj()
if _np.mod(m, 2) == 1:
ylm = - ylm
return ylm |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_coeffs(self, values, ls, ms):
""" Set spherical harmonic coefficients in-place to specified values. Usage ----- x.set_coeffs(values, ls, ms) Parameters values : float (list) The value(s) of the spherical harmonic coefficient(s). ls : int (list) The degree(s) of the coefficient(s) that should be set. ms : int (list) The order(s) of the coefficient(s) that should be set. Positive and negative values correspond to the cosine and sine components, respectively. Examples -------- x.set_coeffs(10., 1, 1) # x.coeffs[0, 1, 1] = 10. x.set_coeffs(5., 1, -1) # x.coeffs[1, 1, 1] = 5. x.set_coeffs([1., 2], [1, 2], [0, -2]) # x.coeffs[0, 1, 0] = 1. # x.coeffs[1, 2, 2] = 2. """ |
# Ensure that the type is correct
values = _np.array(values)
ls = _np.array(ls)
ms = _np.array(ms)
mneg_mask = (ms < 0).astype(_np.int)
self.coeffs[mneg_mask, ls, _np.abs(ms)] = values |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.