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 excepthook (self, etype, evalue, etb): """Handle an uncaught exception. We always forward the exception on to whatever `sys.excepthook` was present upon setup. However, if the exception is a KeyboardInterrupt, we additionally kill ourselves with an uncaught SIGINT, so that invoking programs know what happened. """
self.inner_excepthook (etype, evalue, etb) if issubclass (etype, KeyboardInterrupt): # Don't try this at home, kids. On some systems os.kill (0, ...) # signals our entire progress group, which is not what we want, # so we use os.getpid (). signal.signal (signal.SIGINT, signal.SIG_DFL) os.kill (os.getpid (), signal.SIGINT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_nu_b(b): """Calculate the cyclotron frequency in Hz given a magnetic field strength in Gauss. This is in cycles per second not radians per second; i.e. there is a 2π in the denominator: ν_B = e B / (2π m_e c) """
return cgs.e * b / (2 * cgs.pi * cgs.me * cgs.c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_freefree_snu_ujy(ne, t, width, elongation, dist, ghz): """Calculate a flux density from pure free-free emission. """
hz = ghz * 1e9 eta = calc_freefree_eta(ne, t, hz) kappa = calc_freefree_kappa(ne, t, hz) snu = calc_snu(eta, kappa, width, elongation, dist) ujy = snu * cgs.jypercgs * 1e6 return ujy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def concat(invises, outvis, timesort=False): """Concatenate visibility measurement sets. invises (list of str) Paths to the input measurement sets outvis (str) Path to the output measurement set. timesort (boolean) If true, sort the output in time after concatenation. Example:: from pwkit.environments.casa import tasks tasks.concat(['epoch1.ms', 'epoch2.ms'], 'combined.ms') """
tb = util.tools.table() ms = util.tools.ms() if os.path.exists(outvis): raise RuntimeError('output "%s" already exists' % outvis) for invis in invises: if not os.path.isdir(invis): raise RuntimeError('input "%s" does not exist' % invis) tb.open(b(invises[0])) tb.copy(b(outvis), deep=True, valuecopy=True) tb.close() ms.open(b(outvis), nomodify=False) for invis in invises[1:]: ms.concatenate(msfile=b(invis), freqtol=b(concat_freqtol), dirtol=b(concat_dirtol)) ms.writehistory(message=b'taskname=tasklib.concat', origin=b'tasklib.concat') ms.writehistory(message=b('vis = ' + ', '.join(invises)), origin=b'tasklib.concat') ms.writehistory(message=b('timesort = ' + 'FT'[int(timesort)]), origin=b'tasklib.concat') if timesort: ms.timesort() ms.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delcal(mspath): """Delete the ``MODEL_DATA`` and ``CORRECTED_DATA`` columns from a measurement set. mspath (str) The path to the MS to modify Example:: from pwkit.environments.casa import tasks tasks.delcal('dataset.ms') """
wantremove = 'MODEL_DATA CORRECTED_DATA'.split() tb = util.tools.table() tb.open(b(mspath), nomodify=False) cols = frozenset(tb.colnames()) toremove = [b(c) for c in wantremove if c in cols] if len(toremove): tb.removecols(toremove) tb.close() # We want to return a `str` type, which is what we already # have in Python 2 but not in 3. if six.PY2: return toremove else: return [c.decode('utf8') for c in toremove]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delmod_cli(argv, alter_logger=True): """Command-line access to ``delmod`` functionality. The ``delmod`` task deletes "on-the-fly" model information from a Measurement Set. It is so easy to implement that a standalone function is essentially unnecessary. Just write:: from pwkit.environments.casa import util cb = util.tools.calibrater() cb.open('datasaet.ms', addcorr=False, addmodel=False) cb.delmod(otf=True, scr=False) cb.close() If you want to delete the scratch columns, use :func:`delcal`. If you want to clear the scratch columns, use :func:`clearcal`. """
check_usage(delmod_doc, argv, usageifnoargs=True) if alter_logger: util.logger() cb = util.tools.calibrater() for mspath in argv[1:]: cb.open(b(mspath), addcorr=False, addmodel=False) cb.delmod(otf=True, scr=False) cb.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractbpflags(calpath, deststream): """Make a flags file out of a bandpass calibration table calpath (str) The path to the bandpass calibration table deststream (stream-like object, e.g. an opened file) Where to write the flags data Below is documentation written for the command-line interface to this functionality: """
tb = util.tools.table() tb.open(b(os.path.join(calpath, 'ANTENNA'))) antnames = tb.getcol(b'NAME') tb.close() tb.open(b(calpath)) try: t = tb.getkeyword(b'VisCal') except RuntimeError: raise PKError('no "VisCal" keyword in %s; it doesn\'t seem to be a ' 'bandpass calibration table', calpath) if t != 'B Jones': raise PKError('table %s doesn\'t seem to be a bandpass calibration ' 'table; its type is "%s"', calpath, t) def emit(antidx, spwidx, chanstart, chanend): # Channel ranges are inclusive, unlike Python syntax. print("antenna='%s&*' spw='%d:%d~%d' reason='BANDPASS_FLAGGED'" % \ (antnames[antidx], spwidx, chanstart, chanend), file=deststream) for row in range(tb.nrows()): ant = tb.getcell(b'ANTENNA1', row) spw = tb.getcell(b'SPECTRAL_WINDOW_ID', row) flag = tb.getcell(b'FLAG', row) # This is the logical 'or' of the two polarizations: i.e., anything that # is flagged in either poln is flagged in this. sqflag = ~((~flag).prod(axis=0, dtype=np.bool)) runstart = None for i in range(sqflag.size): if sqflag[i]: # This channel is flagged. Start a run if not already in one. if runstart is None: runstart = i elif runstart is not None: # The current run just ended. emit(ant, spw, runstart, i - 1) runstart = None if runstart is not None: emit(ant, spw, runstart, i) tb.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flagmanager_cli(argv, alter_logger=True): """Command-line access to ``flagmanager`` functionality. The ``flagmanager`` task manages tables of flags associated with measurement sets. Its features are easy to implement that a standalone library function is essentially unnecessary. See the source code to this function for the tool calls that implement different parts of the ``flagmanager`` functionality. """
check_usage(flagmanager_doc, argv, usageifnoargs=True) if len(argv) < 3: wrong_usage(flagmanager_doc, 'expect at least a mode and an MS name') mode = argv[1] ms = argv[2] if alter_logger: if mode == 'list': util.logger('info') elif mode == 'delete': # it WARNs 'deleting version xxx' ... yargh util.logger('severe') else: util.logger() try: factory = util.tools.agentflagger except AttributeError: factory = util.tools.testflagger af = factory() af.open(b(ms)) if mode == 'list': if len(argv) != 3: wrong_usage(flagmanager_doc, 'expect exactly one argument in list mode') af.getflagversionlist() elif mode == 'save': if len(argv) != 4: wrong_usage(flagmanager_doc, 'expect exactly two arguments in save mode') from time import strftime name = argv[3] af.saveflagversion(versionname=b(name), merge=b'replace', comment=b('created %s(casatask flagmanager)' % strftime('%Y-%m-%dT%H:%M:%SZ'))) elif mode == 'restore': if len(argv) != 4: wrong_usage(flagmanager_doc, 'expect exactly two arguments in restore mode') name = argv[3] af.restoreflagversion(versionname=b(name), merge=b'replace') elif mode == 'delete': if len(argv) != 4: wrong_usage(flagmanager_doc, 'expect exactly two arguments in delete mode') name = argv[3] if not os.path.isdir(os.path.join(ms + '.flagversions', 'flags.' + name)): # This condition only results in a WARN from deleteflagversion()! raise RuntimeError('version "%s" doesn\'t exist in "%s.flagversions"' % (name, ms)) af.deleteflagversion(versionname=b(name)) else: wrong_usage(flagmanager_doc, 'unknown flagmanager mode "%s"' % mode) af.done()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image2fits(mspath, fitspath, velocity=False, optical=False, bitpix=-32, minpix=0, maxpix=-1, overwrite=False, dropstokes=False, stokeslast=True, history=True, **kwargs): """Convert an image in MS format to FITS format. mspath (str) The path to the input MS. fitspath (str) The path to the output FITS file. velocity (boolean) (To be documented.) optical (boolean) (To be documented.) bitpix (integer) (To be documented.) minpix (integer) (To be documented.) maxpix (integer) (To be documented.) overwrite (boolean) Whether the task is allowed to overwrite an existing destination file. dropstokes (boolean) Whether the "Stokes" (polarization) axis of the image should be dropped. stokeslast (boolean) Whether the "Stokes" (polarization) axis of the image should be placed as the last (innermost?) axis of the image cube. history (boolean) (To be documented.) ``**kwargs`` Forwarded on to the ``tofits`` function of the CASA ``image`` tool. """
ia = util.tools.image() ia.open(b(mspath)) ia.tofits(outfile=b(fitspath), velocity=velocity, optical=optical, bitpix=bitpix, minpix=minpix, maxpix=maxpix, overwrite=overwrite, dropstokes=dropstokes, stokeslast=stokeslast, history=history, **kwargs) ia.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def importalma(asdm, ms): """Convert an ALMA low-level ASDM dataset to Measurement Set format. asdm (str) The path to the input ASDM dataset. ms (str) The path to the output MS dataset. This implementation automatically infers the value of the "tbuff" parameter. Example:: from pwkit.environments.casa import tasks tasks.importalma('myalma.asdm', 'myalma.ms') """
from .scripting import CasapyScript script = os.path.join(os.path.dirname(__file__), 'cscript_importalma.py') with CasapyScript(script, asdm=asdm, ms=ms) as cs: 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 importevla(asdm, ms): """Convert an EVLA low-level SDM dataset to Measurement Set format. asdm (str) The path to the input ASDM dataset. ms (str) The path to the output MS dataset. This implementation automatically infers the value of the "tbuff" parameter. Example:: from pwkit.environments.casa import tasks tasks.importevla('myvla.sdm', 'myvla.ms') """
from .scripting import CasapyScript # Here's the best way I can figure to find the recommended value of tbuff #(= 1.5 * integration time). Obviously you might have different # integration times in the dataset and such, and we're just going to # ignore that possibility. bdfstem = os.listdir(os.path.join(asdm, 'ASDMBinary'))[0] bdf = os.path.join(asdm, 'ASDMBinary', bdfstem) tbuff = None with open(bdf, 'rb') as f: for linenum, line in enumerate(f): if linenum > 60: raise PKError('cannot find integration time info in %s', bdf) if not line.startswith(b'<sdmDataSubsetHeader'): continue try: i1 = line.index(b'<interval>') + len(b'<interval>') i2 = line.index(b'</interval>') if i2 <= i1: raise ValueError() except ValueError: raise PKError('cannot parse integration time info in %s', bdf) tbuff = float(line[i1:i2]) * 1.5e-9 # nanosecs, and want 1.5x break if tbuff is None: raise PKError('found no integration time info') print('importevla: %s -> %s with tbuff=%.2f' % (asdm, ms, tbuff)) script = os.path.join(os.path.dirname(__file__), 'cscript_importevla.py') with CasapyScript(script, asdm=asdm, ms=ms, tbuff=tbuff) as cs: 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 listobs(vis): """Textually describe the contents of a measurement set. vis (str) The path to the dataset. Returns A generator of lines of human-readable output Errors can only be detected by looking at the output. Example:: from pwkit.environments.casa import tasks for line in tasks.listobs('mydataset.ms'): print(line) """
def inner_list(sink): try: ms = util.tools.ms() ms.open(vis) ms.summary(verbose=True) ms.close() except Exception as e: sink.post(b'listobs failed: %s' % e, priority=b'SEVERE') for line in util.forkandlog(inner_list): info = line.rstrip().split('\t', 3) # date, priority, origin, message if len(info) > 3: yield info[3] else: yield ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mjd2date(mjd, precision=3): """Convert an MJD to a data string in the format used by CASA. mjd (numeric) An MJD value in the UTC timescale. precision (integer, default 3) The number of digits of decimal precision in the seconds portion of the returned string Returns A string representing the input argument in CASA format: ``YYYY/MM/DD/HH:MM:SS.SSS``. Example:: from pwkit.environment.casa import tasks print(tasks.mjd2date(55555)) # yields '2010/12/25/00:00:00.000' """
from astropy.time import Time dt = Time(mjd, format='mjd', scale='utc').to_datetime() fracsec = ('%.*f' % (precision, 1e-6 * dt.microsecond)).split('.')[1] return '%04d/%02d/%02d/%02d:%02d:%02d.%s' % ( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, fracsec )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plotants(vis, figfile): """Plot the physical layout of the antennas described in the MS. vis (str) Path to the input dataset figfile (str) Path to the output image file. The output image format will be inferred from the extension of *figfile*. Example:: from pwkit.environments.casa import tasks tasks.plotants('dataset.ms', 'antennas.png') """
from .scripting import CasapyScript script = os.path.join(os.path.dirname(__file__), 'cscript_plotants.py') with CasapyScript(script, vis=vis, figfile=figfile) as cs: 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 latexify(obj, **kwargs): """Render an object in LaTeX appropriately. """
if hasattr(obj, '__pk_latex__'): return obj.__pk_latex__(**kwargs) if isinstance(obj, text_type): from .unicode_to_latex import unicode_to_latex return unicode_to_latex(obj) if isinstance(obj, bool): # isinstance(True, int) = True, so gotta handle this first. raise ValueError('no well-defined LaTeXification of bool %r' % obj) if isinstance(obj, float): nplaces = kwargs.get('nplaces') if nplaces is None: return '$%f$' % obj return '$%.*f$' % (nplaces, obj) if isinstance(obj, int): return '$%d$' % obj if isinstance(obj, binary_type): if all(c in _printable_ascii for c in obj): return obj.decode('ascii') raise ValueError('no safe LaTeXification of binary string %r' % obj) raise ValueError('can\'t LaTeXify %r' % 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 latexify_n2col(x, nplaces=None, **kwargs): """Render a number into LaTeX in a 2-column format, where the columns split immediately to the left of the decimal point. This gives nice alignment of numbers in a table. """
if nplaces is not None: t = '%.*f' % (nplaces, x) else: t = '%f' % x if '.' not in t: return '$%s$ &' % t left, right = t.split('.') return '$%s$ & $.%s$' % (left, right)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def latexify_u3col(obj, **kwargs): """Convert an object to special LaTeX for uncertainty tables. This conversion is meant for uncertain values in a table. The return value should span three columns. The first column ends just before the decimal point in the main number value, if it has one. It has no separation from the second column. The second column goes from the decimal point until just before the "plus-or-minus" indicator. The third column goes from the "plus-or-minus" until the end. If the item being formatted does not fit this """
if hasattr(obj, '__pk_latex_u3col__'): return obj.__pk_latex_u3col__(**kwargs) # TODO: there are reasonable ways to format many basic types, but I'm not # going to implement them until I need to. raise ValueError('can\'t LaTeXify %r in 3-column uncertain format' % 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 latexify_l3col(obj, **kwargs): """Convert an object to special LaTeX for limit tables. This conversion is meant for limit values in a table. The return value should span three columns. The first column is the limit indicator: <, >, ~, etc. The second column is the whole part of the value, up until just before the decimal point. The third column is the decimal point and the fractional part of the value, if present. If the item being formatted does not fit this schema, it can be wrapped in something like """
if hasattr(obj, '__pk_latex_l3col__'): return obj.__pk_latex_l3col__(**kwargs) if isinstance(obj, bool): # isinstance(True, int) = True, so gotta handle this first. raise ValueError('no well-defined l3col LaTeXification of bool %r' % obj) if isinstance(obj, float): return '&' + latexify_n2col(obj, **kwargs) if isinstance(obj, int): return '& $%d$ &' % obj raise ValueError('can\'t LaTeXify %r in 3-column limit format' % 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 read (path, tabwidth=8, **kwargs): """Read a typed tabular text file into a stream of Holders. Arguments: path The path of the file to read. tabwidth=8 The tab width to assume. Please don't monkey with it. mode='rt' The file open mode (passed to io.open()). noexistok=False If True and the file is missing, treat it as empty. ``**kwargs`` Passed to io.open (). Returns a generator for a stream of `pwkit.Holder`s, each of which will contain ints, strings, or some kind of measurement (cf `pwkit.msmt`). """
datamode = False fixedcols = {} for text in _trimmedlines (path, **kwargs): text = text.expandtabs (tabwidth) if datamode: # table row h = Holder () h.set (**fixedcols) for name, cslice, parser in info: try: v = parser (text[cslice].strip ()) except: reraise_context ('while parsing "%s"', text[cslice].strip ()) h.set_one (name, v) yield h elif text[0] != '@': # fixed column padnamekind, padval = text.split ('=', 1) name, parser = _getparser (padnamekind.strip ()) fixedcols[name] = parser (padval.strip ()) else: # column specification n = len (text) assert n > 1 start = 0 info = [] while start < n: end = start + 1 while end < n and (not text[end].isspace ()): end += 1 if start == 0: namekind = text[start+1:end] # eat leading @ else: namekind = text[start:end] while end < n and text[end].isspace (): end += 1 name, parser = _getparser (namekind) if parser is None: # allow columns to be ignored skippedlast = True else: skippedlast = False info.append ((name, slice (start, end), parser)) start = end datamode = True if not skippedlast: # make our last column go as long as the line goes # (e.g. for "comments" columns) # but if the real last column is ":x"-type, then info[-1] # doesn't run up to the end of the line, so do nothing in that case. lname, lslice, lparser = info[-1] info[-1] = lname, slice (lslice.start, None), lparser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write (stream, items, fieldnames, tabwidth=8): """Write a typed tabular text file to the specified stream. Arguments: stream The destination stream. items An iterable of items to write. Two passes have to be made over the items (to discover the needed column widths), so this will be saved into a list. fieldnames Either a list of field name strings, or a single string. If the latter, it will be split into a list with .split(). tabwidth=8 The tab width to use. Please don't monkey with it. Returns nothing. """
if isinstance (fieldnames, six.string_types): fieldnames = fieldnames.split () maxlens = [0] * len (fieldnames) # We have to make two passes, so listify: items = list (items) # pass 1: get types and maximum lengths for each record. Pad by 1 to # ensure there's at least one space between all columns. coltypes = [None] * len (fieldnames) for i in items: for idx, fn in enumerate (fieldnames): val = i.get (fn) if val is None: continue typetag, text, inexact = msmt.fmtinfo (val) maxlens[idx] = max (maxlens[idx], len (text) + 1) if coltypes[idx] is None: coltypes[idx] = typetag continue if coltypes[idx] == typetag: continue if coltypes[idx][-1] == 'f' and typetag[-1] == 'u': # Can upcast floats to uvals if coltypes[idx][:-1] == typetag[:-1]: coltypes[idx] = coltypes[idx][:-1] + 'u' continue if coltypes[idx][-1] == 'u' and typetag[-1] == 'f': if coltypes[idx][:-1] == typetag[:-1]: continue raise PKError ('irreconcilable column types: %s and %s', coltypes[idx], typetag) # Compute column headers and their widths headers = list (fieldnames) headers[0] = '@' + headers[0] for idx, fn in enumerate (fieldnames): if coltypes[idx] != '': headers[idx] += ':' + coltypes[idx] maxlens[idx] = max (maxlens[idx], len (headers[idx])) widths = [tabwidth * ((k + tabwidth - 1) // tabwidth) for k in maxlens] # pass 2: write out print (''.join (_tabpad (h, widths[idx], tabwidth) for (idx, h) in enumerate (headers)), file=stream) def ustr (i, f): v = i.get (f) if v is None: return '' return msmt.fmtinfo (v)[1] for i in items: print (''.join (_tabpad (ustr (i, fn), widths[idx], tabwidth) for (idx, fn) in enumerate (fieldnames)), file=stream)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vizread (descpath, descsection, tabpath, tabwidth=8, **kwargs): """Read a headerless tabular text file into a stream of Holders. Arguments: descpath The path of the table description ini file. descsection The section in the description file to use. tabpath The path to the actual table data. tabwidth=8 The tab width to assume. Please don't monkey with it. mode='rt' The table file open mode (passed to io.open()). noexistok=False If True and the file is missing, treat it as empty. ``**kwargs`` Passed to io.open (). Returns a generator of a stream of `pwkit.Holder`s, each of which will contain ints, strings, or some kind of measurement (cf `pwkit.msmt`). In this version, the table file does not contain a header, as seen in Vizier data files. The corresponding section in the description ini file has keys of the form "colname = <start> <end> [type]", where <start> and <end> are the **1-based** character numbers defining the column, and [type] is an optional specified of the measurement type of the column (one of the usual b, i, f, u, Lu, Pu). """
from .inifile import read as iniread cols = [] for i in iniread (descpath): if i.section != descsection: continue for field, desc in six.iteritems (i.__dict__): if field == 'section': continue a = desc.split () idx0 = int (a[0]) - 1 if len (a) == 1: cols.append ((field, slice (idx0, idx0 + 1), msmt.parsers['s'])) continue if len (a) == 2: parser = msmt.parsers['s'] else: parser = msmt.parsers[a[2]] cols.append ((field, slice (idx0, int (a[1])), parser)) for text in _trimmedlines (tabpath, **kwargs): text = text.expandtabs (tabwidth) h = Holder () for name, cslice, parser in cols: try: v = parser (text[cslice].strip ()) except: reraise_context ('while parsing "%s"', text[cslice].strip ()) h.set_one (name, v) yield h
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _broadcast_shapes(s1, s2): """Given array shapes `s1` and `s2`, compute the shape of the array that would result from broadcasting them together."""
n1 = len(s1) n2 = len(s2) n = max(n1, n2) res = [1] * n for i in range(n): if i >= n1: c1 = 1 else: c1 = s1[n1-1-i] if i >= n2: c2 = 1 else: c2 = s2[n2-1-i] if c1 == 1: rc = c2 elif c2 == 1 or c1 == c2: rc = c1 else: raise ValueError('array shapes %r and %r are not compatible' % (s1, s2)) res[n-1-i] = rc return tuple(res)
<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_data(self, data, invsigma=None): """Set the data to be modeled. Returns *self*. """
self.data = np.array(data, dtype=np.float, ndmin=1) if invsigma is None: self.invsigma = np.ones(self.data.shape) else: i = np.array(invsigma, dtype=np.float) self.invsigma = np.broadcast_arrays(self.data, i)[1] # allow scalar invsigma if self.invsigma.shape != self.data.shape: raise ValueError('data values and inverse-sigma values must have same shape') return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_soln(self): """Print information about the model solution."""
lmax = reduce(max,(len(x) for x in self.pnames), len('r chi sq')) if self.puncerts is None: for pn, val in zip(self.pnames, self.params): print('%s: %14g' % (pn.rjust(lmax), val)) else: for pn, val, err in zip(self.pnames, self.params, self.puncerts): frac = abs(100. * err / val) print('%s: %14g +/- %14g (%.2f%%)' % (pn.rjust(lmax), val, err, frac)) if self.rchisq is not None: print('%s: %14g' % ('r chi sq'.rjust(lmax), self.rchisq)) elif self.chisq is not None: print('%s: %14g' % ('chi sq'.rjust(lmax), self.chisq)) else: print('%s: unknown/undefined' % ('r chi sq'.rjust(lmax))) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def show_corr(self): "Show the parameter correlation matrix with `pwkit.ndshow_gtk3`." from .ndshow_gtk3 import view d = np.diag(self.covar) ** -0.5 corr = self.covar * d[np.newaxis,:] * d[:,np.newaxis] view(corr, title='Correlation Matrix')
<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_func(self, func, pnames, args=()): """Set the model function to use an efficient but tedious calling convention. The function should obey the following convention:: def func(param_vec, *args): modeled_data = { do something using param_vec } return modeled_data This function creates the :class:`pwkit.lmmin.Problem` so that the caller can futz with it before calling :meth:`solve`, if so desired. Returns *self*. """
from .lmmin import Problem self.func = func self._args = args self.pnames = list(pnames) self.lm_prob = Problem(len(self.pnames)) return self
<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_simple_func(self, func, args=()): """Set the model function to use a simple but somewhat inefficient calling convention. The function should obey the following convention:: modeled_data = { do something using the parameters } return modeled_data Returns *self*. """
code = get_function_code(func) npar = code.co_argcount - len(args) pnames = code.co_varnames[:npar] def wrapper(params, *args): return func(*(tuple(params) + args)) return self.set_func(wrapper, pnames, args)
<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_frozen_func(self, params): """Returns a model function frozen to the specified parameter values. Any remaining arguments are left free and must be provided when the function is called. For this model, the returned function is the application of :func:`functools.partial` to the :attr:`func` property of this object. """
params = np.array(params, dtype=np.float, ndmin=1) from functools import partial return partial(self.func, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve(self, guess): """Solve for the parameters, using an initial guess. This uses the Levenberg-Marquardt optimizer described in :mod:`pwkit.lmmin`. Returns *self*. """
guess = np.array(guess, dtype=np.float, ndmin=1) f = self.func args = self._args def lmfunc(params, vec): vec[:] = f(params, *args).flatten() self.lm_prob.set_residual_func(self.data.flatten(), self.invsigma.flatten(), lmfunc, None) self.lm_soln = soln = self.lm_prob.solve(guess) self.params = soln.params self.puncerts = soln.perror self.covar = soln.covar self.mfunc = self.make_frozen_func(soln.params) # fvec = resids * invsigma = (data - mdata) * invsigma self.resids = soln.fvec.reshape(self.data.shape) / self.invsigma self.mdata = self.data - self.resids # lm_soln.fnorm can be unreliable ("max(fnorm, fnorm1)" branch) self.chisq = (self.lm_soln.fvec**2).sum() if soln.ndof > 0: self.rchisq = self.chisq / soln.ndof return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_nonlinear(self, params=None): """Return a `Model` equivalent to this object. The nonlinear solver is less efficient, but lets you freeze parameters, compute uncertainties, etc. If the `params` argument is provided, solve() will be called on the returned object with those parameters. If it is `None` and this object has parameters in `self.params`, those will be use. Otherwise, solve() will not be called on the returned object. """
if params is None: params = self.params nlm = Model(None, self.data, self.invsigma) nlm.set_func(lambda p, x: npoly.polyval(x, p), self.pnames, args=(self.x,)) if params is not None: nlm.solve(params) return nlm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def files(self): """Returns the URLs of all files attached to posts in the thread."""
if self.topic.has_file: yield self.topic.file.file_url for reply in self.replies: if reply.has_file: yield reply.file.file_url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thumbs(self): """Returns the URLs of all thumbnails in the thread."""
if self.topic.has_file: yield self.topic.file.thumbnail_url for reply in self.replies: if reply.has_file: yield reply.file.thumbnail_url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filenames(self): """Returns the filenames of all files attached to posts in the thread."""
if self.topic.has_file: yield self.topic.file.filename for reply in self.replies: if reply.has_file: yield reply.file.filename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thumbnames(self): """Returns the filenames of all thumbnails in the thread."""
if self.topic.has_file: yield self.topic.file.thumbnail_fname for reply in self.replies: if reply.has_file: yield reply.file.thumbnail_fname
<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(self, force=False): """Fetch new posts from the server. Arguments: force (bool): Force a thread update, even if thread has 404'd. Returns: int: How many new posts have been fetched. """
# The thread has already 404'ed, this function shouldn't do anything anymore. if self.is_404 and not force: return 0 if self._last_modified: headers = {'If-Modified-Since': self._last_modified} else: headers = None # random connection errors, just return 0 and try again later try: res = self._board._requests_session.get(self._api_url, headers=headers) except: # try again later return 0 # 304 Not Modified, no new posts. if res.status_code == 304: return 0 # 404 Not Found, thread died. elif res.status_code == 404: self.is_404 = True # remove post from cache, because it's gone. self._board._thread_cache.pop(self.id, None) return 0 elif res.status_code == 200: # If we somehow 404'ed, we should put ourself back in the cache. if self.is_404: self.is_404 = False self._board._thread_cache[self.id] = self # Remove self.want_update = False self.omitted_images = 0 self.omitted_posts = 0 self._last_modified = res.headers['Last-Modified'] posts = res.json()['posts'] original_post_count = len(self.replies) self.topic = Post(self, posts[0]) if self.last_reply_id and not force: self.replies.extend(Post(self, p) for p in posts if p['no'] > self.last_reply_id) else: self.replies[:] = [Post(self, p) for p in posts[1:]] new_post_count = len(self.replies) post_count_delta = new_post_count - original_post_count if not post_count_delta: return 0 self.last_reply_id = self.replies[-1].post_number return post_count_delta else: res.raise_for_status()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cas_a (freq_mhz, year): """Return the flux of Cas A given a frequency and the year of observation. Based on the formula given in Baars et al., 1977. Parameters: freq - Observation frequency in MHz. year - Year of observation. May be floating-point. Returns: s, flux in Jy. """
# The snu rule is right out of Baars et al. The dnu is corrected # for the frequency being measured in MHz, not GHz. snu = 10. ** (5.745 - 0.770 * np.log10 (freq_mhz)) # Jy dnu = 0.01 * (0.07 - 0.30 * np.log10 (freq_mhz)) # percent per yr. loss = (1 - dnu) ** (year - 1980.) return snu * loss
<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_cas_a (year): """Insert an entry for Cas A into the table of models. Need to specify the year of the observations to account for the time variation of Cas A's emission. """
year = float (year) models['CasA'] = lambda f: cas_a (f, year)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_from_vla_obs (src, Lband, Cband): """Add an entry into the models table for a source based on L-band and C-band flux densities. """
if src in models: raise PKError ('already have a model for ' + src) fL = np.log10 (1425) fC = np.log10 (4860) lL = np.log10 (Lband) lC = np.log10 (Cband) A = (lL - lC) / (fL - fC) B = lL - A * fL def fluxdens (freq_mhz): return 10. ** (A * np.log10 (freq_mhz) + B) def spindex (freq_mhz): return A models[src] = fluxdens spindexes[src] = spindex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def databiv (xy, coordouter=False, **kwargs): """Compute the main parameters of a bivariate distribution from data. The parameters are returned in the same format as used in the rest of this module. * xy: a 2D data array of shape (2, nsamp) or (nsamp, 2) * coordouter: if True, the coordinate axis is the outer axis; i.e. the shape is (2, nsamp). Otherwise, the coordinate axis is the inner axis; i.e. shape is (nsamp, 2). Returns: (sx, sy, cxy) In both cases, the first slice along the coordinate axis gives the X data (i.e., xy[0] or xy[:,0]) and the second slice gives the Y data (xy[1] or xy[:,1]). """
xy = np.asarray (xy) if xy.ndim != 2: raise ValueError ('"xy" must be a 2D array') if coordouter: if xy.shape[0] != 2: raise ValueError ('if "coordouter" is True, first axis of "xy" ' 'must have size 2') else: if xy.shape[1] != 2: raise ValueError ('if "coordouter" is False, second axis of "xy" ' 'must have size 2') cov = np.cov (xy, rowvar=coordouter, **kwargs) sx, sy = np.sqrt (np.diag (cov)) cxy = cov[0,1] return _bivcheck (sx, sy, cxy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bivrandom (x0, y0, sx, sy, cxy, size=None): """Compute random values distributed according to the specified bivariate distribution. Inputs: * x0: the center of the x distribution (i.e. its intended mean) * y0: the center of the y distribution * sx: standard deviation (not variance) of x var * sy: standard deviation (not variance) of y var * cxy: covariance (not correlation coefficient) of x and y * size (optional): the number of values to compute Returns: array of shape (size, 2); or just (2, ), if size was not specified. The bivariate parameters of the generated data are approximately recoverable by calling 'databiv(retval)'. """
from numpy.random import multivariate_normal as mvn p0 = np.asarray ([x0, y0]) cov = np.asarray ([[sx**2, cxy], [cxy, sy**2]]) return mvn (p0, cov, size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bivconvolve (sx_a, sy_a, cxy_a, sx_b, sy_b, cxy_b): """Given two independent bivariate distributions, compute a bivariate distribution corresponding to their convolution. I'm sure this is worked out in a ton of places, but I got the equations Returns: (sx_c, sy_c, cxy_c), the parameters of the convolved distribution. """
_bivcheck (sx_a, sy_a, cxy_a) _bivcheck (sx_b, sy_b, cxy_b) sx_c = np.sqrt (sx_a**2 + sx_b**2) sy_c = np.sqrt (sy_a**2 + sy_b**2) cxy_c = cxy_a + cxy_b return _bivcheck (sx_c, sy_c, cxy_c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ellplot (mjr, mnr, pa): """Utility for debugging."""
_ellcheck (mjr, mnr, pa) import omega as om th = np.linspace (0, 2 * np.pi, 200) x, y = ellpoint (mjr, mnr, pa, th) return om.quickXY (x, y, 'mjr=%f mnr=%f pa=%f' % (mjr, mnr, pa * 180 / np.pi))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def abcd2 (x0, y0, a, b, c, x, y): """Given an 2D Gaussian expressed as the ABC polynomial coefficients, compute a "squared distance parameter" such that z = exp (-0.5 * d2) Inputs: * x0: position of Gaussian center on x axis * y0: position of Gaussian center on y axis * a: such that z = exp (ax² + bxy + cy²) * b: see above * c: see above * x: x coordinates of the locations for which to evaluate d2 * y: y coordinates of the locations for which to evaluate d2 Returns: d2, distance parameter defined as above. This is pretty trivial. """
_abccheck (a, b, c) dx, dy = x - x0, y - y0 return -2 * (a * dx**2 + b * dx * dy + c * dy**2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eigh_robust(a, b=None, eigvals=None, eigvals_only=False, overwrite_a=False, overwrite_b=False, turbo=True, check_finite=True): """Robustly solve the Hermitian generalized eigenvalue problem This function robustly solves the Hermetian generalized eigenvalue problem ``A v = lambda B v`` in the case that B is not strictly positive definite. When B is strictly positive-definite, the result is equivalent to scipy.linalg.eigh() within floating-point accuracy. Parameters a : (M, M) array_like A complex Hermitian or real symmetric matrix whose eigenvalues and eigenvectors will be computed. b : (M, M) array_like, optional A complex Hermitian or real symmetric matrix. If omitted, identity matrix is assumed. eigvals : tuple (lo, hi), optional Indexes of the smallest and largest (in ascending order) eigenvalues and corresponding eigenvectors to be returned: 0 <= lo <= hi <= M-1. If omitted, all eigenvalues and eigenvectors are returned. eigvals_only : bool, optional Whether to calculate only eigenvalues and no eigenvectors. (Default: both are calculated) turbo : bool, optional Use divide and conquer algorithm (faster but expensive in memory, only for generalized eigenvalue problem and if eigvals=None) overwrite_a : bool, optional Whether to overwrite data in `a` (may improve performance) overwrite_b : bool, optional Whether to overwrite data in `b` (may improve performance) check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Returns ------- w : (N,) float ndarray The N (1<=N<=M) selected eigenvalues, in ascending order, each repeated according to its multiplicity. v : (M, N) complex ndarray (if eigvals_only == False) """
kwargs = dict(eigvals=eigvals, eigvals_only=eigvals_only, turbo=turbo, check_finite=check_finite, overwrite_a=overwrite_a, overwrite_b=overwrite_b) # Check for easy case first: if b is None: return linalg.eigh(a, **kwargs) # Compute eigendecomposition of b kwargs_b = dict(turbo=turbo, check_finite=check_finite, overwrite_a=overwrite_b) # b is a for this operation S, U = linalg.eigh(b, **kwargs_b) # Combine a and b on left hand side via decomposition of b S[S <= 0] = np.inf Sinv = 1. / np.sqrt(S) W = Sinv[:, None] * np.dot(U.T, np.dot(a, U)) * Sinv output = linalg.eigh(W, **kwargs) if eigvals_only: return output else: evals, evecs = output return evals, np.dot(U, Sinv[:, None] * evecs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_projection(self, X, W): """Compute the LPP projection matrix Parameters X : array_like, (n_samples, n_features) The input data W : array_like or sparse matrix, (n_samples, n_samples) The precomputed adjacency matrix Returns ------- P : ndarray, (n_features, self.n_components) The matrix encoding the locality preserving projection """
# TODO: check W input; handle sparse case X = check_array(X) D = np.diag(W.sum(1)) L = D - W evals, evecs = eigh_robust(np.dot(X.T, np.dot(L, X)), np.dot(X.T, np.dot(D, X)), eigvals=(0, self.n_components - 1)) return evecs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def find_common_dtype(*args): '''Returns common dtype of numpy and scipy objects. Recognizes ndarray, spmatrix and LinearOperator. All other objects are ignored (most notably None).''' dtypes = [] for arg in args: if type(arg) is numpy.ndarray or \ isspmatrix(arg) or \ isinstance(arg, LinearOperator): if hasattr(arg, 'dtype'): dtypes.append(arg.dtype) else: warnings.warn('object %s does not have a dtype.' % arg.__repr__) return numpy.find_common_type(dtypes, [])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def inner(X, Y, ip_B=None): '''Euclidean and non-Euclidean inner product. numpy.vdot only works for vectors and numpy.dot does not use the conjugate transpose. :param X: numpy array with ``shape==(N,m)`` :param Y: numpy array with ``shape==(N,n)`` :param ip_B: (optional) May be one of the following * ``None``: Euclidean inner product. * a self-adjoint and positive definite operator :math:`B` (as ``numpy.array`` or ``LinearOperator``). Then :math:`X^*B Y` is returned. * a callable which takes 2 arguments X and Y and returns :math:`\\langle X,Y\\rangle`. **Caution:** a callable should only be used if necessary. The choice potentially has an impact on the round-off behavior, e.g. of projections. :return: numpy array :math:`\\langle X,Y\\rangle` with ``shape==(m,n)``. ''' if ip_B is None or isinstance(ip_B, IdentityLinearOperator): return numpy.dot(X.T.conj(), Y) (N, m) = X.shape (_, n) = Y.shape try: B = get_linearoperator((N, N), ip_B) except TypeError: return ip_B(X, Y) if m > n: return numpy.dot((B*X).T.conj(), Y) else: return numpy.dot(X.T.conj(), B*Y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def norm_squared(x, Mx=None, inner_product=ip_euclid): '''Compute the norm^2 w.r.t. to a given scalar product.''' assert(len(x.shape) == 2) if Mx is None: rho = inner_product(x, x) else: assert(len(Mx.shape) == 2) rho = inner_product(x, Mx) if rho.shape == (1, 1): if abs(rho[0, 0].imag) > abs(rho[0, 0])*1e-10 or rho[0, 0].real < 0.0: raise InnerProductError(('<x,Mx> = %g. Is the inner product ' 'indefinite?') % rho[0, 0]) return numpy.linalg.norm(rho, 2)
<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_linearoperator(shape, A, timer=None): """Enhances aslinearoperator if A is None."""
ret = None import scipy.sparse.linalg as scipylinalg if isinstance(A, LinearOperator): ret = A elif A is None: ret = IdentityLinearOperator(shape) elif isinstance(A, numpy.ndarray) or isspmatrix(A): ret = MatrixLinearOperator(A) elif isinstance(A, numpy.matrix): ret = MatrixLinearOperator(numpy.atleast_2d(numpy.asarray(A))) elif isinstance(A, scipylinalg.LinearOperator): if not hasattr(A, 'dtype'): raise ArgumentError('scipy LinearOperator has no dtype.') ret = LinearOperator(A.shape, dot=A.matvec, dot_adj=A.rmatvec, dtype=A.dtype) else: raise TypeError('type not understood') # set up timer if requested if A is not None and not isinstance(A, IdentityLinearOperator) \ and timer is not None: ret = TimedLinearOperator(ret, timer) # check shape if shape != ret.shape: raise LinearOperatorError('shape mismatch') return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def orthonormality(V, ip_B=None): """Measure orthonormality of given basis. :param V: a matrix :math:`V=[v_1,\ldots,v_n]` with ``shape==(N,n)``. :param ip_B: (optional) the inner product to use, see :py:meth:`inner`. :return: :math:`\\| I_n - \\langle V,V \\rangle \\|_2`. """
return norm(numpy.eye(V.shape[1]) - inner(V, V, ip_B=ip_B))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def arnoldi_res(A, V, H, ip_B=None): """Measure Arnoldi residual. :param A: a linear operator that can be used with scipy's aslinearoperator with ``shape==(N,N)``. :param V: Arnoldi basis matrix with ``shape==(N,n)``. :param H: Hessenberg matrix: either :math:`\\underline{H}_{n-1}` with ``shape==(n,n-1)`` or :math:`H_n` with ``shape==(n,n)`` (if the Arnoldi basis spans an A-invariant subspace). :param ip_B: (optional) the inner product to use, see :py:meth:`inner`. :returns: either :math:`\\|AV_{n-1} - V_n \\underline{H}_{n-1}\\|` or :math:`\\|A V_n - V_n H_n\\|` (in the invariant case). """
N = V.shape[0] invariant = H.shape[0] == H.shape[1] A = get_linearoperator((N, N), A) if invariant: res = A*V - numpy.dot(V, H) else: res = A*V[:, :-1] - numpy.dot(V, H) return norm(res, ip_B=ip_B)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qr(X, ip_B=None, reorthos=1): """QR factorization with customizable inner product. :param X: array with ``shape==(N,k)`` :param ip_B: (optional) inner product, see :py:meth:`inner`. :param reorthos: (optional) numer of reorthogonalizations. Defaults to 1 (i.e. 2 runs of modified Gram-Schmidt) which should be enough in most cases (TODO: add reference). :return: Q, R where :math:`X=QR` with :math:`\\langle Q,Q \\rangle=I_k` and R upper triangular. """
if ip_B is None and X.shape[1] > 0: return scipy.linalg.qr(X, mode='economic') else: (N, k) = X.shape Q = X.copy() R = numpy.zeros((k, k), dtype=X.dtype) for i in range(k): for reortho in range(reorthos+1): for j in range(i): alpha = inner(Q[:, [j]], Q[:, [i]], ip_B=ip_B)[0, 0] R[j, i] += alpha Q[:, [i]] -= alpha * Q[:, [j]] R[i, i] = norm(Q[:, [i]], ip_B=ip_B) if R[i, i] >= 1e-15: Q[:, [i]] /= R[i, i] return Q, R
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def angles(F, G, ip_B=None, compute_vectors=False): """Principal angles between two subspaces. This algorithm is based on algorithm 6.2 in `Knyazev, Argentati. Principal angles between subspaces in an A-based scalar product: algorithms and perturbation estimates. 2002.` This algorithm can also handle small angles (in contrast to the naive cosine-based svd algorithm). :param F: array with ``shape==(N,k)``. :param G: array with ``shape==(N,l)``. :param ip_B: (optional) angles are computed with respect to this inner product. See :py:meth:`inner`. :param compute_vectors: (optional) if set to ``False`` then only the angles are returned (default). If set to ``True`` then also the principal vectors are returned. :return: * ``theta`` if ``compute_vectors==False`` * ``theta, U, V`` if ``compute_vectors==True`` where * ``theta`` is the array with ``shape==(max(k,l),)`` containing the principal angles :math:`0\\leq\\theta_1\\leq\\ldots\\leq\\theta_{\\max\\{k,l\\}}\\leq \\frac{\\pi}{2}`. * ``U`` are the principal vectors from F with :math:`\\langle U,U \\rangle=I_k`. * ``V`` are the principal vectors from G with :math:`\\langle V,V \\rangle=I_l`. The principal angles and vectors fulfill the relation :math:`\\langle U,V \\rangle = \ \\begin{bmatrix} \ \\cos(\\Theta) & 0_{m,l-m} \\\\ \ 0_{k-m,m} & 0_{k-m,l-m} \ \\end{bmatrix}` where :math:`m=\\min\\{k,l\\}` and :math:`\\cos(\\Theta)=\\operatorname{diag}(\\cos(\\theta_1),\\ldots,\\cos(\\theta_m))`. Furthermore, :math:`\\theta_{m+1}=\\ldots=\\theta_{\\max\\{k,l\\}}=\\frac{\\pi}{2}`. """
# make sure that F.shape[1]>=G.shape[1] reverse = False if F.shape[1] < G.shape[1]: reverse = True F, G = G, F QF, _ = qr(F, ip_B=ip_B) QG, _ = qr(G, ip_B=ip_B) # one or both matrices empty? (enough to check G here) if G.shape[1] == 0: theta = numpy.ones(F.shape[1])*numpy.pi/2 U = QF V = QG else: Y, s, Z = scipy.linalg.svd(inner(QF, QG, ip_B=ip_B)) Vcos = numpy.dot(QG, Z.T.conj()) n_large = numpy.flatnonzero((s**2) < 0.5).shape[0] n_small = s.shape[0] - n_large theta = numpy.r_[ numpy.arccos(s[n_small:]), # [-i:] does not work if i==0 numpy.ones(F.shape[1]-G.shape[1])*numpy.pi/2] if compute_vectors: Ucos = numpy.dot(QF, Y) U = Ucos[:, n_small:] V = Vcos[:, n_small:] if n_small > 0: RG = Vcos[:, :n_small] S = RG - numpy.dot(QF, inner(QF, RG, ip_B=ip_B)) _, R = qr(S, ip_B=ip_B) Y, u, Z = scipy.linalg.svd(R) theta = numpy.r_[ numpy.arcsin(u[::-1][:n_small]), theta] if compute_vectors: RF = Ucos[:, :n_small] Vsin = numpy.dot(RG, Z.T.conj()) # next line is hand-crafted since the line from the paper does # not seem to work. Usin = numpy.dot(RF, numpy.dot( numpy.diag(1/s[:n_small]), numpy.dot(Z.T.conj(), numpy.diag(s[:n_small])))) U = numpy.c_[Usin, U] V = numpy.c_[Vsin, V] if compute_vectors: if reverse: U, V = V, U return theta, U, V else: return theta
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gap(lamda, sigma, mode='individual'): """Compute spectral gap. Useful for eigenvalue/eigenvector bounds. Computes the gap :math:`\delta\geq 0` between two sets of real numbers ``lamda`` and ``sigma``. The gap can be computed in several ways and may not exist, see the ``mode`` parameter. :param lamda: a non-empty set :math:`\Lambda=\{\lambda_1,\ldots,\lambda_n\}` given as a single real number or a list or ``numpy.array`` with real numbers. :param sigma: a non-empty set :math:`\Sigma=\{\sigma_1,\ldots,\sigma_m\}`. See ``lamda``. :param mode: (optional). Defines how the gap should be computed. May be one of * ``'individual'`` (default): :math:`\delta=\min_{\substack{i\in\{1,\ldots,n\}\\\\j\in\{1,\ldots,m\}}} |\lambda_i - \sigma_j|`. With this mode, the gap is always be defined. * ``'interval'``: determine the maximal :math:`\delta` such that :math:`\Sigma\subset\mathbb{R}\setminus[\min_{\lambda\in\Lambda}\lambda-\delta,\max_{\lambda\in\Lambda}\lambda+\delta]`. If the gap does not exists, ``None`` is returned. :return: :math:`\delta` or ``None``. """
# sanitize input if numpy.isscalar(lamda): lamda = [lamda] lamda = numpy.array(lamda) if numpy.isscalar(sigma): sigma = [sigma] sigma = numpy.array(sigma) if not numpy.isreal(lamda).all() or not numpy.isreal(sigma).all(): raise ArgumentError('complex spectra not yet implemented') if mode == 'individual': return numpy.min(numpy.abs(numpy.reshape(lamda, (len(lamda), 1)) - numpy.reshape(sigma, (1, len(sigma))))) elif mode == 'interval': lamda_min, lamda_max = numpy.min(lamda), numpy.max(lamda) # determine all values in sigma<lamda_min or >lamda_max sigma_lo = sigma <= lamda_min sigma_hi = sigma >= lamda_max # is a sigma value in lamda interval? if not numpy.all(sigma_lo + sigma_hi): return None delta = numpy.Infinity if numpy.any(sigma_lo): delta = lamda_min - numpy.max(sigma[sigma_lo]) if numpy.any(sigma_hi): delta = numpy.min([delta, numpy.min(sigma[sigma_hi]) - lamda_max]) return delta
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bound_perturbed_gmres(pseudo, p, epsilon, deltas): '''Compute GMRES perturbation bound based on pseudospectrum Computes the GMRES bound from [SifEM13]_. ''' if not numpy.all(numpy.array(deltas) > epsilon): raise ArgumentError('all deltas have to be greater than epsilon') bound = [] for delta in deltas: # get boundary paths paths = pseudo.contour_paths(delta) # get vertices on boundary vertices = paths.vertices() # evaluate polynomial supremum = numpy.max(numpy.abs(p(vertices))) # compute bound bound.append(epsilon/(delta-epsilon) * paths.length()/(2*numpy.pi*delta) * supremum) return bound
<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_residual_norms(H, self_adjoint=False): '''Compute relative residual norms from Hessenberg matrix. It is assumed that the initial guess is chosen as zero.''' H = H.copy() n_, n = H.shape y = numpy.eye(n_, 1, dtype=H.dtype) resnorms = [1.] for i in range(n_-1): G = Givens(H[i:i+2, [i]]) if self_adjoint: H[i:i+2, i:i+3] = G.apply(H[i:i+2, i:i+3]) else: H[i:i+2, i:] = G.apply(H[i:i+2, i:]) y[i:i+2] = G.apply(y[i:i+2]) resnorms.append(numpy.abs(y[i+1, 0])) if n_ == n: resnorms.append(0.) return numpy.array(resnorms)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, x): """Apply Householder transformation to vector x. Applies the Householder transformation efficiently to the given vector. """
# make sure that x is a (N,*) matrix if len(x.shape) != 2: raise ArgumentError('x is not a matrix of shape (N,*)') if self.beta == 0: return x return x - self.beta * self.v * numpy.dot(self.v.T.conj(), x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matrix(self): """Build matrix representation of Householder transformation. Builds the matrix representation :math:`H = I - \\beta vv^*`. **Use with care!** This routine may be helpful for testing purposes but should not be used in production codes for high dimensions since the resulting matrix is dense. """
n = self.v.shape[0] return numpy.eye(n, n) - self.beta * numpy.dot(self.v, self.v.T.conj())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _apply(self, a, return_Ya=False): r'''Single application of the projection. :param a: array with ``a.shape==(N,m)``. :param return_inner: (optional) should the inner product :math:`\langle Y,a\rangle` be returned? :return: * :math:`P_{\mathcal{X},\mathcal{Y}^\perp} a = X \langle Y,X\rangle^{-1} \langle Y, a\rangle`. * :math:`\langle Y,a\rangle` if ``return_inner==True``. ''' # is projection the zero operator? if self.V.shape[1] == 0: Pa = numpy.zeros(a.shape) if return_Ya: return Pa, numpy.zeros((0, a.shape[1])) return Pa c = inner(self.W, a, ip_B=self.ip_B) if return_Ya: Ya = c.copy() if self.WR is not None: Ya = self.WR.T.conj().dot(Ya) if self.Q is not None and self.R is not None: c = scipy.linalg.solve_triangular(self.R, self.Q.T.conj().dot(c)) Pa = self.V.dot(c) if return_Ya: return Pa, Ya return Pa
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _apply_adj(self, a): # is projection the zero operator? if self.V.shape[1] == 0: return numpy.zeros(a.shape) '''Single application of the adjoint projection.''' c = inner(self.V, a, ip_B=self.ip_B) if self.Q is not None and self.R is not None: c = self.Q.dot(scipy.linalg.solve_triangular(self.R.T.conj(), c, lower=True)) return self.W.dot(c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, a, return_Ya=False): r"""Apply the projection to an array. The computation is carried out without explicitly forming the matrix corresponding to the projection (which would be an array with ``shape==(N,N)``). See also :py:meth:`_apply`. """
# is projection the zero operator? if self.V.shape[1] == 0: Pa = numpy.zeros(a.shape) if return_Ya: return Pa, numpy.zeros((0, a.shape[1])) return Pa if return_Ya: x, Ya = self._apply(a, return_Ya=return_Ya) else: x = self._apply(a) for i in range(self.iterations-1): z = a - x w = self._apply(z) x = x + w if return_Ya: return x, Ya return x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_complement(self, a, return_Ya=False): """Apply the complementary projection to an array. :param z: array with ``shape==(N,m)``. :return: :math:`P_{\\mathcal{Y}^\\perp,\\mathcal{X}}z = z - P_{\\mathcal{X},\\mathcal{Y}^\\perp} z`. """
# is projection the zero operator? --> complement is identity if self.V.shape[1] == 0: if return_Ya: return a.copy(), numpy.zeros((0, a.shape[1])) return a.copy() if return_Ya: x, Ya = self._apply(a, return_Ya=True) else: x = self._apply(a) z = a - x for i in range(self.iterations-1): w = self._apply(z) z = z - w if return_Ya: return z, Ya return z
<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(self, key): '''Return timings for `key`. Returns 0 if not present.''' if key in self and len(self[key]) > 0: return min(self[key]) else: return 0
<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_ops(self, ops): '''Return timings for dictionary ops holding the operation names as keys and the number of applications as values.''' time = 0. for op, count in ops.items(): time += self.get(op) * count return time
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def min_pos(self): '''Returns minimal positive value or None.''' if self.__len__() == 0: return ArgumentError('empty set has no minimum positive value.') if self.contains(0): return None positive = [interval for interval in self.intervals if interval.left > 0] if len(positive) == 0: return None return numpy.min(list(map(lambda i: i.left, positive)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def max_neg(self): '''Returns maximum negative value or None.''' if self.__len__() == 0: return ArgumentError('empty set has no maximum negative value.') if self.contains(0): return None negative = [interval for interval in self.intervals if interval.right < 0] if len(negative) == 0: return None return numpy.max(list(map(lambda i: i.right, negative)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def min_abs(self): '''Returns minimum absolute value.''' if self.__len__() == 0: return ArgumentError('empty set has no minimum absolute value.') if self.contains(0): return 0 return numpy.min([numpy.abs(val) for val in [self.max_neg(), self.min_pos()] if val is not 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 max_abs(self): '''Returns maximum absolute value.''' if self.__len__() == 0: return ArgumentError('empty set has no maximum absolute value.') return numpy.max(numpy.abs([self.max(), self.min()]))
<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_step(self, tol): '''Return step at which bound falls below tolerance. ''' return 2 * numpy.log(tol/2.)/numpy.log(self.base)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def minmax_candidates(self): '''Get points where derivative is zero. Useful for computing the extrema of the polynomial over an interval if the polynomial has real roots. In this case, the maximum is attained for one of the interval endpoints or a point from the result of this function that is contained in the interval. ''' from numpy.polynomial import Polynomial as P p = P.fromroots(self.roots) return p.deriv(1).roots()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def errors(self): """ Check for usage errors """
try: self.now = datetime.datetime.now() if len(self.alarm_day) < 2 or len(self.alarm_day) > 2: print("error: day: usage 'DD' such us '0%s' not '%s'" % ( self.alarm_day, self.alarm_day)) self.RUN_ALARM = False if int(self.alarm_day) > calendar.monthrange( self.now.year, self.now.month)[1] or int( self.alarm_day) < 1: print("error: day: out of range") self.RUN_ALARM = False # compare alarm time with alarm pattern if (len(self.alarm_time) != len(self.alarm_pattern) or len(self.alarm_time[0]) < 2 or len(self.alarm_time[0]) > 2 or len(self.alarm_time[1]) < 2 or len(self.alarm_time[1]) > 2): print("error: time: usage '%s'" % ":".join(self.alarm_pattern)) self.RUN_ALARM = False # compare if alarm hour or alarm minutes # is within the range if int(self.alarm_hour) not in range(0, 24): print("error: hour: out of range") self.RUN_ALARM = False if int(self.alarm_minutes) not in range(0, 60): print("error: minutes: out of range") self.RUN_ALARM = False except ValueError: print("Usage '%s'" % ":".join(self.alarm_pattern)) self.RUN_ALARM = False if not os.path.isfile(self.song): print("error: song: file does not exist") self.RUN_ALARM = 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 _get_best_subset(self, ritz): '''Return candidate set with smallest goal functional.''' # (c,\omega(c)) for all considered subsets c overall_evaluations = {} def evaluate(_subset, _evaluations): try: _evaluations[_subset] = \ self.subset_evaluator.evaluate(ritz, _subset) except utils.AssumptionError: # no evaluation possible -> move on pass # I in algo current_subset = frozenset() # evaluate empty set evaluate(current_subset, overall_evaluations) while True: # get a list of subset candidates for inclusion in current_subset # (S in algo) remaining_subset = set(range(len(ritz.values))) \ .difference(current_subset) subsets = self.subsets_generator.generate(ritz, remaining_subset) # no more candidates to check? if len(subsets) == 0: break # evaluate candidates evaluations = {} for subset in subsets: eval_subset = current_subset.union(subset) evaluate(eval_subset, evaluations) if len(evaluations) > 0: current_subset = min(evaluations, key=evaluations.get) else: # fallback: pick the subset with smallest residual # note: only a bound is used if the subset consists of more # than one index. resnorms = [numpy.sum(ritz.resnorms[list(subset)]) for subset in subsets] subset = subsets[numpy.argmin(resnorms)] current_subset = current_subset.union(subset) overall_evaluations.update(evaluations) if len(overall_evaluations) > 0: # if there was a successfull evaluation: pick the best one selection = list(min(overall_evaluations, key=overall_evaluations.get)) else: # otherwise: return empty list selection = [] # debug output requested? if self.print_results == 'number': print('# of selected deflation vectors: {0}' .format(len(selection))) elif self.print_results == 'values': print('{0} Ritz values corresponding to selected deflation ' .format(len(selection)) + 'vectors: ' + (', '.join([str(el) for el in ritz.values[selection]]))) elif self.print_results == 'timings': import operator print('Timings for all successfully evaluated choices of ' 'deflation vectors with corresponding Ritz values:') for subset, time in sorted(overall_evaluations.items(), key=operator.itemgetter(1)): print(' {0}s: '.format(time) + ', '.join([str(el) for el in ritz.values[list(subset)]])) elif self.print_results is None: pass else: raise utils.ArgumentError( 'Invalid value `{0}` for argument `print_result`. ' .format(self.print_results) + 'Valid are `None`, `number`, `values` and `timings`.') return selection
<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_default_command(self, command): """Sets a command function as the default command."""
cmd_name = command.name self.add_command(command) self.default_cmd_name = cmd_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_residual(self, z, compute_norm=False): r'''Compute residual. For a given :math:`z\in\mathbb{C}^N`, the residual .. math:: r = M M_l ( b - A z ) is computed. If ``compute_norm == True``, then also the absolute residual norm .. math:: \| M M_l (b-Az)\|_{M^{-1}} is computed. :param z: approximate solution with ``z.shape == (N, 1)``. :param compute_norm: (bool, optional) pass ``True`` if also the norm of the residual should be computed. ''' if z is None: if compute_norm: return self.MMlb, self.Mlb, self.MMlb_norm return self.MMlb, self.Mlb r = self.b - self.A*z Mlr = self.Ml*r MMlr = self.M*Mlr if compute_norm: return MMlr, Mlr, utils.norm(Mlr, MMlr, ip_B=self.ip_B) return MMlr, Mlr
<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_ip_Minv_B(self): '''Returns the inner product that is implicitly used with the positive definite preconditioner ``M``.''' if not isinstance(self.M, utils.IdentityLinearOperator): if isinstance(self.Minv, utils.IdentityLinearOperator): raise utils.ArgumentError( 'Minv has to be provided for the evaluation of the inner ' 'product that is implicitly defined by M.') if isinstance(self.ip_B, utils.LinearOperator): return self.Minv*self.ip_B else: return lambda x, y: self.ip_B(x, self.Minv*y) return self.ip_B
<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_xk(self, yk): '''Compute approximate solution from initial guess and approximate solution of the preconditioned linear system.''' if yk is not None: return self.x0 + self.linear_system.Mr * yk return self.x0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _finalize_iteration(self, yk, resnorm): '''Compute solution, error norm and residual norm if required. :return: the residual norm or ``None``. ''' self.xk = None # compute error norm if asked for if self.linear_system.exact_solution is not None: self.xk = self._get_xk(yk) self.errnorms.append(utils.norm( self.linear_system.exact_solution - self.xk, ip_B=self.linear_system.ip_B)) rkn = None # compute explicit residual if asked for or if the updated residual # is below the tolerance or if this is the last iteration if self.explicit_residual or \ resnorm/self.linear_system.MMlb_norm <= self.tol \ or self.iter+1 == self.maxiter: # compute xk if not yet done if self.xk is None: self.xk = self._get_xk(yk) # compute residual norm _, _, rkn = self.linear_system.get_residual(self.xk, compute_norm=True) # store relative residual norm self.resnorms.append(rkn/self.linear_system.MMlb_norm) # no convergence? if self.resnorms[-1] > self.tol: # no convergence in last iteration -> raise exception # (approximate solution can be obtained from exception) if self.iter+1 == self.maxiter: self._finalize() raise utils.ConvergenceError( ('No convergence in last iteration ' '(maxiter: {0}, residual: {1}).') .format(self.maxiter, self.resnorms[-1]), self) # updated residual was below but explicit is not: warn elif not self.explicit_residual \ and resnorm/self.linear_system.MMlb_norm <= self.tol: warnings.warn( 'updated residual is below tolerance, explicit ' 'residual is NOT! (upd={0} <= tol={1} < exp={2})' .format(resnorm, self.tol, self.resnorms[-1])) else: # only store updated residual self.resnorms.append(resnorm/self.linear_system.MMlb_norm) return rkn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def operations(nsteps): '''Returns the number of operations needed for nsteps of GMRES''' return {'A': 1 + nsteps, 'M': 2 + nsteps, 'Ml': 2 + nsteps, 'Mr': 1 + nsteps, 'ip_B': 2 + nsteps + nsteps*(nsteps+1)/2, 'axpy': 4 + 2*nsteps + nsteps*(nsteps+1)/2 }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def solve(self, linear_system, vector_factory=None, *args, **kwargs): '''Solve the given linear system with recycling. The provided `vector_factory` determines which vectors are used for deflation. :param linear_system: the :py:class:`~krypy.linsys.LinearSystem` that is about to be solved. :param vector_factory: (optional) see description in constructor. All remaining arguments are passed to the ``DeflatedSolver``. :returns: instance of ``DeflatedSolver`` which was used to obtain the approximate solution. The approximate solution is available under the attribute ``xk``. ''' # replace linear_system with equivalent TimedLinearSystem on demand if not isinstance(linear_system, linsys.TimedLinearSystem): linear_system = linsys.ConvertedTimedLinearSystem(linear_system) with self.timings['vector_factory']: if vector_factory is None: vector_factory = self._vector_factory # construct vector_factory if strings are provided if vector_factory == 'RitzApproxKrylov': vector_factory = factories.RitzFactory( subset_evaluator=evaluators.RitzApproxKrylov() ) elif vector_factory == 'RitzAprioriCg': vector_factory = factories.RitzFactory( subset_evaluator=evaluators.RitzApriori( Bound=utils.BoundCG ) ) elif vector_factory == 'RitzAprioriMinres': vector_factory = factories.RitzFactory( subset_evaluator=evaluators.RitzApriori( Bound=utils.BoundMinres ) ) # get deflation vectors if self.last_solver is None or vector_factory is None: U = numpy.zeros((linear_system.N, 0)) else: U = vector_factory.get(self.last_solver) with self.timings['solve']: # solve deflated linear system self.last_solver = self._DeflatedSolver(linear_system, U=U, store_arnoldi=True, *args, **kwargs) # return solver instance return self.last_solver
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_hash(func, string): """compute hash of string using given hash function"""
h = func() h.update(string) return h.hexdigest()
<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_local_serial(): ''' Retrieves the serial number from the executing host. For example, 'C02NT43PFY14' ''' return [x for x in [subprocess.Popen("system_profiler SPHardwareDataType |grep -v tray |awk '/Serial/ {print $4}'", shell=True, stdout=subprocess.PIPE).communicate()[0].strip()] if x]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _estimate_eval_intervals(ritz, indices, indices_remaining, eps_min=0, eps_max=0, eps_res=None): '''Estimate evals based on eval inclusion theorem + heuristic. :returns: Intervals object with inclusion intervals for eigenvalues ''' if len(indices) == 0: return utils.Intervals( [utils.Interval(mu-resnorm, mu+resnorm) for mu, resnorm in zip(ritz.values, ritz.resnorms)]) if len(ritz.values) == len(indices): raise utils.AssumptionError( 'selection of all Ritz pairs does not allow estimation.') if eps_res is None: eps_res = numpy.max(numpy.abs([eps_min, eps_max])) # compute quantities for bound delta_sel = numpy.linalg.norm(ritz.resnorms[indices], 2) delta_non_sel = numpy.linalg.norm(ritz.resnorms[indices_remaining], 2) delta = utils.gap(ritz.values[indices], ritz.values[indices_remaining]) mu_ints = utils.Intervals( [utils.Interval(mu+eps_min, mu+eps_max) for mu in ritz.values[indices]]) mu_min = mu_ints.min_abs() # check gap assumption #if delta_sel + delta_non_sel + eps_max - eps_min >= delta: if delta_sel + eps_max - eps_min >= delta: raise utils.AssumptionError( 'delta_sel + delta_non_sel + eps_max - eps_min >= delta' + '({0} >= {1}'.format( delta_sel + delta_non_sel + eps_max - eps_min, delta) ) # check assumption on mu_min if mu_min == 0: raise utils.AssumptionError('mu_min == 0 not allowed') # compute eta #eta = (delta_sel+eps_res)**2 * ( # 1/(delta-delta_non_sel-eps_max+eps_min) # + 1/mu_min # ) #left = - delta_non_sel + eps_min - eta #right = delta_non_sel + eps_max + eta eta = (delta_sel+eps_res)**2 * ( 1/(delta-eps_max+eps_min) + 1/mu_min ) left = eps_min - eta right = eps_max + eta # return bound return utils.Intervals( [utils.Interval(mu+left, mu+right) for mu in ritz.values[indices_remaining]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def correct(self, z): '''Correct the given approximate solution ``z`` with respect to the linear system ``linear_system`` and the deflation space defined by ``U``.''' c = self.linear_system.Ml*( self.linear_system.b - self.linear_system.A*z) c = utils.inner(self.W, c, ip_B=self.ip_B) if self.Q is not None and self.R is not None: c = scipy.linalg.solve_triangular(self.R, self.Q.T.conj().dot(c)) if self.WR is not self.VR: c = self.WR.dot(scipy.linalg.solve_triangular(self.VR, c)) return z + self.W.dot(c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _apply_projection(self, Av): '''Apply the projection and store inner product. :param v: the vector resulting from an application of :math:`M_lAM_r` to the current Arnoldi vector. (CG needs special treatment, here). ''' PAv, UAv = self.projection.apply_complement(Av, return_Ya=True) self.C = numpy.c_[self.C, UAv] return PAv
<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_initial_residual(self, x0): '''Return the projected initial residual. Returns :math:`MPM_l(b-Ax_0)`. ''' if x0 is None: Mlr = self.linear_system.Mlb else: r = self.linear_system.b - self.linear_system.A*x0 Mlr = self.linear_system.Ml*r PMlr, self.UMlr = self.projection.apply_complement(Mlr, return_Ya=True) MPMlr = self.linear_system.M*PMlr MPMlr_norm = utils.norm(PMlr, MPMlr, ip_B=self.linear_system.ip_B) return MPMlr, PMlr, MPMlr_norm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def estimate_time(self, nsteps, ndefl, deflweight=1.0): '''Estimate time needed to run nsteps iterations with deflation Uses timings from :py:attr:`linear_system` if it is an instance of :py:class:`~krypy.linsys.TimedLinearSystem`. Otherwise, an :py:class:`~krypy.utils.OtherError` is raised. :param nsteps: number of iterations. :param ndefl: number of deflation vectors. :param deflweight: (optional) the time for the setup and application of the projection for deflation is multiplied by this factor. This can be used as a counter measure for the evaluation of Ritz vectors. Defaults to 1. ''' # get ops for nsteps of this solver solver_ops = self.operations(nsteps) # define ops for deflation setup + application with ndefl deflation # vectors proj_ops = {'A': ndefl, 'M': ndefl, 'Ml': ndefl, 'Mr': ndefl, 'ip_B': (ndefl*(ndefl+1)/2 + ndefl**2 + 2*ndefl*solver_ops['Ml']), 'axpy': (ndefl*(ndefl+1)/2 + ndefl*ndefl + (2*ndefl+2)*solver_ops['Ml']) } # get timings from linear_system if not isinstance(self.linear_system, linsys.TimedLinearSystem): raise utils.RuntimeError( 'A `TimedLinearSystem` has to be used in order to obtain ' 'timings.') timings = self.linear_system.timings return (timings.get_ops(solver_ops) + deflweight*timings.get_ops(proj_ops))
<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_vectors(self, indices=None): '''Compute Ritz vectors.''' H_ = self._deflated_solver.H (n_, n) = H_.shape coeffs = self.coeffs if indices is None else self.coeffs[:, indices] return numpy.c_[self._deflated_solver.V[:, :n], self._deflated_solver.projection.U].dot(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 get_explicit_residual(self, indices=None): '''Explicitly computes the Ritz residual.''' ritz_vecs = self.get_vectors(indices) return self._deflated_solver.linear_system.MlAMr * ritz_vecs \ - ritz_vecs * self.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 get_explicit_resnorms(self, indices=None): '''Explicitly computes the Ritz residual norms.''' res = self.get_explicit_residual(indices) # apply preconditioner linear_system = self._deflated_solver.linear_system Mres = linear_system.M * res # compute norms resnorms = numpy.zeros(res.shape[1]) for i in range(resnorms.shape[0]): resnorms[i] = utils.norm(res[:, [i]], Mres[:, [i]], ip_B=linear_system.ip_B) return resnorms
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def transform_data(self, data): '''Transform Pandas Timeseries into JSON format Parameters ---------- data: DataFrame or Series Pandas DataFrame or Series must have datetime index Returns ------- JSON to object.json_data Example ------- >>>vis.transform_data(df) >>>vis.json_data ''' def type_check(value): '''Type check values for JSON serialization. Native Python JSON serialization will not recognize some Numpy data types properly, so they must be explictly converted.''' if pd.isnull(value): return None elif (isinstance(value, pd.tslib.Timestamp) or isinstance(value, pd.Period)): return time.mktime(value.timetuple()) elif isinstance(value, (int, np.integer)): return int(value) elif isinstance(value, (float, np.float_)): return float(value) elif isinstance(value, str): return str(value) else: return value objectify = lambda dat: [{"x": type_check(x), "y": type_check(y)} for x, y in dat.iteritems()] self.raw_data = data if isinstance(data, pd.Series): data.name = data.name or 'data' self.json_data = [{'name': data.name, 'data': objectify(data)}] elif isinstance(data, pd.DataFrame): self.json_data = [{'name': x[0], 'data': objectify(x[1])} for x in data.iteritems()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _build_graph(self): '''Build Rickshaw graph syntax with all data''' # Set palette colors if necessary if not self.colors: self.palette = self.env.get_template('palette.js') self.template_vars.update({'palette': self.palette.render()}) self.colors = {x['name']: 'palette.color()' for x in self.json_data} template_vars = [] for index, dataset in enumerate(self.json_data): group = 'datagroup' + str(index) template_vars.append({'name': str(dataset['name']), 'color': self.colors[dataset['name']], 'data': 'json[{0}].data'.format(index)}) variables = {'dataset': template_vars, 'width': self.width, 'height': self.height, 'render': self.renderer, 'chart_id': self.chart_id} if not self.y_zero: variables.update({'min': "min: 'auto',"}) graph = self.env.get_template('graph.js') self.template_vars.update({'graph': graph.render(variables)})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create_chart(self, html_path='index.html', data_path='data.json', js_path='rickshaw.min.js', css_path='rickshaw.min.css', html_prefix=''): '''Save bearcart output to HTML and JSON. Parameters ---------- html_path: string, default 'index.html' Path for html output data_path: string, default 'data.json' Path for data JSON output js_path: string, default 'rickshaw.min.js' If passed, the Rickshaw javascript library will be saved to the path. The file must be named "rickshaw.min.js" css_path: string, default 'rickshaw.min.css' If passed, the Rickshaw css library will be saved to the path. The file must be named "rickshaw.min.css" html_prefix: Prefix path to be appended to all the other paths for file creation, but not in the generated html file. This is needed if the html file does not live in the same folder as the running python script. Returns ------- HTML, JSON, JS, and CSS Example -------- >>>vis.create_chart(html_path='myvis.html', data_path='visdata.json'), js_path='rickshaw.min.js', cs_path='rickshaw.min.css') ''' self.template_vars.update({'data_path': str(data_path), 'js_path': js_path, 'css_path': css_path, 'chart_id': self.chart_id, 'y_axis_id': self.y_axis_id, 'legend_id': self.legend_id, 'slider_id': self.slider_id}) self._build_graph() html = self.env.get_template('bcart_template.html') self.HTML = html.render(self.template_vars) with open(os.path.join(html_prefix, html_path), 'w') as f: f.write(self.HTML) with open(os.path.join(html_prefix, data_path), 'w') as f: json.dump(self.json_data, f, sort_keys=True, indent=4, separators=(',', ': ')) if js_path: js = resource_string('bearcart', 'rickshaw.min.js') with open(os.path.join(html_prefix, js_path), 'w') as f: f.write(js) if css_path: css = resource_string('bearcart', 'rickshaw.min.css') with open(os.path.join(html_prefix, css_path), 'w') as f: f.write(css)
<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_expire(self, y = 2999, mon = 12, d = 28, h = 23, min_ = 59, s = 59): """This method is used to change the expire date of a group - y is the year between 1 and 9999 inclusive - mon is the month between 1 and 12 - d is a day in the given month - h is a hour between 0 and 23 - min_ is a minute between 0 and 59 - s is a second between 0 and 59 The special date 2999-12-28 23:59:59 means that group expires never. If only an uuid is given the expire date will set to this one. """
if type(y) is not int or type(mon) is not int or type(d) is not int or \ type(h) is not int or type(min_) is not int or type(s) is not int: raise KPError("Date variables must be integers") elif y > 9999 or y < 1 or mon > 12 or mon < 1 or d > 31 or d < 1 or \ h > 23 or h < 0 or min_ > 59 or min_ < 0 or s > 59 or s < 0: raise KPError("No legal date") elif ((mon == 1 or mon == 3 or mon == 5 or mon == 7 or mon == 8 or \ mon == 10 or mon == 12) and d > 31) or ((mon == 4 or mon == 6 or \ mon == 9 or mon == 11) and d > 30) or (mon == 2 and d > 28): raise KPError("Given day doesn't exist in given month") else: self.expire = datetime(y, mon, d, h, min_, s) self.last_mod = datetime.now().replace(microsecond = 0) 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 create_entry(self, title='', image=1, url='', username='', password='', comment='', y=2999, mon=12, d=28, h=23, min_=59, s=59): """This method creates an entry in this group. Compare to StdEntry for information about the arguments. One of the following arguments is needed: - title - url - username - password - comment """
return self.db.create_entry(self, title, image, url, username, password, comment, y, mon, d, h, min_, s)
<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_title(self, title = None): """This method is used to change an entry title. A new title string is needed. """
if title is None or type(title) is not str: raise KPError("Need a new title.") else: self.title = title self.last_mod = datetime.now().replace(microsecond=0) 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_image(self, image = None): """This method is used to set the image number. image must be an unsigned int. """
if image is None or type(image) is not int: raise KPError("Need a new image number") else: self.image = image self.last_mod = datetime.now().replace(microsecond=0) 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_url(self, url = None): """This method is used to set the url. url must be a string. """
if url is None or type(url) is not str: raise KPError("Need a new image number") else: self.url = url self.last_mod = datetime.now().replace(microsecond=0) 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_username(self, username = None): """This method is used to set the username. username must be a string. """
if username is None or type(username) is not str: raise KPError("Need a new image number") else: self.username = username self.last_mod = datetime.now().replace(microsecond=0) 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_password(self, password = None): """This method is used to set the password. password must be a string. """
if password is None or type(password) is not str: raise KPError("Need a new image number") else: self.password = password self.last_mod = datetime.now().replace(microsecond=0) 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_comment(self, comment = None): """This method is used to the the comment. comment must be a string. """
if comment is None or type(comment) is not str: raise KPError("Need a new image number") else: self.comment = comment self.last_mod = datetime.now().replace(microsecond=0) return True