Search is not available for this dataset
text stringlengths 75 104k |
|---|
def positionErrorSkyAvg(G, vmini, extension=0.0):
"""
Calculate the sky averaged position errors from G and (V-I).
NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR
SIMULATED ASTROMETRY IS ALSO ON THE ICRS.
Parameters
----------
G - Value(s) of ... |
def positionMinError(G, vmini, extension=0.0):
"""
Calculate the minimum position errors from G and (V-I). These correspond to the sky regions with the
smallest astrometric errors.
NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR
SIMULATED ASTROMETRY IS ... |
def positionMaxError(G, vmini, extension=0.0):
"""
Calculate the maximum position errors from G and (V-I). These correspond to the sky regions with the
largest astrometric errors.
NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR
SIMULATED ASTROMETRY IS A... |
def positionError(G, vmini, beta, extension=0.0):
"""
Calculate the position errors from G and (V-I) and the Ecliptic latitude beta of the source.
NOTE! THE ERRORS ARE FOR SKY POSITIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE YOUR
SIMULATED ASTROMETRY IS ALSO ON THE ICRS.
Parameters
--... |
def properMotionMinError(G, vmini, extension=0.0):
"""
Calculate the minimum proper motion errors from G and (V-I). These correspond to the sky regions with
the smallest astrometric errors.
NOTE! THE ERRORS ARE FOR PROPER MOTIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE
YOUR SIMULATED ASTR... |
def properMotionMaxError(G, vmini, extension=0.0):
"""
Calculate the maximum proper motion errors from G and (V-I). These correspond to the sky regions with
the largest astrometric errors.
NOTE! THE ERRORS ARE FOR PROPER MOTIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE
YOUR SIMULATED ASTRO... |
def properMotionError(G, vmini, beta, extension=0.0):
"""
Calculate the proper motion errors from G and (V-I) and the Ecliptic latitude beta of the source.
NOTE! THE ERRORS ARE FOR PROPER MOTIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE
YOUR SIMULATED ASTROMETRY IS ALSO ON THE ICRS.
Param... |
def totalProperMotionErrorSkyAvg(G, vmini, extension=0.0):
"""
Calculate the sky averaged total proper motion error from G and (V-I). This refers to the error on the
length of the proper motion vector.
NOTE! THE ERRORS ARE FOR PROPER MOTIONS IN THE ICRS (I.E., RIGHT ASCENSION, DECLINATION). MAKE SURE
YOUR SI... |
def makePlot(args):
"""
Make the plot with parallax horizons. The plot shows V-band magnitude vs distance for a number of
spectral types and over the range 5.7<G<20. In addition a set of crudely drawn contours show the points
where 0.1, 1, and 10 per cent relative parallax accracy are reached.
Parameters
-... |
def vminiFromSpt(spt):
"""
Obtain (V-I) for the input spectral type.
Parameters
----------
spt - String representing the spectral type of the star.
Returns
-------
The value of (V-I).
"""
if spt in _sptToVminiVabsDictionary:
return _sptToVminiVabsDictionary[spt][0]
else:
message="U... |
def vabsFromSpt(spt):
"""
Obtain M_V (absolute magnitude in V-band) for the input spectral type.
Parameters
----------
spt - String representing the spectral type of the star.
Returns
-------
The value of M_V.
"""
if spt in _sptToVminiVabsDictionary:
return _sptToVminiVabsDictionary[spt]... |
def gabsFromSpt(spt):
"""
Obtain M_G (absolute magnitude in G-band) for the input spectral type.
Parameters
----------
spt - String representing the spectral type of the star.
Returns
-------
The value of M_G.
"""
if spt in _sptToVminiVabsDictionary:
return vabsFromSpt(spt) + gminvFromVm... |
def makePlot(pdf=False, png=False):
"""
Plot relative parallax errors as a function of distance for stars of a given spectral type.
Parameters
----------
args - command line arguments
"""
logdistancekpc = np.linspace(-1,np.log10(20.0),100)
sptVabsAndVmini=OrderedDict([('K0V',(5.58,0.87)), ('G5V',(4.78... |
def makePlot(args):
"""
Make the plot with radial velocity performance predictions.
:argument args: command line arguments
"""
gRvs=np.linspace(5.7,16.1,101)
spts=['B0V', 'B5V', 'A0V', 'A5V', 'F0V', 'G0V',
'G5V', 'K0V', 'K1IIIMP', 'K4V', 'K1III']
fig=plt.figure(figsize=(10,6.5))
deltaHue = 24... |
def either(*funcs):
"""
A utility function for selecting the first non-null query.
Parameters:
funcs: One or more functions
Returns:
A function that, when called with a :class:`Node`, will
pass the input to each `func`, and return the first non-Falsey
result.
Examples... |
def _helpful_failure(method):
"""
Decorator for eval_ that prints a helpful error message
if an exception is generated in a Q expression
"""
@wraps(method)
def wrapper(self, val):
try:
return method(self, val)
except:
exc_cls, inst, tb = sys.exc_info()
... |
def _uniquote(value):
"""
Convert to unicode, and add quotes if initially a string
"""
if isinstance(value, six.binary_type):
try:
value = value.decode('utf-8')
except UnicodeDecodeError: # Not utf-8. Show the repr
value = six.text_type(_dequote(repr(value))) # ... |
def each(self, *funcs):
"""
Call `func` on each element in the collection.
If multiple functions are provided, each item
in the output will be a tuple of each
func(item) in self.
Returns a new Collection.
Example:
>>> col = Collection([Scalar(1), S... |
def exclude(self, func=None):
"""
Return a new Collection excluding some items
Parameters:
func : function(Node) -> Scalar
A function that, when called on each item
in the collection, returns a boolean-like
value. If no function is p... |
def filter(self, func=None):
"""
Return a new Collection with some items removed.
Parameters:
func : function(Node) -> Scalar
A function that, when called on each item
in the collection, returns a boolean-like
value. If no function i... |
def takewhile(self, func=None):
"""
Return a new Collection with the last few items removed.
Parameters:
func : function(Node) -> Node
Returns:
A new Collection, discarding all items
at and after the first item where bool(func(item)) == False
... |
def dropwhile(self, func=None):
"""
Return a new Collection with the first few items removed.
Parameters:
func : function(Node) -> Node
Returns:
A new Collection, discarding all items
before the first item where bool(func(item)) == True
"""... |
def dump(self, *args, **kwargs):
"""
Build a list of dicts, by calling :meth:`Node.dump`
on each item.
Each keyword provides a function that extracts a value
from a Node.
Examples:
>>> c = Collection([Scalar(1), Scalar(2)])
>>> c.dump(x2=Q*2, m1... |
def zip(self, *others):
"""
Zip the items of this collection with one or more
other sequences, and wrap the result.
Unlike Python's zip, all sequences must be the same length.
Parameters:
others: One or more iterables or Collections
Returns:
A... |
def dictzip(self, keys):
"""
Turn this collection into a Scalar(dict), by zipping keys and items.
Parameters:
keys: list or Collection of NavigableStrings
The keys of the dictionary
Examples:
>>> c = Collection([Scalar(1), Scalar(2)])
... |
def find(self, *args, **kwargs):
"""
Find a single Node among this Node's descendants.
Returns :class:`NullNode` if nothing matches.
This inputs to this function follow the same semantics
as BeautifulSoup. See http://bit.ly/bs4doc for more info.
Examples:
- n... |
def find_next_sibling(self, *args, **kwargs):
"""
Like :meth:`find`, but searches through :attr:`next_siblings`
"""
op = operator.methodcaller('find_next_sibling', *args, **kwargs)
return self._wrap_node(op) |
def find_parent(self, *args, **kwargs):
"""
Like :meth:`find`, but searches through :attr:`parents`
"""
op = operator.methodcaller('find_parent', *args, **kwargs)
return self._wrap_node(op) |
def find_previous_sibling(self, *args, **kwargs):
"""
Like :meth:`find`, but searches through :attr:`previous_siblings`
"""
op = operator.methodcaller('find_previous_sibling', *args, **kwargs)
return self._wrap_node(op) |
def find_all(self, *args, **kwargs):
"""
Like :meth:`find`, but selects all matches (not just the first one).
Returns a :class:`Collection`.
If no elements match, this returns a Collection with no items.
"""
op = operator.methodcaller('find_all', *args, **kwargs)
... |
def find_next_siblings(self, *args, **kwargs):
"""
Like :meth:`find_all`, but searches through :attr:`next_siblings`
"""
op = operator.methodcaller('find_next_siblings', *args, **kwargs)
return self._wrap_multi(op) |
def find_parents(self, *args, **kwargs):
"""
Like :meth:`find_all`, but searches through :attr:`parents`
"""
op = operator.methodcaller('find_parents', *args, **kwargs)
return self._wrap_multi(op) |
def find_previous_siblings(self, *args, **kwargs):
"""
Like :meth:`find_all`, but searches through :attr:`previous_siblings`
"""
op = operator.methodcaller('find_previous_siblings', *args, **kwargs)
return self._wrap_multi(op) |
def select(self, selector):
"""
Like :meth:`find_all`, but takes a CSS selector string as input.
"""
op = operator.methodcaller('select', selector)
return self._wrap_multi(op) |
def serach_path():
"""Return potential locations of IACA installation."""
operating_system = get_os()
# 1st choice: in ~/.kerncraft/iaca-{}
# 2nd choice: in package directory / iaca-{}
return [os.path.expanduser("~/.kerncraft/iaca/{}/".format(operating_system)),
os.path.abspath(os.path.d... |
def find_iaca():
"""Return (hopefully) valid installation of IACA."""
requires = ['iaca2.2', 'iaca2.3', 'iaca3.0']
for path in serach_path():
path += 'bin/'
valid = True
for r in requires:
if not os.path.exists(path + r):
valid = False
brea... |
def group_iterator(group):
"""
Yild all groups of simple regex-like expression.
The only special character is a dash (-), which take the preceding and the following chars to
compute a range. If the range is non-sensical (e.g., b-a) it will be empty
Example:
>>> list(group_iterator('a-f'))
... |
def register_options(regdescr):
"""
Very reduced regular expressions for describing a group of registers.
Only groups in square bracktes and unions with pipes (|) are supported.
Examples:
>>> list(register_options('PMC[0-3]'))
['PMC0', 'PMC1', 'PMC2', 'PMC3']
>>> list(register_options('MBO... |
def eventstr(event_tuple=None, event=None, register=None, parameters=None):
"""
Return a LIKWID event string from an event tuple or keyword arguments.
*event_tuple* may have two or three arguments: (event, register) or
(event, register, parameters)
Keyword arguments will be overwritten by *event_t... |
def build_minimal_runs(events):
"""Compile list of minimal runs for given events."""
# Eliminate multiples
events = [e for i, e in enumerate(events) if events.index(e) == i]
# Build list of runs per register group
scheduled_runs = {}
scheduled_events = []
cur_run = 0
while len(scheduled... |
def calculate_cache_access(self):
"""Apply cache prediction to generate cache access behaviour."""
self.results = {'misses': self.predictor.get_misses(),
'hits': self.predictor.get_hits(),
'evicts': self.predictor.get_evicts(),
'ver... |
def analyze(self):
"""Run analysis."""
precision = 'DP' if self.kernel.datatype == 'double' else 'SP'
self.calculate_cache_access()
self.results['max_perf'] = self.conv_perf(self.machine['clock'] * self.cores * \
self.machine['FLOPs per cycle'][precision]['total']) |
def conv_perf(self, performance):
"""Convert performance (FLOP/s) to other units, such as It/s or cy/CL."""
clock = self.machine['clock']
flops_per_it = sum(self.kernel._flops.values())
it_s = performance/flops_per_it
it_s.unit = 'It/s'
element_size = self.kernel.datatype... |
def report(self, output_file=sys.stdout):
"""Report analysis outcome in human readable form."""
max_perf = self.results['max_perf']
if self._args and self._args.verbose >= 3:
print('{}'.format(pformat(self.results)), file=output_file)
if self._args and self._args.verbose >=... |
def analyze(self):
"""Run complete analysis."""
self.results = self.calculate_cache_access()
try:
iaca_analysis, asm_block = self.kernel.iaca_analysis(
micro_architecture=self.machine['micro-architecture'],
asm_block=self.asm_block,
poi... |
def report(self, output_file=sys.stdout):
"""Print human readable report of model."""
cpu_perf = self.results['cpu bottleneck']['performance throughput']
if self.verbose >= 3:
print('{}'.format(pformat(self.results)), file=output_file)
if self.verbose >= 1:
prin... |
def calculate_cache_access(self):
"""Apply layer condition model to calculate cache accesses."""
# FIXME handle multiple datatypes
element_size = self.kernel.datatypes_size[self.kernel.datatype]
results = {'dimensions': {}}
def sympy_compare(a, b):
c = 0
... |
def analyze(self):
"""Run complete analysis."""
# check that layer conditions can be applied on this kernel:
# 1. All iterations may only have a step width of 1
loop_stack = list(self.kernel.get_loop_stack())
if any([l['increment'] != 1 for l in loop_stack]):
raise Va... |
def report(self, output_file=sys.stdout):
"""Report generated model in human readable form."""
if self._args and self._args.verbose > 2:
pprint(self.results)
for dimension, lc_info in self.results['dimensions'].items():
print("{}D layer condition:".format(dimension), fil... |
def clean_code(code, comments=True, macros=False, pragmas=False):
"""
Naive comment and macro striping from source code
:param comments: If True, all comments are stripped from code
:param macros: If True, all macros are stripped from code
:param pragmas: If True, all pragmas are stripped from code... |
def replace_id(ast, id_name, replacement):
"""
Replace all matching ID nodes in ast (in-place), with replacement.
:param id_name: name of ID node to match
:param replacement: single or list of node to insert in replacement for ID node.
"""
for a in ast:
if isinstance(a, c_ast.ID) and a.... |
def round_to_next(x, base):
"""Round float to next multiple of base."""
# Based on: http://stackoverflow.com/a/2272174
return int(base * math.ceil(float(x)/base)) |
def blocking(indices, block_size, initial_boundary=0):
"""
Split list of integers into blocks of block_size and return block indices.
First block element will be located at initial_boundary (default 0).
>>> blocking([0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 8)
[0,-1]
>>> blocking([0], 8)
[0... |
def calculate_cache_access(self):
"""Dispatch to cache predictor to get cache stats."""
self.results.update({
'cycles': [], # will be filled by caclculate_cycles()
'misses': self.predictor.get_misses(),
'hits': self.predictor.get_h... |
def calculate_cycles(self):
"""
Calculate performance model cycles from cache stats.
calculate_cache_access() needs to have been execute before.
"""
element_size = self.kernel.datatypes_size[self.kernel.datatype]
elements_per_cacheline = float(self.machine['cacheline siz... |
def analyze(self):
"""Run complete anaylysis and return results."""
self.calculate_cache_access()
self.calculate_cycles()
self.results['flops per iteration'] = sum(self.kernel._flops.values())
return self.results |
def report(self, output_file=sys.stdout):
"""Print generated model data in human readable format."""
if self.verbose > 1:
print('{}'.format(pprint.pformat(self.results['verbose infos'])), file=output_file)
for level, cycles in self.results['cycles']:
print('{} = {}'.form... |
def analyze(self):
"""
Run complete analysis and return results.
"""
try:
incore_analysis, asm_block = self.kernel.iaca_analysis(
micro_architecture=self.machine['micro-architecture'],
asm_block=self.asm_block,
pointer_incremen... |
def conv_cy(self, cy_cl):
"""Convert cycles (cy/CL) to other units, such as FLOP/s or It/s."""
if not isinstance(cy_cl, PrefixedUnit):
cy_cl = PrefixedUnit(cy_cl, '', 'cy/CL')
clock = self.machine['clock']
element_size = self.kernel.datatypes_size[self.kernel.datatype]
... |
def report(self, output_file=sys.stdout):
"""Print generated model data in human readable format."""
if self.verbose > 2:
print("IACA Output:", file=output_file)
print(self.results['IACA output'], file=output_file)
print('', file=output_file)
if self.verbose ... |
def analyze(self):
"""Run complete analysis."""
self._CPU.analyze()
self._data.analyze()
self.results = copy.deepcopy(self._CPU.results)
self.results.update(copy.deepcopy(self._data.results))
cores_per_numa_domain = self.machine['cores per NUMA domain']
# Compil... |
def report(self, output_file=sys.stdout):
"""Print generated model data in human readable format."""
report = ''
if self.verbose > 1:
self._CPU.report()
self._data.report()
report += '{{ {:.1f} || {:.1f} | {} }} cy/CL'.format(
self.results['T_OL'],
... |
def plot(self, fig=None):
"""Plot visualization of model prediction."""
if not fig:
fig = plt.gcf()
fig.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.15)
ax = fig.add_subplot(1, 1, 1)
sorted_overlapping_ports = sorted(
[(p, self.results['port cy... |
def strip_and_uncomment(asm_lines):
"""Strip whitespaces and comments from asm lines."""
asm_stripped = []
for line in asm_lines:
# Strip comments and whitespaces
asm_stripped.append(line.split('#')[0].strip())
return asm_stripped |
def strip_unreferenced_labels(asm_lines):
"""Strip all labels, which are never referenced."""
asm_stripped = []
for line in asm_lines:
if re.match(r'^\S+:', line):
# Found label
label = line[0:line.find(':')]
# Search for references to current label
if... |
def find_asm_blocks(asm_lines):
"""Find blocks probably corresponding to loops in assembly."""
blocks = []
last_labels = OrderedDict()
packed_ctr = 0
avx_ctr = 0
xmm_references = []
ymm_references = []
zmm_references = []
gp_references = []
mem_references = []
increments = {... |
def select_best_block(blocks):
"""Return best block selected based on simple heuristic."""
# TODO make this cleverer with more stats
if not blocks:
raise ValueError("No suitable blocks were found in assembly.")
best_block = max(blocks, key=lambda b: b[1]['packed_instr'])
if best_block[1]['pa... |
def userselect_increment(block):
"""Let user interactively select byte increment."""
print("Selected block:")
print('\n ' + ('\n '.join(block['lines'])))
print()
increment = None
while increment is None:
increment = input("Choose store pointer increment (number of bytes): ")
... |
def userselect_block(blocks, default=None, debug=False):
"""Let user interactively select block."""
print("Blocks found in assembly file:")
print(" block | OPs | pck. | AVX || Registers | ZMM | YMM | XMM | GP ||ptr.inc|\n"
"----------------+-----+------+-----++--------... |
def insert_markers(asm_lines, start_line, end_line):
"""Insert IACA marker into list of ASM instructions at given indices."""
asm_lines = (asm_lines[:start_line] + START_MARKER +
asm_lines[start_line:end_line + 1] + END_MARKER +
asm_lines[end_line + 1:])
return asm_lines |
def iaca_instrumentation(input_file, output_file,
block_selection='auto',
pointer_increment='auto_with_manual_fallback',
debug=False):
"""
Add IACA markers to an assembly file.
If instrumentation fails because loop increment could n... |
def iaca_analyse_instrumented_binary(instrumented_binary_file, micro_architecture):
"""
Run IACA analysis on an instrumented binary.
:param instrumented_binary_file: path of binary that was built with IACA markers
:param micro_architecture: micro architecture string as taken by IACA.
... |
def main():
"""Execute command line interface."""
parser = argparse.ArgumentParser(
description='Find and analyze basic loop blocks and mark for IACA.',
epilog='For help, examples, documentation and bug reports go to:\nhttps://github.com'
'/RRZE-HPC/kerncraft\nLicense: AGPLv3')
... |
def simulate(kernel, model, define_dict, blocking_constant, blocking_length):
"""Setup and execute model with given blocking length"""
kernel.clear_state()
# Add constants from define arguments
for k, v in define_dict.items():
kernel.set_constant(k, v)
kernel.set_constant(blocking_constant... |
def good_prefix(self, max_error=0.01, round_length=2, min_prefix='', max_prefix=None):
"""
returns the largest prefix where the relative error is bellow *max_error* although rounded
by *round_length*
if *max_prefix* is found in PrefixedUnit.PREFIXES, returned value will not exceed this
... |
def space(start, stop, num, endpoint=True, log=False, base=10):
"""
Return list of evenly spaced integers over an interval.
Numbers can either be evenly distributed in a linear space (if *log* is False) or in a log
space (if *log* is True). If *log* is True, base is used to define the log space basis.
... |
def get_last_modified_datetime(dir_path=os.path.dirname(__file__)):
"""Return datetime object of latest change in kerncraft module directory."""
max_mtime = 0
for root, dirs, files in os.walk(dir_path):
for f in files:
p = os.path.join(root, f)
try:
max_mtime ... |
def create_parser():
"""Return argparse parser."""
parser = argparse.ArgumentParser(
description='Analytical performance modelling and benchmarking toolkit.',
epilog='For help, examples, documentation and bug reports go to:\nhttps://github.com'
'/RRZE-HPC/kerncraft\nLicense: AGPLv... |
def check_arguments(args, parser):
"""Check arguments passed by user that are not checked by argparse itself."""
if args.asm_block not in ['auto', 'manual']:
try:
args.asm_block = int(args.asm_block)
except ValueError:
parser.error('--asm-block can only be "auto", "manual... |
def run(parser, args, output_file=sys.stdout):
"""Run command line interface."""
# Try loading results file (if requested)
result_storage = {}
if args.store:
args.store.seek(0)
try:
result_storage = pickle.load(args.store)
except EOFError:
pass
arg... |
def main():
"""Initialize and run command line interface."""
# Create and populate parser
parser = create_parser()
# Parse given arguments
args = parser.parse_args()
# Checking arguments
check_arguments(args, parser)
# BUSINESS LOGIC IS FOLLOWING
run(parser, args) |
def main():
"""Comand line interface of picklemerge."""
parser = argparse.ArgumentParser(
description='Recursively merges two or more pickle files. Only supports pickles consisting '
'of a single dictionary object.')
parser.add_argument('destination', type=argparse.FileType('r+b'),
... |
def symbol_pos_int(*args, **kwargs):
"""Create a sympy.Symbol with positive and integer assumptions."""
kwargs.update({'positive': True,
'integer': True})
return sympy.Symbol(*args, **kwargs) |
def prefix_indent(prefix, textblock, later_prefix=' '):
"""
Prefix and indent all lines in *textblock*.
*prefix* is a prefix string
*later_prefix* is used on all but the first line, if it is a single character
it will be repeated to match length of *prefix*
"""
textblock = te... |
def transform_multidim_to_1d_decl(decl):
"""
Transform ast of multidimensional declaration to a single dimension declaration.
In-place operation!
Returns name and dimensions of array (to be used with transform_multidim_to_1d_ref())
"""
dims = []
type_ = decl.type
while type(type_) is c... |
def transform_multidim_to_1d_ref(aref, dimension_dict):
"""
Transform ast of multidimensional reference to a single dimension reference.
In-place operation!
"""
dims = []
name = aref
while type(name) is c_ast.ArrayRef:
dims.append(name.subscript)
name = name.name
subscr... |
def transform_array_decl_to_malloc(decl, with_init=True):
"""
Transform ast of "type var_name[N]" to "type* var_name = aligned_malloc(sizeof(type)*N, 32)"
In-place operation.
:param with_init: if False, ommit malloc
"""
if type(decl.type) is not c_ast.ArrayDecl:
# Not an array declarat... |
def find_node_type(ast, node_type):
"""Return list of array references in AST."""
if type(ast) is node_type:
return [ast]
elif type(ast) is list:
return reduce(operator.add, list(map(lambda a: find_node_type(a, node_type), ast)), [])
elif ast is None:
return []
else:
... |
def force_iterable(f):
"""Will make any functions return an iterable objects by wrapping its result in a list."""
def wrapper(*args, **kwargs):
r = f(*args, **kwargs)
if hasattr(r, '__iter__'):
return r
else:
return [r]
return wrapper |
def reduce_path(path):
"""Reduce absolute path to relative (if shorter) for easier readability."""
relative_path = os.path.relpath(path)
if len(relative_path) < len(path):
return relative_path
else:
return path |
def check(self):
"""Check that information about kernel makes sens and is valid."""
datatypes = [v[0] for v in self.variables.values()]
assert len(set(datatypes)) <= 1, 'mixing of datatypes within a kernel is not supported.' |
def set_constant(self, name, value):
"""
Set constant of name to value.
:param name: may be a str or a sympy.Symbol
:param value: must be an int
"""
assert isinstance(name, str) or isinstance(name, sympy.Symbol), \
"constant name needs to be of type str, unic... |
def set_variable(self, name, type_, size):
"""
Register variable of name and type_, with a (multidimensional) size.
:param name: variable name as it appears in code
:param type_: may be any key from Kernel.datatypes_size (typically float or double)
:param size: either None for s... |
def subs_consts(self, expr):
"""Substitute constants in expression unless it is already a number."""
if isinstance(expr, numbers.Number):
return expr
else:
return expr.subs(self.constants) |
def array_sizes(self, in_bytes=False, subs_consts=False):
"""
Return a dictionary with all arrays sizes.
:param in_bytes: If True, output will be in bytes, not element counts.
:param subs_consts: If True, output will be numbers and not symbolic.
Scalar variables are ignored.
... |
def _calculate_relative_offset(self, name, access_dimensions):
"""
Return the offset from the iteration center in number of elements.
The order of indices used in access is preserved.
"""
# TODO to be replaced with compile_global_offsets
offset = 0
base_dims = se... |
def _remove_duplicate_accesses(self):
"""
Remove duplicate source and destination accesses
"""
self.destinations = {var_name: set(acs) for var_name, acs in self.destinations.items()}
self.sources = {var_name: set(acs) for var_name, acs in self.sources.items()} |
def access_to_sympy(self, var_name, access):
"""
Transform a (multidimensional) variable access to a flattend sympy expression.
Also works with flat array accesses.
"""
base_sizes = self.variables[var_name][1]
expr = sympy.Number(0)
for dimension, a in enumerat... |
def iteration_length(self, dimension=None):
"""
Return the number of global loop iterations that are performed.
If dimension is not None, it is the loop dimension that is returned
(-1 is the inner most loop and 0 the outermost)
"""
total_length = 1
if dimension ... |
def get_loop_stack(self, subs_consts=False):
"""Yield loop stack dictionaries in order from outer to inner."""
for l in self._loop_stack:
if subs_consts:
yield {'index': l[0],
'start': self.subs_consts(l[1]),
'stop': self.subs_con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.