INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Make the plot with photometry performance predictions.
def makePlot(args): """ Make the plot with photometry performance predictions. :argument args: command line arguments """ gmag=np.linspace(3.0,20.0,171) vmini = args['vmini'] vmag=gmag-gminvFromVmini(vmini) if args['eom']: sigmaG = gMagnitudeErrorEoM(gmag) sigmaGBp = bpMagnitudeError...
Calculate the value for the parameter z in the formula for parallax and G magnitude errors as a function of G and ( V - I ).
def calcZ(G): """ Calculate the value for the parameter z in the formula for parallax and G magnitude errors as a function of G and (V-I). Parameters ---------- G - Value of G-band magnitude. Returns ------- Value of z. """ gatefloor=power(10.0,0.4*(12.0-15.0)) if isscalar(G): result=...
Calculate the value for the parameter z in the formula for the BP and RP magnitude errors as a function of G and ( V - I ).
def calcZBpRp(G): """ Calculate the value for the parameter z in the formula for the BP and RP magnitude errors as a function of G and (V-I). Parameters ---------- G - Value of G-band magnitude. Returns ------- Value of z for BP/RP. """ gatefloor=power(10.0,0.4*(11.0-15.0)) if isscalar(G...
Calculate the value of z in the formula for the parallax errors. In this case assume gating starts at G = 13. 3 ( to simulate bright star worst performance )
def calcZAltStartGate(G): """ Calculate the value of z in the formula for the parallax errors. In this case assume gating starts at G=13.3 (to simulate bright star worst performance) Parameters ---------- G - Value of G-band magnitude. Returns ------- Value of z. """ gatefloor=power(10.0,0...
Returns the number of transits across the Gaia focal plane averaged over ecliptic longitude.
def averageNumberOfTransits(beta): """ Returns the number of transits across the Gaia focal plane averaged over ecliptic longitude. Parameters ---------- beta - Value(s) of the Ecliptic latitude. Returns ------- Average number of transits for the input values of beta. """ indices = array(floor(a...
Calculate the angular distance between pairs of sky coordinates.
def angularDistance(phi1, theta1, phi2, theta2): """ Calculate the angular distance between pairs of sky coordinates. Parameters ---------- phi1 : float Longitude of first coordinate (radians). theta1 : float Latitude of first coordinate (radians). phi2 : float Long...
Rotates Cartesian coordinates from one reference system to another using the rotation matrix with which the class was initialized. The inputs can be scalars or 1 - dimensional numpy arrays.
def transformCartesianCoordinates(self, x, y, z): """ Rotates Cartesian coordinates from one reference system to another using the rotation matrix with which the class was initialized. The inputs can be scalars or 1-dimensional numpy arrays. Parameters ---------- x - V...
Converts sky coordinates from one reference system to another making use of the rotation matrix with which the class was initialized. Inputs can be scalars or 1 - dimensional numpy arrays.
def transformSkyCoordinates(self, phi, theta): """ Converts sky coordinates from one reference system to another, making use of the rotation matrix with which the class was initialized. Inputs can be scalars or 1-dimensional numpy arrays. Parameters ---------- phi - V...
Converts proper motions from one reference system to another using the prescriptions in section 1. 5. 3 of the Hipparcos Explanatory Volume 1 ( equations 1. 5. 18 1. 5. 19 ).
def transformProperMotions(self, phi, theta, muphistar, mutheta): """ Converts proper motions from one reference system to another, using the prescriptions in section 1.5.3 of the Hipparcos Explanatory Volume 1 (equations 1.5.18, 1.5.19). Parameters ---------- phi ...
Converts the sky coordinate errors from one reference system to another including the covariance term. Equations ( 1. 5. 4 ) and ( 1. 5. 20 ) from section 1. 5 in the Hipparcos Explanatory Volume 1 are used.
def transformSkyCoordinateErrors(self, phi, theta, sigPhiStar, sigTheta, rhoPhiTheta=0): """ Converts the sky coordinate errors from one reference system to another, including the covariance term. Equations (1.5.4) and (1.5.20) from section 1.5 in the Hipparcos Explanatory Volume 1 are used. ...
Converts the proper motion errors from one reference system to another including the covariance term. Equations ( 1. 5. 4 ) and ( 1. 5. 20 ) from section 1. 5 in the Hipparcos Explanatory Volume 1 are used.
def transformProperMotionErrors(self, phi, theta, sigMuPhiStar, sigMuTheta, rhoMuPhiMuTheta=0): """ Converts the proper motion errors from one reference system to another, including the covariance term. Equations (1.5.4) and (1.5.20) from section 1.5 in the Hipparcos Explanatory Volume 1 are use...
Transform the astrometric covariance matrix to its representation in the new coordinate system.
def transformCovarianceMatrix(self, phi, theta, covmat): """ Transform the astrometric covariance matrix to its representation in the new coordinate system. Parameters ---------- phi - The longitude-like angle of the position of the source (radians). theta - T...
Calculates the Jacobian for the transformation of the position errors and proper motion errors between coordinate systems. This Jacobian is also the rotation matrix for the transformation of proper motions. See section 1. 5. 3 of the Hipparcos Explanatory Volume 1 ( equation 1. 5. 20 ). This matrix has the following fo...
def _getJacobian(self, phi, theta): """ Calculates the Jacobian for the transformation of the position errors and proper motion errors between coordinate systems. This Jacobian is also the rotation matrix for the transformation of proper motions. See section 1.5.3 of the Hipparcos Explan...
Propagate the position of a source from the reference epoch t0 to the new epoch t1.
def propagate_astrometry(self, phi, theta, parallax, muphistar, mutheta, vrad, t0, t1): """ Propagate the position of a source from the reference epoch t0 to the new epoch t1. Parameters ---------- phi : float Longitude at reference epoch (radians). theta : ...
Propagate the position of a source from the reference epoch t0 to the new epoch t1.
def propagate_pos(self, phi, theta, parallax, muphistar, mutheta, vrad, t0, t1): """ Propagate the position of a source from the reference epoch t0 to the new epoch t1. Parameters ---------- phi : float Longitude at reference epoch (radians). theta : float ...
Propagate the covariance matrix of the astrometric parameters and radial proper motion of a source from epoch t0 to epoch t1.
def propagate_astrometry_and_covariance_matrix(self, a0, c0, t0, t1): """ Propagate the covariance matrix of the astrometric parameters and radial proper motion of a source from epoch t0 to epoch t1. Code based on the Hipparcos Fortran implementation by Lennart Lindegren. Param...
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.
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 -...
Look up the numerical factors to apply to the sky averaged parallax error in order to obtain error values for a given astrometric parameter taking the Ecliptic latitude and the number of transits into account.
def errorScalingFactor(observable, beta): """ Look up the numerical factors to apply to the sky averaged parallax error in order to obtain error values for a given astrometric parameter, taking the Ecliptic latitude and the number of transits into account. Parameters ---------- observable - Name of astr...
Calculate the sky averaged parallax error from G and ( V - I ).
def parallaxErrorSkyAvg(G, vmini, extension=0.0): """ Calculate the sky averaged parallax error from G and (V-I). Parameters ---------- G - Value(s) of G-band magnitude. vmini - Value(s) of (V-I) colour. Keywords -------- extension - Add this amount of years to the mission lifetime and scale t...
Calculate the minimum parallax error from G and ( V - I ). This correspond to the sky regions with the smallest astrometric errors. At the bright end the parallax error is at least 14 muas due to the gating scheme.
def parallaxMinError(G, vmini, extension=0.0): """ Calculate the minimum parallax error from G and (V-I). This correspond to the sky regions with the smallest astrometric errors. At the bright end the parallax error is at least 14 muas due to the gating scheme. Parameters ---------- G - Value(s) of...
Calculate the maximum parallax error from G and ( V - I ). This correspond to the sky regions with the largest astrometric errors. At the bright end the parallax error is at least 14 muas due to the gating scheme.
def parallaxMaxError(G, vmini, extension=0.0): """ Calculate the maximum parallax error from G and (V-I). This correspond to the sky regions with the largest astrometric errors. At the bright end the parallax error is at least 14 muas due to the gating scheme. Parameters ---------- G - Value(s) of ...
Calculate the sky averaged parallax error from G and ( V - I ). In this case assume gating starts at G = 13. 3 ( to simulate bright star worst performance )
def parallaxErrorSkyAvgAltStartGate(G, vmini, extension=0.0): """ Calculate the sky averaged parallax error from G and (V-I). In this case assume gating starts at G=13.3 (to simulate bright star worst performance) Parameters ---------- G - Value(s) of G-band magnitude. vmini - Value(s) of (V-I) colo...
Calculate the sky averaged position errors from G and ( V - I ).
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 ...
Calculate the minimum position errors from G and ( V - I ). These correspond to the sky regions with the smallest astrometric errors.
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 ...
Calculate the maximum position errors from G and ( V - I ). These correspond to the sky regions with the largest astrometric errors.
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...
Calculate the position errors from G and ( V - I ) and the Ecliptic latitude beta of the source.
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 --...
Calculate the minimum proper motion errors from G and ( V - I ). These correspond to the sky regions with the smallest astrometric errors.
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...
Calculate the maximum proper motion errors from G and ( V - I ). These correspond to the sky regions with the largest astrometric errors.
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...
Calculate the proper motion errors from G and ( V - I ) and the Ecliptic latitude beta of the source.
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...
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.
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...
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.
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 -...
Obtain ( V - I ) for the input spectral type.
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...
Obtain M_V ( absolute magnitude in V - band ) for the input spectral type.
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]...
Obtain M_G ( absolute magnitude in G - band ) for the input spectral type.
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...
Plot relative parallax errors as a function of distance for stars of a given spectral type.
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...
Make the plot with radial velocity performance predictions.
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...
A utility function for selecting the first non - null query.
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...
Decorator for eval_ that prints a helpful error message if an exception is generated in a Q expression
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() ...
Convert to unicode and add quotes if initially a string
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))) # ...
Call func on each element in the collection.
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...
Return a new Collection excluding some items
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...
Return a new Collection with some items removed.
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...
Return a new Collection with the last few items removed.
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 ...
Return a new Collection with the first few items removed.
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 """...
Build a list of dicts by calling: meth: Node. dump on each item.
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...
Zip the items of this collection with one or more other sequences and wrap the result.
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...
Turn this collection into a Scalar ( dict ) by zipping keys and items.
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)]) ...
Find a single Node among this Node s descendants.
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...
Like: meth: find but searches through: attr: next_siblings
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)
Like: meth: find but searches through: attr: parents
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)
Like: meth: find but searches through: attr: previous_siblings
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)
Like: meth: find but selects all matches ( not just the first one ).
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) ...
Like: meth: find_all but searches through: attr: next_siblings
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)
Like: meth: find_all but searches through: attr: parents
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)
Like: meth: find_all but searches through: attr: previous_siblings
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)
Like: meth: find_all but takes a CSS selector string as input.
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)
Return potential locations of IACA installation.
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...
Return ( hopefully ) valid installation of IACA.
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...
Yild all groups of simple regex - like expression.
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')) ...
Very reduced regular expressions for describing a group of registers.
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...
Return a LIKWID event string from an event tuple or keyword arguments.
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...
Compile list of minimal runs for given events.
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...
Apply cache prediction to generate cache access behaviour.
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...
Run analysis.
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'])
Convert performance ( FLOP/ s ) to other units such as It/ s or cy/ CL.
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...
Report analysis outcome in human readable form.
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 >=...
Run complete analysis.
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...
Print human readable report of model.
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...
Apply layer condition model to calculate cache accesses.
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 ...
Run complete analysis.
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...
Report generated model in human readable form.
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...
Naive comment and macro striping from source code
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...
Replace all matching ID nodes in ast ( in - place ) with replacement.
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....
Round float to next multiple of base.
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))
Split list of integers into blocks of block_size and return block indices.
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...
Dispatch to cache predictor to get cache stats.
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...
Calculate performance model cycles from cache stats.
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...
Run complete anaylysis and return results.
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
Print generated model data in human readable format.
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...
Run complete analysis and return results.
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...
Convert cycles ( cy/ CL ) to other units such as FLOP/ s or It/ s.
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] ...
Print generated model data in human readable format.
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 ...
Run complete analysis.
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...
Print generated model data in human readable format.
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'], ...
Plot visualization of model prediction.
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...
Strip whitespaces and comments from asm lines.
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
Strip all labels which are never referenced.
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...
Find blocks probably corresponding to loops in assembly.
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 = {...
Return best block selected based on simple heuristic.
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...
Let user interactively select byte increment.
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): ") ...
Let user interactively select block.
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" "----------------+-----+------+-----++--------...
Insert IACA marker into list of ASM instructions at given indices.
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
Add IACA markers to an assembly file.
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...
Run IACA analysis on an instrumented binary.
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. ...
Execute command line interface.
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') ...
Setup and execute model with given blocking length
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...
returns the largest prefix where the relative error is bellow * max_error * although rounded by * round_length *
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 ...
Return list of evenly spaced integers over an interval.
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. ...
Return datetime object of latest change in kerncraft module directory.
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 ...
Return argparse parser.
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...