text
stringlengths
0
1.05M
meta
dict
"""Affine transformation class """ import os import numpy as np from six import string_types class Transform(object): ''' A standard affine transform. Typically holds a transform from anatomical magnet space to epi file space. ''' def __init__(self, xfm, reference): self.xfm = xfm self.reference = None if isstr(reference): import nibabel try: self.reference = nibabel.load(reference) self.shape = self.reference.shape[:3][::-1] except IOError: self.reference = reference elif isinstance(reference, tuple): self.shape = reference else: self.reference = reference self.shape = self.reference.shape[:3][::-1] def __call__(self, pts): return np.dot(self.xfm, np.hstack([pts, np.ones((len(pts),1))]).T)[:3].T @property def inv(self): ref = self.reference if ref is None: ref = self.shape return Transform(np.linalg.inv(self.xfm), ref) def __mul__(self, other): ref = self.reference if ref is None: ref = self.shape if isinstance(other, Transform): other = other.xfm return Transform(np.dot(self.xfm, other), ref) def __rmul__(self, other): ref = self.reference if ref is None: ref = self.shape if isinstance(other, Transform): other = other.xfm return Transform(np.dot(other, self.xfm), ref) def __repr__(self): try: path, fname = os.path.split(self.reference.get_filename()) return "<Transform into %s space>"%fname except AttributeError: return "<Reference free affine transform>" def save(self, subject, name, xfmtype="magnet"): if self.reference is None: raise ValueError('Cannot save reference-free transforms into the database') from .database import db db.save_xfm(subject, name, self.xfm, xfmtype=xfmtype, reference=self.reference.get_filename()) @classmethod def from_fsl(cls, xfm, func_nii, anat_nii): """Converts an fsl transform to a pycortex transform. Converts a transform computed using FSL's FLIRT to a transform ("xfm") object in pycortex. The transform must have been computed FROM the nifti volume specified in `func_nii` TO the volume specified in `anat_nii` (See Notes below). Parameters ---------- xfm : array 4x4 transformation matrix, loaded from an FSL .mat file, for a transform computed FROM the func_nii volume TO the anat_nii volume. Alternatively, a string file name for the FSL .mat file. anat_nii : str or nibabel.Nifti1Image nibabel image object (or path to nibabel-readable image) for anatomical volume from which cortical surface was created func_nii : str or nibabel.Nifti1Image nibabel image object (or string path to nibabel-readable image) for (functional) data volume to be projected onto cortical surface Returns ------- xfm : cortex.xfm.Transform object A pycortex COORD transform. Notes ----- The transform is assumed to be computed FROM the functional data TO the anatomical data. In FSL speak, that means that the arguments to flirt should have been: flirt -in <func_nii> -ref <anat_nii> ... """ ## -- Adapted from dipy.external.fsl.flirt2aff -- ## import nibabel import numpy.linalg as npl inv = npl.inv # Load transform from text file, if string is provided if isinstance(xfm, string_types): with open(xfm, 'r') as fid: L = fid.readlines() xfm = np.array([[np.float(s) for s in ll.split() if s] for ll in L]) # Internally, pycortex computes the OPPOSITE transform: from anatomical volume to functional volume. # Thus, assign anat to "infile" (starting point for transform) infile = anat_nii # Assign func to "reffile" (end point for transform) reffile = func_nii # and invert the usual direction (change from func>anat to anat>func) xfm = inv(xfm) try: inIm = nibabel.load(infile) except AttributeError: inIm = infile refIm = nibabel.load(reffile) in_hdr = inIm.get_header() ref_hdr = refIm.get_header() # get_zooms gets the positive voxel sizes as returned in the header inspace = np.diag(in_hdr.get_zooms()[:3] + (1,)) refspace = np.diag(ref_hdr.get_zooms()[:3] + (1,)) # Since FSL does not use the full transform info in the nifti header, # determine whether the transform indicates that the X axis should be # flipped; if so, flip the X axis (for both infile and reffile) if npl.det(in_hdr.get_best_affine())>=0: inspace = np.dot(inspace, _x_flipper(in_hdr.get_data_shape()[0])) if npl.det(ref_hdr.get_best_affine())>=0: refspace = np.dot(refspace, _x_flipper(ref_hdr.get_data_shape()[0])) inAffine = inIm.get_affine() coord = np.dot(inv(refspace),np.dot(xfm,np.dot(inspace,inv(inAffine)))) return cls(coord, refIm) def to_fsl(self, anat_nii, direction='func>anat'): """Converts a pycortex transform to an FSL transform. Uses the stored "reference" file provided when the transform was created (usually a functional data or statistical volume) and the supplied anatomical file to create an FSL transform. By default, returns the transform FROM the refernce volume (usually the functional data volume) to the anatomical volume (`anat_nii` input). Parameters ---------- anat_nii : str or nibabel.Nifti1Image nibabel image object (or path to nibabel-readable image) for anatomical volume from which cortical surface was created direction : str, optional {'func>anat', 'anat>func'} Direction of transform to return. Defaults to 'func>anat' Notes ----- This function will only work for "coord" transform objects, (those retrieved with cortex.db.get_xfm(xfmtype='coord',...)). It will fail hard for "magnet" transforms! """ import nibabel import numpy.linalg as npl inv = npl.inv ## -- Internal notes -- ## # pycortex transforms are internally stored as anatomical space -> functional data space # transforms. Thus the anatomical file is the "infile" in FSL-speak. infile = anat_nii try: inIm = nibabel.load(infile) except AttributeError: inIm = infile in_hdr = inIm.get_header() ref_hdr = self.reference.get_header() # get_zooms gets the positive voxel sizes as returned in the header inspace = np.diag(in_hdr.get_zooms()[:3] + (1,)) refspace = np.diag(ref_hdr.get_zooms()[:3] + (1,)) # Since FSL does not use the full transform info in the nifti header, # determine whether the transform indicates that the X axis should be # flipped; if so, flip the X axis (for both infile and reffile) if npl.det(in_hdr.get_best_affine())>=0: print("Determinant is > 0: FLIPPING!") inspace = np.dot(inspace, _x_flipper(in_hdr.get_data_shape()[0])) if npl.det(ref_hdr.get_best_affine())>=0: print("Determinant is > 0: FLIPPING!") refspace = np.dot(refspace, _x_flipper(ref_hdr.get_data_shape()[0])) inAffine = inIm.get_affine() fslx = np.dot(refspace,np.dot(self.xfm,np.dot(inAffine,inv(inspace)))) if direction=='func>anat': return inv(fslx) elif direction=='anat>func': return fslx @classmethod def from_freesurfer(cls, fs_register, func_nii, subject, freesurfer_subject_dir=None): """Converts a FreeSurfer transform to a pycortex transform. Converts a transform computed using FreeSurfer alignment tools (e.g., bbregister) to a transform ("xfm") object in pycortex. The transform must have been computed FROM the nifti volume specified in `func_nii` TO the anatomical volume of the FreeSurfer subject `subject` (See Notes below). Parameters ---------- fs_register : array 4x4 transformation matrix, described in an FreeSurfer .dat or .lta file, for a transform computed FROM the func_nii volume TO the anatomical volume of the FreeSurfer subject `subject`. Alternatively, a string file name for the FreeSurfer .dat or .lta file. func_nii : str or nibabel.Nifti1Image nibabel image object (or string path to nibabel-readable image) for (functional) data volume to be projected onto cortical surface subject : str FreeSurfer subject name for which the anatomical volume was registered for. freesurfer_subject_dir : str | None Directory of FreeSurfer subjects. Defaults to the value for the environment variable 'SUBJECTS_DIR' (which should be set by freesurfer) Returns ------- xfm : cortex.xfm.Transform object A pycortex COORD transform. Notes ----- The transform is assumed to be computed FROM the functional data TO the anatomical data of the specified FreeSurfer subject. In FreeSurfer speak, that means that the arguments to FreeSurfer alignment tools should have been: bbregister --s <subject> --mov <func_nii> --reg <fs_register> ... """ import subprocess import nibabel import numpy.linalg as npl inv = npl.inv # Load anatomical to functional transform from register.dat file, if string is provided if isinstance(fs_register, string_types): with open(fs_register, 'r') as fid: L = fid.readlines() anat2func = np.array([[np.float(s) for s in ll.split() if s] for ll in L[4:8]]) else: anat2func = fs_register # Set FreeSurfer subject directory if freesurfer_subject_dir is None: freesurfer_subject_dir = os.environ['SUBJECTS_DIR'] # Set path to the anatomical volume used to compute fs_register anat_mgz = os.path.join(freesurfer_subject_dir, subject, 'mri', 'orig.mgz') # Read vox2ras transform for the anatomical volume try: cmd = ('mri_info', '--vox2ras', anat_mgz) L = decode(subprocess.check_output(cmd)).splitlines() anat_vox2ras = np.array([[np.float(s) for s in ll.split() if s] for ll in L]) except OSError: print ("Error occured while executing:\n{}".format(' '.join(cmd))) raise # Read tkrvox2ras transform for the anatomical volume try: cmd = ('mri_info', '--vox2ras-tkr', anat_mgz) L = decode(subprocess.check_output(cmd)).splitlines() anat_tkrvox2ras = np.array([[np.float(s) for s in ll.split() if s] for ll in L]) except OSError: print ("Error occured while executing:\n{}".format(' '.join(cmd))) raise # Read tkvox2ras transform for the functional volume try: cmd = ('mri_info', '--vox2ras-tkr', func_nii) L = decode(subprocess.check_output(cmd)).splitlines() # The [1:] index skips a first line that is present only if an error occurs # or some info is missing when the transform is created - i.e. # not in all cases, just in the case that the transform is # created exactly as it is now. if len(L) == 5: L = L[1:] func_tkrvox2ras = np.array([[np.float(s) for s in ll.split() if s] for ll in L]) except OSError: print ("Error occured while executing:\n{}".format(' '.join(cmd))) raise # Calculate pycorex transform (i.e. scanner to functional transform) coord = np.dot(inv(func_tkrvox2ras), np.dot(anat2func, np.dot(anat_tkrvox2ras, inv(anat_vox2ras)))) try: refIm = nibabel.load(func_nii) except AttributeError: refIm = func_nii return cls(coord, refIm) def to_freesurfer(self, fs_register, subject, freesurfer_subject_dir=None): """Converts a pycortex transform to a FreeSurfer transform. Converts a transform stored in pycortex xfm object to the FreeSurfer format (i.e., register.dat format: https://surfer.nmr.mgh.harvard.edu/fswiki/RegisterDat) Parameters ---------- fs_register : str Output path for the FreeSurfer formatted transform to be output. subject : str FreeSurfer subject name from which the pycortex subject was imported freesurfer_subject_dir : str | None Directory of FreeSurfer subjects. If None, defaults to the value for the environment variable 'SUBJECTS_DIR' (which should be set by freesurfer) """ import tempfile import subprocess import nibabel import numpy.linalg as npl from .database import db inv = npl.inv # Set path to the anatomical volume for the FreeSurfer subject anat = db.get_anat(subject, type='raw') # Read vox2ras transform for the anatomical volume anat_vox2ras = anat.affine # Read tkrvox2ras transform for the anatomical volume try: cmd = ('mri_info', '--vox2ras-tkr', anat.get_filename()) L = decode(subprocess.check_output(cmd)).splitlines() anat_tkrvox2ras = np.array([[np.float(s) for s in ll.split() if s] for ll in L]) except OSError: print ("Error occured while executing:\n{}".format(' '.join(cmd))) raise # Read tkvox2ras transform for the functional volume try: cmd = ('mri_info', '--vox2ras-tkr', self.reference.get_filename()) L = decode(subprocess.check_output(cmd)).splitlines() # The [1:] index skips a first line that is present only if an error occurs # or some info is missing when the transform is created - i.e. # not in all cases, just in the case that the transform is # created exactly as it is now. if len(L) == 5: L = L[1:] func_tkrvox2ras = np.array([[np.float(s) for s in ll.split() if s] for ll in L]) except OSError: print ("Error occured while executing:\n{}".format(' '.join(cmd))) raise # Debugging code #print('Shape of func_tkrvox2ras is: [SHOULD BE (4,4) !!]') #print(func_tkrvox2ras.shape) # Read voxel resolution of the functional volume func_voxres = self.reference.header.get_zooms() # Calculate FreeSurfer transform fs_anat2func = np.dot(func_tkrvox2ras, np.dot(self.xfm, np.dot(anat_vox2ras, inv(anat_tkrvox2ras)))) # Debugging code #if not fs_anat2func.shape == (4, 4): # raise Exception("bad assumptions led to bad transformation matrix.") # Write out to `fs_register` in register.dat format with open(fs_register, 'w') as fid: fid.write('{}\n'.format(subject)) fid.write('{:.6f}\n'.format(func_voxres[0])) fid.write('{:.6f}\n'.format(func_voxres[1])) fid.write('0.150000\n') for row in fs_anat2func: fid.write(' '.join(['{:.15e}'.format(x) for x in row]) + '\n') print('Wrote:') subprocess.call(('cat', fs_register)) return fs_anat2func def isstr(obj): """Check for stringy-ness in python 2.7 or 3""" try: return isinstance(obj, basestring) except NameError: return isinstance(obj, str) def decode(obj): if isinstance(obj, bytes): obj = obj.decode() return obj def _x_flipper(N_i): #Copied from dipy flipr = np.diag([-1, 1, 1, 1]) flipr[0,3] = N_i - 1 return flipr
{ "repo_name": "gallantlab/pycortex", "path": "cortex/xfm.py", "copies": "1", "size": "16398", "license": "bsd-2-clause", "hash": -2960051944227231000, "line_mean": 39.7910447761, "line_max": 109, "alpha_frac": 0.601780705, "autogenerated": false, "ratio": 3.7914450867052025, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9872226267224766, "avg_score": 0.004199904896087327, "num_lines": 402 }
"""Affine transformation matrices The 3x3 augmented affine transformation matrix for transformations in two dimensions is illustrated below. | x' | | a b c | | x | | y' | = | d e f | | y | | 1 | | 0 0 1 | | 1 | The Affine package is derived from Casey Duncan's Planar package. See the copyright statement below. """ ############################################################################# # Copyright (c) 2010 by Casey Duncan # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name(s) of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AS IS AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO # EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################# from __future__ import division from collections import namedtuple import math __all__ = ['Affine'] __author__ = "Sean Gillies" __version__ = "2.0.0" EPSILON = 1e-5 class TransformNotInvertibleError(Exception): """The transform could not be inverted""" # Define assert_unorderable() depending on the language # implicit ordering rules. This keeps things consistent # across major Python versions try: 3 > "" except TypeError: # pragma: no cover # No implicit ordering (newer Python) def assert_unorderable(a, b): """Assert that a and b are unorderable""" return NotImplemented else: # pragma: no cover # Implicit ordering by default (older Python) # We must raise an exception ourselves # To prevent nonsensical ordering def assert_unorderable(a, b): """Assert that a and b are unorderable""" raise TypeError("unorderable types: %s and %s" % (type(a).__name__, type(b).__name__)) def cached_property(func): """Special property decorator that caches the computed property value in the object's instance dict the first time it is accessed. """ name = func.__name__ doc = func.__doc__ def getter(self, name=name): try: return self.__dict__[name] except KeyError: self.__dict__[name] = value = func(self) return value getter.func_name = name return property(getter, doc=doc) def cos_sin_deg(deg): """Return the cosine and sin for the given angle in degrees. With special-case handling of multiples of 90 for perfect right angles. """ deg = deg % 360.0 if deg == 90.0: return 0.0, 1.0 elif deg == 180.0: return -1.0, 0 elif deg == 270.0: return 0, -1.0 rad = math.radians(deg) return math.cos(rad), math.sin(rad) class Affine( namedtuple('Affine', ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'))): """Two dimensional affine transform for 2D linear mapping. Parallel lines are preserved by these transforms. Affine transforms can perform any combination of translations, scales/flips, shears, and rotations. Class methods are provided to conveniently compose transforms from these operations. Internally the transform is stored as a 3x3 transformation matrix. The transform may be constructed directly by specifying the first two rows of matrix values as 6 floats. Since the matrix is an affine transform, the last row is always ``(0, 0, 1)``. :param members: 6 floats for the first two matrix rows. :type members: float """ precision = EPSILON def __new__(self, *members): if len(members) == 6: mat3x3 = [x * 1.0 for x in members] + [0.0, 0.0, 1.0] return tuple.__new__(Affine, mat3x3) else: raise TypeError( "Expected 6 coefficients, found %d" % len(members)) @classmethod def from_gdal(cls, c, a, b, f, d, e): """Use same coefficient order as GDAL's GetGeoTransform(). :param c, a, b, f, d, e: 6 floats ordered by GDAL. :rtype: Affine """ members = [a, b, c, d, e, f] mat3x3 = [x * 1.0 for x in members] + [0.0, 0.0, 1.0] return tuple.__new__(cls, mat3x3) @classmethod def identity(cls): """Return the identity transform. :rtype: Affine """ return identity @classmethod def translation(cls, xoff, yoff): """Create a translation transform from an offset vector. :param xoff: Translation x offset. :type xoff: float :param yoff: Translation y offset. :type yoff: float :rtype: Affine """ return tuple.__new__( cls, (1.0, 0.0, xoff, 0.0, 1.0, yoff, 0.0, 0.0, 1.0)) @classmethod def scale(cls, *scaling): """Create a scaling transform from a scalar or vector. :param scaling: The scaling factor. A scalar value will scale in both dimensions equally. A vector scaling value scales the dimensions independently. :type scaling: float or sequence :rtype: Affine """ if len(scaling) == 1: sx = sy = float(scaling[0]) else: sx, sy = scaling return tuple.__new__( cls, (sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0)) @classmethod def shear(cls, x_angle=0, y_angle=0): """Create a shear transform along one or both axes. :param x_angle: Shear angle in degrees parallel to the x-axis. :type x_angle: float :param y_angle: Shear angle in degrees parallel to the y-axis. :type y_angle: float :rtype: Affine """ mx = math.tan(math.radians(x_angle)) my = math.tan(math.radians(y_angle)) return tuple.__new__( cls, (1.0, mx, 0.0, my, 1.0, 0.0, 0.0, 0.0, 1.0)) @classmethod def rotation(cls, angle, pivot=None): """Create a rotation transform at the specified angle. A pivot point other than the coordinate system origin may be optionally specified. :param angle: Rotation angle in degrees, counter-clockwise about the pivot point. :type angle: float :param pivot: Point to rotate about, if omitted the rotation is about the origin. :type pivot: sequence :rtype: Affine """ ca, sa = cos_sin_deg(angle) if pivot is None: return tuple.__new__( cls, (ca, -sa, 0.0, sa, ca, 0.0, 0.0, 0.0, 1.0)) else: px, py = pivot return tuple.__new__( cls, (ca, -sa, px - px * ca + py * sa, sa, ca, py - px * sa - py * ca, 0.0, 0.0, 1.0)) def __str__(self): """Concise string representation.""" return ("|% .2f,% .2f,% .2f|\n" "|% .2f,% .2f,% .2f|\n" "|% .2f,% .2f,% .2f|") % self def __repr__(self): """Precise string representation.""" return ("Affine(%r, %r, %r,\n" " %r, %r, %r)") % self[:6] def to_gdal(self): """Return same coefficient order as GDAL's SetGeoTransform(). :rtype: tuple """ return (self.c, self.a, self.b, self.f, self.d, self.e) @property def xoff(self): """Alias for 'c'""" return self.c @property def yoff(self): """Alias for 'f'""" return self.f @cached_property def determinant(self): """The determinant of the transform matrix. This value is equal to the area scaling factor when the transform is applied to a shape. """ a, b, c, d, e, f, g, h, i = self return a * e - b * d @property def is_identity(self): """True if this transform equals the identity matrix, within rounding limits. """ return self is identity or self.almost_equals(identity, self.precision) @property def is_rectilinear(self): """True if the transform is rectilinear. i.e., whether a shape would remain axis-aligned, within rounding limits, after applying the transform. """ a, b, c, d, e, f, g, h, i = self return ((abs(a) < self.precision and abs(e) < self.precision) or (abs(d) < self.precision and abs(b) < self.precision)) @property def is_conformal(self): """True if the transform is conformal. i.e., if angles between points are preserved after applying the transform, within rounding limits. This implies that the transform has no effective shear. """ a, b, c, d, e, f, g, h, i = self return abs(a * b + d * e) < self.precision @property def is_orthonormal(self): """True if the transform is orthonormal. Which means that the transform represents a rigid motion, which has no effective scaling or shear. Mathematically, this means that the axis vectors of the transform matrix are perpendicular and unit-length. Applying an orthonormal transform to a shape always results in a congruent shape. """ a, b, c, d, e, f, g, h, i = self return (self.is_conformal and abs(1.0 - (a * a + d * d)) < self.precision and abs(1.0 - (b * b + e * e)) < self.precision) @cached_property def is_degenerate(self): """True if this transform is degenerate. Which means that it will collapse a shape to an effective area of zero. Degenerate transforms cannot be inverted. """ return self.determinant == 0.0 @property def column_vectors(self): """The values of the transform as three 2D column vectors""" a, b, c, d, e, f, _, _, _ = self return (a, d), (b, e), (c, f) def almost_equals(self, other, precision=EPSILON): """Compare transforms for approximate equality. :param other: Transform being compared. :type other: Affine :return: True if absolute difference between each element of each respective transform matrix < ``self.precision``. """ for i in (0, 1, 2, 3, 4, 5): if abs(self[i] - other[i]) >= precision: return False return True def __gt__(self, other): return assert_unorderable(self, other) __ge__ = __lt__ = __le__ = __gt__ # Override from base class. We do not support entrywise # addition, subtraction or scalar multiplication because # the result is not an affine transform def __add__(self, other): raise TypeError("Operation not supported") __iadd__ = __add__ def __mul__(self, other): """Apply the transform using matrix multiplication, creating a resulting object of the same type. A transform may be applied to another transform, a vector, vector array, or shape. :param other: The object to transform. :type other: Affine, :class:`~planar.Vec2`, :class:`~planar.Vec2Array`, :class:`~planar.Shape` :rtype: Same as ``other`` """ sa, sb, sc, sd, se, sf, _, _, _ = self if isinstance(other, Affine): oa, ob, oc, od, oe, of, _, _, _ = other return tuple.__new__( Affine, (sa * oa + sb * od, sa * ob + sb * oe, sa * oc + sb * of + sc, sd * oa + se * od, sd * ob + se * oe, sd * oc + se * of + sf, 0.0, 0.0, 1.0)) else: try: vx, vy = other except Exception: return NotImplemented return (vx * sa + vy * sb + sc, vx * sd + vy * se + sf) def __imul__(self, other): if isinstance(other, Affine) or isinstance(other, tuple): return self.__mul__(other) else: return NotImplemented def itransform(self, seq): """Transform a sequence of points or vectors in place. :param seq: Mutable sequence of :class:`~planar.Vec2` to be transformed. :returns: None, the input sequence is mutated in place. """ if self is not identity and self != identity: sa, sb, sc, sd, se, sf, _, _, _ = self for i, (x, y) in enumerate(seq): seq[i] = (x * sa + y * sd + sc, x * sb + y * se + sf) def __invert__(self): """Return the inverse transform. :raises: :except:`TransformNotInvertible` if the transform is degenerate. """ if self.is_degenerate: raise TransformNotInvertibleError( "Cannot invert degenerate transform") idet = 1.0 / self.determinant sa, sb, sc, sd, se, sf, _, _, _ = self ra = se * idet rb = -sb * idet rd = -sd * idet re = sa * idet return tuple.__new__( Affine, (ra, rb, -sc * ra - sf * rb, rd, re, -sc * rd - sf * re, 0.0, 0.0, 1.0)) __hash__ = tuple.__hash__ # hash is not inherited in Py 3 def __getnewargs__(self): # Required for unpickling. # Normal unpickling creates a situation where __new__ receives all 9 # elements rather than the 6 that are required for the constructor. # This method ensures that only the 6 are provided. return self.a, self.b, self.c, self.d, self.e, self.f identity = Affine(1, 0, 0, 0, 1, 0) """The identity transform""" # Miscellaneous utilities def loadsw(s): """Returns Affine from the contents of a world file string. This method also translates the coefficients from from center- to corner-based coordinates. :param s: str with 6 floats ordered in a world file. :rtype: Affine """ if not hasattr(s, 'split'): raise TypeError("Cannot split input string") coeffs = s.split() if len(coeffs) != 6: raise ValueError("Expected 6 coefficients, found %d" % len(coeffs)) a, d, b, e, c, f = [float(x) for x in coeffs] center = tuple.__new__(Affine, [a, b, c, d, e, f, 0.0, 0.0, 1.0]) return center * Affine.translation(-0.5, -0.5) def dumpsw(obj): """Return string for a world file. This method also translates the coefficients from from corner- to center-based coordinates. :rtype: str """ center = obj * Affine.translation(0.5, 0.5) return '\n'.join(repr(getattr(center, x)) for x in list('adbecf')) + '\n' # vim: ai ts=4 sts=4 et sw=4 tw=78
{ "repo_name": "ToddSmall/affine", "path": "affine/__init__.py", "copies": "1", "size": "15872", "license": "bsd-3-clause", "hash": -8132406815322374000, "line_mean": 32.2050209205, "line_max": 79, "alpha_frac": 0.5735257056, "autogenerated": false, "ratio": 3.891149791615592, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9962583447006388, "avg_score": 0.0004184100418410042, "num_lines": 478 }
"""Affine transforms, both in general and specific, named transforms.""" from math import sin, cos, tan, pi __all__ = ['affine_transform', 'rotate', 'scale', 'skew', 'translate'] def affine_transform(geom, matrix): """Returns a transformed geometry using an affine transformation matrix. The coefficient matrix is provided as a list or tuple with 6 or 12 items for 2D or 3D transformations, respectively. For 2D affine transformations, the 6 parameter matrix is: [a, b, d, e, xoff, yoff] which represents the augmented matrix: / a b xoff \ [x' y' 1] = [x y 1] | d e yoff | \ 0 0 1 / or the equations for the transformed coordinates: x' = a * x + b * y + xoff y' = d * x + e * y + yoff For 3D affine transformations, the 12 parameter matrix is: [a, b, c, d, e, f, g, h, i, xoff, yoff, zoff] which represents the augmented matrix: / a b c xoff \ [x' y' z' 1] = [x y z 1] | d e f yoff | | g h i zoff | \ 0 0 0 1 / or the equations for the transformed coordinates: x' = a * x + b * y + c * z + xoff y' = d * x + e * y + f * z + yoff z' = g * x + h * y + i * z + zoff """ if geom.is_empty: return geom if len(matrix) == 6: ndim = 2 a, b, d, e, xoff, yoff = matrix if geom.has_z: ndim = 3 i = 1.0 c = f = g = h = zoff = 0.0 matrix = a, b, c, d, e, f, g, h, i, xoff, yoff, zoff elif len(matrix) == 12: ndim = 3 a, b, c, d, e, f, g, h, i, xoff, yoff, zoff = matrix if not geom.has_z: ndim = 2 matrix = a, b, d, e, xoff, yoff else: raise ValueError("'matrix' expects either 6 or 12 coefficients") def affine_pts(pts): """Internal function to yield affine transform of coordinate tuples""" if ndim == 2: for x, y in pts: xp = a * x + b * y + xoff yp = d * x + e * y + yoff yield (xp, yp) elif ndim == 3: for x, y, z in pts: xp = a * x + b * y + c * z + xoff yp = d * x + e * y + f * z + yoff zp = g * x + h * y + i * z + zoff yield (xp, yp, zp) # Process coordinates from each supported geometry type if geom.type in ('Point', 'LineString', 'LinearRing'): return type(geom)(list(affine_pts(geom.coords))) elif geom.type == 'Polygon': ring = geom.exterior shell = type(ring)(list(affine_pts(ring.coords))) holes = list(geom.interiors) for pos, ring in enumerate(holes): holes[pos] = type(ring)(list(affine_pts(ring.coords))) return type(geom)(shell, holes) elif geom.type.startswith('Multi') or geom.type == 'GeometryCollection': # Recursive call # TODO: fix GeometryCollection constructor return type(geom)([affine_transform(part, matrix) for part in geom.geoms]) else: raise ValueError('Type %r not recognized' % geom.type) def interpret_origin(geom, origin, ndim): """Returns interpreted coordinate tuple for origin parameter. This is a helper function for other transform functions. The point of origin can be a keyword 'center' for the 2D bounding box center, 'centroid' for the geometry's 2D centroid, a Point object or a coordinate tuple (x0, y0, z0). """ # get coordinate tuple from 'origin' from keyword or Point type if origin == 'center': # bounding box center minx, miny, maxx, maxy = geom.bounds origin = ((maxx + minx)/2.0, (maxy + miny)/2.0) elif origin == 'centroid': origin = geom.centroid.coords[0] elif isinstance(origin, str): raise ValueError("'origin' keyword %r is not recognized" % origin) elif hasattr(origin, 'type') and origin.type == 'Point': origin = origin.coords[0] # origin should now be tuple-like if len(origin) not in (2, 3): raise ValueError("Expected number of items in 'origin' to be " "either 2 or 3") if ndim == 2: return origin[0:2] else: # 3D coordinate if len(origin) == 2: return origin + (0.0,) else: return origin def rotate(geom, angle, origin='center', use_radians=False): """Returns a rotated geometry on a 2D plane. The angle of rotation can be specified in either degrees (default) or radians by setting ``use_radians=True``. Positive angles are counter-clockwise and negative are clockwise rotations. The point of origin can be a keyword 'center' for the bounding box center (default), 'centroid' for the geometry's centroid, a Point object or a coordinate tuple (x0, y0). The affine transformation matrix for 2D rotation is: / cos(r) -sin(r) xoff \ | sin(r) cos(r) yoff | \ 0 0 1 / where the offsets are calculated from the origin Point(x0, y0): xoff = x0 - x0 * cos(r) + y0 * sin(r) yoff = y0 - x0 * sin(r) - y0 * cos(r) """ if not use_radians: # convert from degrees angle *= pi/180.0 cosp = cos(angle) sinp = sin(angle) if abs(cosp) < 2.5e-16: cosp = 0.0 if abs(sinp) < 2.5e-16: sinp = 0.0 x0, y0 = interpret_origin(geom, origin, 2) matrix = (cosp, -sinp, 0.0, sinp, cosp, 0.0, 0.0, 0.0, 1.0, x0 - x0 * cosp + y0 * sinp, y0 - x0 * sinp - y0 * cosp, 0.0) return affine_transform(geom, matrix) def scale(geom, xfact=1.0, yfact=1.0, zfact=1.0, origin='center'): """Returns a scaled geometry, scaled by factors along each dimension. The point of origin can be a keyword 'center' for the 2D bounding box center (default), 'centroid' for the geometry's 2D centroid, a Point object or a coordinate tuple (x0, y0, z0). Negative scale factors will mirror or reflect coordinates. The general 3D affine transformation matrix for scaling is: / xfact 0 0 xoff \ | 0 yfact 0 yoff | | 0 0 zfact zoff | \ 0 0 0 1 / where the offsets are calculated from the origin Point(x0, y0, z0): xoff = x0 - x0 * xfact yoff = y0 - y0 * yfact zoff = z0 - z0 * zfact """ x0, y0, z0 = interpret_origin(geom, origin, 3) matrix = (xfact, 0.0, 0.0, 0.0, yfact, 0.0, 0.0, 0.0, zfact, x0 - x0 * xfact, y0 - y0 * yfact, z0 - z0 * zfact) return affine_transform(geom, matrix) def skew(geom, xs=0.0, ys=0.0, origin='center', use_radians=False): """Returns a skewed geometry, sheared by angles along x and y dimensions. The shear angle can be specified in either degrees (default) or radians by setting ``use_radians=True``. The point of origin can be a keyword 'center' for the bounding box center (default), 'centroid' for the geometry's centroid, a Point object or a coordinate tuple (x0, y0). The general 2D affine transformation matrix for skewing is: / 1 tan(xs) xoff \ | tan(ys) 1 yoff | \ 0 0 1 / where the offsets are calculated from the origin Point(x0, y0): xoff = -y0 * tan(xs) yoff = -x0 * tan(ys) """ if not use_radians: # convert from degrees xs *= pi/180.0 ys *= pi/180.0 tanx = tan(xs) tany = tan(ys) if abs(tanx) < 2.5e-16: tanx = 0.0 if abs(tany) < 2.5e-16: tany = 0.0 x0, y0 = interpret_origin(geom, origin, 2) matrix = (1.0, tanx, 0.0, tany, 1.0, 0.0, 0.0, 0.0, 1.0, -y0 * tanx, -x0 * tany, 0.0) return affine_transform(geom, matrix) def translate(geom, xoff=0.0, yoff=0.0, zoff=0.0): """Returns a translated geometry shifted by offsets along each dimension. The general 3D affine transformation matrix for translation is: / 1 0 0 xoff \ | 0 1 0 yoff | | 0 0 1 zoff | \ 0 0 0 1 / """ matrix = (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, xoff, yoff, zoff) return affine_transform(geom, matrix)
{ "repo_name": "johanvdw/python-shapely", "path": "shapely/affinity.py", "copies": "6", "size": "8488", "license": "bsd-3-clause", "hash": 5706803894596433000, "line_mean": 32.2862745098, "line_max": 78, "alpha_frac": 0.5444156456, "autogenerated": false, "ratio": 3.370929308975377, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6915344954575378, "avg_score": null, "num_lines": null }
"""Affinity Propagation clustering algorithm.""" # Author: Alexandre Gramfort alexandre.gramfort@inria.fr # Gael Varoquaux gael.varoquaux@normalesup.org # License: BSD 3 clause import numpy as np import warnings from ..exceptions import ConvergenceWarning from ..base import BaseEstimator, ClusterMixin from ..utils import as_float_array, check_array, check_random_state from ..utils.validation import check_is_fitted, _deprecate_positional_args from ..metrics import euclidean_distances from ..metrics import pairwise_distances_argmin def _equal_similarities_and_preferences(S, preference): def all_equal_preferences(): return np.all(preference == preference.flat[0]) def all_equal_similarities(): # Create mask to ignore diagonal of S mask = np.ones(S.shape, dtype=bool) np.fill_diagonal(mask, 0) return np.all(S[mask].flat == S[mask].flat[0]) return all_equal_preferences() and all_equal_similarities() @_deprecate_positional_args def affinity_propagation(S, *, preference=None, convergence_iter=15, max_iter=200, damping=0.5, copy=True, verbose=False, return_n_iter=False, random_state='warn'): """Perform Affinity Propagation Clustering of data Read more in the :ref:`User Guide <affinity_propagation>`. Parameters ---------- S : array-like of shape (n_samples, n_samples) Matrix of similarities between points preference : array-like of shape (n_samples,) or float, default=None Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, i.e. of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities (resulting in a moderate number of clusters). For a smaller amount of clusters, this can be set to the minimum value of the similarities. convergence_iter : int, default=15 Number of iterations with no change in the number of estimated clusters that stops the convergence. max_iter : int, default=200 Maximum number of iterations damping : float, default=0.5 Damping factor between 0.5 and 1. copy : bool, default=True If copy is False, the affinity matrix is modified inplace by the algorithm, for memory efficiency verbose : bool, default=False The verbosity level return_n_iter : bool, default=False Whether or not to return the number of iterations. random_state : int or RandomState instance, default=0 Pseudo-random number generator to control the starting state. Use an int for reproducible results across function calls. See the :term:`Glossary <random_state>`. .. versionadded:: 0.23 this parameter was previously hardcoded as 0. Returns ------- cluster_centers_indices : ndarray of shape (n_clusters,) index of clusters centers labels : ndarray of shape (n_samples,) cluster labels for each point n_iter : int number of iterations run. Returned only if `return_n_iter` is set to True. Notes ----- For an example, see :ref:`examples/cluster/plot_affinity_propagation.py <sphx_glr_auto_examples_cluster_plot_affinity_propagation.py>`. When the algorithm does not converge, it returns an empty array as ``cluster_center_indices`` and ``-1`` as label for each training sample. When all training samples have equal similarities and equal preferences, the assignment of cluster centers and labels depends on the preference. If the preference is smaller than the similarities, a single cluster center and label ``0`` for every sample will be returned. Otherwise, every training sample becomes its own cluster center and is assigned a unique label. References ---------- Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages Between Data Points", Science Feb. 2007 """ S = as_float_array(S, copy=copy) n_samples = S.shape[0] if S.shape[0] != S.shape[1]: raise ValueError("S must be a square array (shape=%s)" % repr(S.shape)) if preference is None: preference = np.median(S) if damping < 0.5 or damping >= 1: raise ValueError('damping must be >= 0.5 and < 1') preference = np.array(preference) if (n_samples == 1 or _equal_similarities_and_preferences(S, preference)): # It makes no sense to run the algorithm in this case, so return 1 or # n_samples clusters, depending on preferences warnings.warn("All samples have mutually equal similarities. " "Returning arbitrary cluster center(s).") if preference.flat[0] >= S.flat[n_samples - 1]: return ((np.arange(n_samples), np.arange(n_samples), 0) if return_n_iter else (np.arange(n_samples), np.arange(n_samples))) else: return ((np.array([0]), np.array([0] * n_samples), 0) if return_n_iter else (np.array([0]), np.array([0] * n_samples))) if random_state == 'warn': warnings.warn(("'random_state' has been introduced in 0.23. " "It will be set to None starting from 0.25 which " "means that results will differ at every function " "call. Set 'random_state' to None to silence this " "warning, or to 0 to keep the behavior of versions " "<0.23."), FutureWarning) random_state = 0 random_state = check_random_state(random_state) # Place preference on the diagonal of S S.flat[::(n_samples + 1)] = preference A = np.zeros((n_samples, n_samples)) R = np.zeros((n_samples, n_samples)) # Initialize messages # Intermediate results tmp = np.zeros((n_samples, n_samples)) # Remove degeneracies S += ((np.finfo(np.double).eps * S + np.finfo(np.double).tiny * 100) * random_state.randn(n_samples, n_samples)) # Execute parallel affinity propagation updates e = np.zeros((n_samples, convergence_iter)) ind = np.arange(n_samples) for it in range(max_iter): # tmp = A + S; compute responsibilities np.add(A, S, tmp) I = np.argmax(tmp, axis=1) Y = tmp[ind, I] # np.max(A + S, axis=1) tmp[ind, I] = -np.inf Y2 = np.max(tmp, axis=1) # tmp = Rnew np.subtract(S, Y[:, None], tmp) tmp[ind, I] = S[ind, I] - Y2 # Damping tmp *= 1 - damping R *= damping R += tmp # tmp = Rp; compute availabilities np.maximum(R, 0, tmp) tmp.flat[::n_samples + 1] = R.flat[::n_samples + 1] # tmp = -Anew tmp -= np.sum(tmp, axis=0) dA = np.diag(tmp).copy() tmp.clip(0, np.inf, tmp) tmp.flat[::n_samples + 1] = dA # Damping tmp *= 1 - damping A *= damping A -= tmp # Check for convergence E = (np.diag(A) + np.diag(R)) > 0 e[:, it % convergence_iter] = E K = np.sum(E, axis=0) if it >= convergence_iter: se = np.sum(e, axis=1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != n_samples) if (not unconverged and (K > 0)) or (it == max_iter): never_converged = False if verbose: print("Converged after %d iterations." % it) break else: never_converged = True if verbose: print("Did not converge") I = np.flatnonzero(E) K = I.size # Identify exemplars if K > 0 and not never_converged: c = np.argmax(S[:, I], axis=1) c[I] = np.arange(K) # Identify clusters # Refine the final set of exemplars and clusters and return results for k in range(K): ii = np.where(c == k)[0] j = np.argmax(np.sum(S[ii[:, np.newaxis], ii], axis=0)) I[k] = ii[j] c = np.argmax(S[:, I], axis=1) c[I] = np.arange(K) labels = I[c] # Reduce labels to a sorted, gapless, list cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) else: warnings.warn("Affinity propagation did not converge, this model " "will not have any cluster centers.", ConvergenceWarning) labels = np.array([-1] * n_samples) cluster_centers_indices = [] if return_n_iter: return cluster_centers_indices, labels, it + 1 else: return cluster_centers_indices, labels ############################################################################### class AffinityPropagation(ClusterMixin, BaseEstimator): """Perform Affinity Propagation Clustering of data. Read more in the :ref:`User Guide <affinity_propagation>`. Parameters ---------- damping : float, default=0.5 Damping factor (between 0.5 and 1) is the extent to which the current value is maintained relative to incoming values (weighted 1 - damping). This in order to avoid numerical oscillations when updating these values (messages). max_iter : int, default=200 Maximum number of iterations. convergence_iter : int, default=15 Number of iterations with no change in the number of estimated clusters that stops the convergence. copy : bool, default=True Make a copy of input data. preference : array-like of shape (n_samples,) or float, default=None Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, ie of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities. affinity : {'euclidean', 'precomputed'}, default='euclidean' Which affinity to use. At the moment 'precomputed' and ``euclidean`` are supported. 'euclidean' uses the negative squared euclidean distance between points. verbose : bool, default=False Whether to be verbose. random_state : int or RandomState instance, default=0 Pseudo-random number generator to control the starting state. Use an int for reproducible results across function calls. See the :term:`Glossary <random_state>`. .. versionadded:: 0.23 this parameter was previously hardcoded as 0. Attributes ---------- cluster_centers_indices_ : ndarray of shape (n_clusters,) Indices of cluster centers cluster_centers_ : ndarray of shape (n_clusters, n_features) Cluster centers (if affinity != ``precomputed``). labels_ : ndarray of shape (n_samples,) Labels of each point affinity_matrix_ : ndarray of shape (n_samples, n_samples) Stores the affinity matrix used in ``fit``. n_iter_ : int Number of iterations taken to converge. Notes ----- For an example, see :ref:`examples/cluster/plot_affinity_propagation.py <sphx_glr_auto_examples_cluster_plot_affinity_propagation.py>`. The algorithmic complexity of affinity propagation is quadratic in the number of points. When ``fit`` does not converge, ``cluster_centers_`` becomes an empty array and all training samples will be labelled as ``-1``. In addition, ``predict`` will then label every sample as ``-1``. When all training samples have equal similarities and equal preferences, the assignment of cluster centers and labels depends on the preference. If the preference is smaller than the similarities, ``fit`` will result in a single cluster center and label ``0`` for every sample. Otherwise, every training sample becomes its own cluster center and is assigned a unique label. References ---------- Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages Between Data Points", Science Feb. 2007 Examples -------- >>> from sklearn.cluster import AffinityPropagation >>> import numpy as np >>> X = np.array([[1, 2], [1, 4], [1, 0], ... [4, 2], [4, 4], [4, 0]]) >>> clustering = AffinityPropagation(random_state=5).fit(X) >>> clustering AffinityPropagation(random_state=5) >>> clustering.labels_ array([0, 0, 0, 1, 1, 1]) >>> clustering.predict([[0, 0], [4, 4]]) array([0, 1]) >>> clustering.cluster_centers_ array([[1, 2], [4, 2]]) """ @_deprecate_positional_args def __init__(self, *, damping=.5, max_iter=200, convergence_iter=15, copy=True, preference=None, affinity='euclidean', verbose=False, random_state='warn'): self.damping = damping self.max_iter = max_iter self.convergence_iter = convergence_iter self.copy = copy self.verbose = verbose self.preference = preference self.affinity = affinity self.random_state = random_state @property def _pairwise(self): return self.affinity == "precomputed" def fit(self, X, y=None): """Fit the clustering from features, or affinity matrix. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ array-like of shape (n_samples, n_samples) Training instances to cluster, or similarities / affinities between instances if ``affinity='precomputed'``. If a sparse feature matrix is provided, it will be converted into a sparse ``csr_matrix``. y : Ignored Not used, present here for API consistency by convention. Returns ------- self """ if self.affinity == "precomputed": accept_sparse = False else: accept_sparse = 'csr' X = self._validate_data(X, accept_sparse=accept_sparse) if self.affinity == "precomputed": self.affinity_matrix_ = X elif self.affinity == "euclidean": self.affinity_matrix_ = -euclidean_distances(X, squared=True) else: raise ValueError("Affinity must be 'precomputed' or " "'euclidean'. Got %s instead" % str(self.affinity)) self.cluster_centers_indices_, self.labels_, self.n_iter_ = \ affinity_propagation( self.affinity_matrix_, preference=self.preference, max_iter=self.max_iter, convergence_iter=self.convergence_iter, damping=self.damping, copy=self.copy, verbose=self.verbose, return_n_iter=True, random_state=self.random_state) if self.affinity != "precomputed": self.cluster_centers_ = X[self.cluster_centers_indices_].copy() return self def predict(self, X): """Predict the closest cluster each sample in X belongs to. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) New data to predict. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- labels : ndarray of shape (n_samples,) Cluster labels. """ check_is_fitted(self) X = check_array(X) if not hasattr(self, "cluster_centers_"): raise ValueError("Predict method is not supported when " "affinity='precomputed'.") if self.cluster_centers_.shape[0] > 0: return pairwise_distances_argmin(X, self.cluster_centers_) else: warnings.warn("This model does not have any cluster centers " "because affinity propagation did not converge. " "Labeling every sample as '-1'.", ConvergenceWarning) return np.array([-1] * X.shape[0]) def fit_predict(self, X, y=None): """Fit the clustering from features or affinity matrix, and return cluster labels. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ array-like of shape (n_samples, n_samples) Training instances to cluster, or similarities / affinities between instances if ``affinity='precomputed'``. If a sparse feature matrix is provided, it will be converted into a sparse ``csr_matrix``. y : Ignored Not used, present here for API consistency by convention. Returns ------- labels : ndarray of shape (n_samples,) Cluster labels. """ return super().fit_predict(X, y)
{ "repo_name": "bnaul/scikit-learn", "path": "sklearn/cluster/_affinity_propagation.py", "copies": "2", "size": "17232", "license": "bsd-3-clause", "hash": 8205221239703559000, "line_mean": 35.3544303797, "line_max": 79, "alpha_frac": 0.6034702878, "autogenerated": false, "ratio": 4.161313692344844, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00014141976167292622, "num_lines": 474 }
"""Affinity Propagation clustering algorithm. This module is an extension of sklearn's Affinity Propagation to take into account sparse matrices, which are not currently supported. Author: Federico Tomasi Copyright (c) 2016, Federico Tomasi. Licensed under the FreeBSD license (see LICENSE.txt). Original authors for sklearn: # Author: Alexandre Gramfort alexandre.gramfort@inria.fr # Gael Varoquaux gael.varoquaux@normalesup.org # License: BSD 3 clause """ import numpy as np from scipy.sparse import coo_matrix from scipy.sparse import issparse from sklearn.cluster import AffinityPropagation from sklearn.utils import as_float_array, check_array from sklearn.metrics import euclidean_distances from ._sparse_affinity_propagation import ( parse_preference, _set_sparse_diagonal, _sparse_row_maxindex, _sparse_row_sum_update, _update_r_max_row, remove_single_samples) def sparse_ap(S, preference=None, convergence_iter=15, max_iter=200, damping=0.5, copy=True, verbose=False, return_n_iter=False, convergence_percentage=0.999999): """Perform Affinity Propagation Clustering of data. Same as affinity_propagation(), but assume S be a sparse matrix. Parameters ---------- S : array-like, shape (n_samples, n_samples) Matrix of similarities between points preference : array-like, shape (n_samples,) or float, optional Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, i.e. of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities (resulting in a moderate number of clusters). For a smaller amount of clusters, this can be set to the minimum value of the similarities. convergence_iter : int, optional, default: 15 Number of iterations with no change in the number of estimated clusters that stops the convergence. max_iter : int, optional, default: 200 Maximum number of iterations damping : float, optional, default: 0.5 Damping factor between 0.5 and 1. copy : boolean, optional, default: True If copy is False, the affinity matrix is modified inplace by the algorithm, for memory efficiency. Unused, but left for sklearn affinity propagation consistency. verbose : boolean, optional, default: False The verbosity level return_n_iter : bool, default False Whether or not to return the number of iterations. Returns ------- cluster_centers_indices : array, shape (n_clusters,) index of clusters centers labels : array, shape (n_samples,) cluster labels for each point n_iter : int number of iterations run. Returned only if `return_n_iter` is set to True. Notes ----- See examples/cluster/plot_affinity_propagation.py for an example. References ---------- Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages Between Data Points", Science Feb. 2007 """ # rows, cols, data = matrix_to_row_col_data(S) rows, cols, data = S.row, S.col, as_float_array(S.data, copy=copy) n_samples = S.shape[0] preferences = parse_preference(preference, n_samples, data) if damping < 0.5 or damping >= 1: raise ValueError('damping must be >= 0.5 and < 1') if convergence_percentage is None: convergence_percentage = 1 random_state = np.random.RandomState(0) # Place preference on the diagonal of S rows, cols, data = _set_sparse_diagonal(rows, cols, data, preferences) rows, cols, data, left_ori_dict, idx_single_samples, n_samples = \ remove_single_samples(rows, cols, data, n_samples) data_len = data.shape[0] row_indptr = np.append( np.insert(np.where(np.diff(rows) > 0)[0] + 1, 0, 0), data_len) row_to_col_idx = np.lexsort((rows, cols)) rows_colbased = rows[row_to_col_idx] cols_colbased = cols[row_to_col_idx] col_to_row_idx = np.lexsort((cols_colbased, rows_colbased)) col_indptr = np.append( np.insert(np.where(np.diff(cols_colbased) > 0)[0] + 1, 0, 0), data_len) kk_row_index = np.where(rows == cols)[0] kk_col_index = np.where(rows_colbased == cols_colbased)[0] # Initialize messages A = np.zeros(data_len, dtype=float) R = np.zeros(data_len, dtype=float) # Intermediate results tmp = np.zeros(data_len, dtype=float) # Remove degeneracies data += ((np.finfo(np.double).eps * data + np.finfo(np.double).tiny * 100) * random_state.randn(data_len)) labels = np.empty(0, dtype=np.int) last_labels = None convergence_count = 0 for it in range(max_iter): last_labels = labels.copy() # tmp = A + S; compute responsibilities np.add(A, data, tmp) np.subtract(data, _update_r_max_row(tmp, row_indptr), tmp) # Damping tmp *= 1. - damping R *= damping R += tmp # tmp = Rp; compute availabilities np.maximum(R, 0, tmp) tmp[kk_row_index] = R[kk_row_index] # tmp = -Anew tmp = tmp[row_to_col_idx] _sparse_row_sum_update(tmp, col_indptr, kk_col_index) tmp = tmp[col_to_row_idx] # Damping tmp *= 1. - damping A *= damping A -= tmp # Check for convergence labels = _sparse_row_maxindex(A + R, row_indptr) if labels.shape[0] == 0 or np.sum(last_labels == labels) / \ float(labels.shape[0]) < convergence_percentage: convergence_count = 0 else: convergence_count += 1 if convergence_count == convergence_iter: if verbose: print("Converged after %d iterations." % it) break else: if verbose: print("Did not converge") if idx_single_samples is None or len(idx_single_samples) == 0: cluster_centers_indices = cols[labels] else: cluster_centers_indices = [left_ori_dict[el] for el in cols[labels]] for ind in sorted(idx_single_samples): cluster_centers_indices.insert(ind, ind) cluster_centers_indices = np.asarray(cluster_centers_indices) _centers = np.unique(cluster_centers_indices) lookup = {v: i for i, v in enumerate(_centers)} labels = np.array([lookup[x] for x in cluster_centers_indices], dtype=int) if return_n_iter: return cluster_centers_indices, labels, it + 1 else: return cluster_centers_indices, labels ############################################################################### class AffinityPropagation(AffinityPropagation): """Perform Affinity Propagation Clustering of data. Read more in the :ref:`User Guide <affinity_propagation>`. Parameters ---------- damping : float, optional, default: 0.5 Damping factor between 0.5 and 1. convergence_iter : int, optional, default: 15 Number of iterations with no change in the number of estimated clusters that stops the convergence. max_iter : int, optional, default: 200 Maximum number of iterations. copy : boolean, optional, default: True Make a copy of input data. preference : array-like, shape (n_samples,) or float, optional Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, ie of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities. affinity : string, optional, default=``euclidean`` Which affinity to use. At the moment ``precomputed`` and ``euclidean`` are supported. ``euclidean`` uses the negative squared euclidean distance between points. verbose : boolean, optional, default: False Whether to be verbose. Attributes ---------- cluster_centers_indices_ : array, shape (n_clusters,) Indices of cluster centers cluster_centers_ : array, shape (n_clusters, n_features) Cluster centers (if affinity != ``precomputed``). labels_ : array, shape (n_samples,) Labels of each point affinity_matrix_ : array, shape (n_samples, n_samples) Stores the affinity matrix used in ``fit``. n_iter_ : int Number of iterations taken to converge. Notes ----- See examples/cluster/plot_affinity_propagation.py for an example. The algorithmic complexity of affinity propagation is quadratic in the number of points. References ---------- Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages Between Data Points", Science Feb. 2007 """ def __init__(self, damping=.5, max_iter=200, convergence_iter=15, copy=True, preference=None, affinity='euclidean', verbose=False, convergence_percentage=0.999999): super(AffinityPropagation, self).__init__( damping=damping, max_iter=max_iter, convergence_iter=convergence_iter, copy=copy, verbose=verbose, preference=preference, affinity=affinity) self.convergence_percentage = convergence_percentage def fit(self, X, **kwargs): """Apply affinity propagation clustering. Create affinity matrix from negative euclidean distances if required. Parameters ---------- X: array-like or sparse matrix, shape (n_samples, n_features) or (n_samples, n_samples) Data matrix or, if affinity is ``precomputed``, matrix of similarities / affinities. """ if not issparse(X): return super(AffinityPropagation, self).fit(X, **kwargs) # Since X is sparse, this converts it in a coo_matrix if required X = check_array(X, accept_sparse='coo') if self.affinity == "precomputed": self.affinity_matrix_ = X elif self.affinity == "euclidean": self.affinity_matrix_ = coo_matrix( -euclidean_distances(X, squared=True)) else: raise ValueError("Affinity must be 'precomputed' or " "'euclidean'. Got %s instead" % str(self.affinity)) self.cluster_centers_indices_, self.labels_, self.n_iter_ = \ sparse_ap( self.affinity_matrix_, self.preference, max_iter=self.max_iter, convergence_iter=self.convergence_iter, damping=self.damping, copy=self.copy, verbose=self.verbose, return_n_iter=True, convergence_percentage=self.convergence_percentage) if self.affinity != "precomputed": self.cluster_centers_ = X.data[self.cluster_centers_indices_].copy() return self
{ "repo_name": "slipguru/ignet", "path": "icing/externals/sparse_affinity_propagation.py", "copies": "2", "size": "11131", "license": "bsd-2-clause", "hash": 4927493427139840000, "line_mean": 33.784375, "line_max": 80, "alpha_frac": 0.6321983649, "autogenerated": false, "ratio": 3.9953338119167263, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5627532176816726, "avg_score": null, "num_lines": null }
# affirm.py / Eli Finer / 2016 # # This script causes assert statements to output much better default error messages # that include the tested condition and the values for any variables referenced in it. # # Here are some examples: # # >>> assert 1 > 2 # AssertionError: assertion (1 > 2) failed # # >>> a = 1; b = 2; c = 'foo'; d = None # >>> assert a > b # AssertionError: assertion (a > b) failed with a=1, b=2 # # >>> assert c is None # AssertionError: assertion (c is None) failed with c='foo' # # >>> assert a == b == c # AssertionError: assertion (a == b == c) failed with a=1, b=2, c='foo' import re import ast import types import inspect from collections import OrderedDict def make_assert_message(frame, regex): def extract_condition(): code_context = inspect.getframeinfo(frame)[3] if not code_context: return '' match = re.search(regex, code_context[0]) if not match: return '' return match.group(1).strip() class ReferenceFinder(ast.NodeVisitor): def __init__(self): self.names = [] def find(self, tree, frame): self.visit(tree) nothing = object() deref = OrderedDict() for name in self.names: value = frame.f_locals.get(name, nothing) or frame.f_globals.get(name, nothing) if value is not nothing and not isinstance(value, (types.ModuleType, types.FunctionType)): deref[name] = repr(value) return deref def visit_Name(self, node): self.names.append(node.id) condition = extract_condition() if not condition: return deref = ReferenceFinder().find(ast.parse(condition), frame) deref_str = '' if deref: deref_str = ' with ' + ', '.join('{}={}'.format(k, v) for k, v in deref.items()) return 'assertion {} failed{}'.format(condition, deref_str) import sys _old_excepthook = sys.excepthook def assert_excepthook(type, value, traceback): if type == AssertionError: from traceback import print_exception if not value.args: top = traceback while top.tb_next and top.tb_next.tb_frame: top = top.tb_next message = make_assert_message(top.tb_frame, r'assert\s+([^#]+)') value = AssertionError(message) print_exception(type, value, traceback) else: _old_excepthook(type, value, traceback) sys.excepthook = assert_excepthook def affirm(condition): if not __debug__: return if condition: return else: message = make_assert_message(inspect.currentframe().f_back, r'affirm\s*\(\s*(.+)\s*\)') raise AssertionError(message)
{ "repo_name": "gooli/affirm", "path": "affirm.py", "copies": "1", "size": "2746", "license": "mit", "hash": 8639708602584335000, "line_mean": 31.6904761905, "line_max": 106, "alpha_frac": 0.6052439913, "autogenerated": false, "ratio": 3.7360544217687073, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9816280734098832, "avg_score": 0.005003535793974968, "num_lines": 84 }
a = "fiebre" b = "muerto" c = "normal" d = "enfermo" x = True temp = float while x: while x: try: archivo = open('temperatura.txt', 'a+') temp = float(input("ingrese una temperatura ")) x = False except Exception: print("intenta de nuevo") else: archivo = open('temperatura.txt', 'a+') if temp > 37.5: print("tienes fiebre " ) archivo.write(str(temp) + " " + a + "\n") archivo.close() elif temp < 5: print("jajajajaja estas muerto " ) archivo.write(str(temp) + " " + b + "\n") elif temp >=5 and temp <=35 : print("estas enfermo " ) archivo.write(str(temp) + " " + d + "\n") else: print("estas bien " ) archivo.write(str(temp) + " " + c + "\n") archivo.close() else: s = input("desea continuar s / n") if s == 's': x = True else : print("good by..") x = False
{ "repo_name": "erick84/uip-iiiq2016-prog3", "path": "laboratorio5/Main.py", "copies": "1", "size": "1144", "license": "mit", "hash": 5465192341371452000, "line_mean": 24.6046511628, "line_max": 59, "alpha_frac": 0.4082167832, "autogenerated": false, "ratio": 3.4149253731343285, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9289740030246967, "avg_score": 0.0066804252174722705, "num_lines": 43 }
"""A file-backed declarative layer on optparse. This module allows the user to register command line options, and to load them in bulk from a configuration file. >>> class Config(Configuration): ... debug = BoolOption('Enable debugging.', default=False) ... debug_level = IntOption('Debug level 0 <= n <= 9.', default=0) ... db = URIOption('Database URI.') >>> config = Config(args=['--debug=true', '--db=mysql://localhost/db']) >>> config {'debug': True, 'debug_level': 0, 'db': URI(u'mysql://localhost/db')} >>> config.debug True >>> config.db URI(u'mysql://localhost/db') """ from __future__ import with_statement import optparse import sys from flam.util import to_boolean, to_list, URI __all__ = ['Configuration', 'Option', 'IntOption', 'FloatOption', 'ListOption', 'BoolOption'] class Option(object): """A configuration option.""" def __init__(self, help, default=None, *args, **kwargs): self.args = args kwargs['help'] = help kwargs['default'] = default self.init_kwargs(kwargs) self.kwargs = kwargs def init_kwargs(self, kwargs): """Hook for initialising keyword arguments to optparse.Option().""" kwargs.setdefault('action', 'store') def to_optparse_option(self, name): flag = '--' + name option = optparse.Option(flag, *self.args, **self.kwargs) return option class ConvertingOption(Option): """A virtual base Option that performs type conversion.""" def convert(self, value): """Override this to convert an option.""" raise NotImplementedError def init_kwargs(self, kwargs): def convert(option, opt_str, value, parser): setattr(parser.values, opt_str[2:], self.convert(value)) kwargs.update(dict( type='string', action='callback', callback=convert, )) class IntOption(Option): """An integer option. >>> class Config(Configuration): ... age = IntOption('Age.') >>> config = Config(args=['--age=34']) >>> config.age 34 """ def init_kwargs(self, kwargs): kwargs['type'] = 'int' class FloatOption(Option): """A floating point option.""" def init_kwargs(self, kwargs): kwargs['type'] = 'float' class BoolOption(ConvertingOption): """A boolean option. >>> class Config(Configuration): ... alive = BoolOption('Alive?') >>> config = Config(args=['--alive=true']) >>> config.alive True """ def convert(self, value): return to_boolean(value) class URIOption(ConvertingOption): """A URI option. The value will be a flam.util.URI object. >>> class Config(Configuration): ... db = URIOption('Database connection.') >>> config = Config(args=['--db=mysql://localhost:5001/db']) >>> config.db URI(u'mysql://localhost:5001/db') """ def convert(self, value): return URI(value) class ListOption(ConvertingOption): """An option with a list of values. >>> class Config(Configuration): ... names = ListOption('Names.') >>> config = Config(args=['--names=bob,alice']) >>> config.names ['bob', 'alice'] """ def __init__(self, *args, **kwargs): self.sep = kwargs.pop('sep', ',') self.keep_empty = kwargs.pop('keep_empty', False) super(ListOption, self).__init__(*args, **kwargs) def convert(self, value): return to_list(value, sep=self.sep, keep_empty=self.keep_empty) class Configuration(object): """Configuration container object. Configuration options are declared as class attributes. Options can be defined in a configuration file or via command line flags. """ def __init__(self, file=None, args=None, **kwargs): """Create a new Configuration object. :param file: File-like object or filename to load configuration from. :param args: Command-line arguments, excluding argv[0]. sys.argv will be used if omitted. :param kwargs: Extra keyword arguments to pass to the OptionParser constructor. """ options = self._collect_options() self._parser = optparse.OptionParser(option_list=options, **kwargs) self._parser.add_option( '--config', help='Configuration file to load.', default=filename, action='store', ) defaults = dict((option.dest, option.default) for option in options) self._values = optparse.Values(defaults) if filename is not None: self.read(filename) # TODO(alec) We should preserve args somewhere... _, args = self._parser.parse_args(args or sys.argv[1:], values=self._values) def read(self, file): """Read option configuration from a file-like object or a filename. >>> class Config(Configuration): ... age = IntOption('Age.') >>> from StringIO import StringIO >>> conf_file = StringIO('age=10') >>> config = Config(conf_file) >>> config.age 10 """ file_args = self._read_args(file) self._parser.parse_args(file_args, values=self._values) def __repr__(self): return repr(self._values.__dict__) def _collect_options(self): options = [] for name, value in self.__class__.__dict__.items(): if isinstance(value, Option): value = value.to_optparse_option(name) elif isinstance(value, optparse.Option): pass else: continue options.append(value) return options def _read_args(self, file): args = [] if isinstance(file, basestring): file = open(file) try: for line in file: line = line.strip() if not line or line.startswith('#'): continue key, value = line.split('=', 1) args.append('--' + key.strip()) args.append(value.strip()) return args finally: file.close() if __name__ == '__main__': import doctest doctest.testmod()
{ "repo_name": "tectronics/flimflam", "path": "random/config.py", "copies": "3", "size": "6244", "license": "bsd-3-clause", "hash": -788368774768525200, "line_mean": 28.0418604651, "line_max": 84, "alpha_frac": 0.5807174888, "autogenerated": false, "ratio": 4.151595744680851, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00005471956224350205, "num_lines": 215 }
"""A file containing all of our interfaces. Currently contains only Stats interface """ from redis import Redis from redis.exceptions import ConnectionError import time __all__ = ['Stats'] class Stats(object): """Stats interface""" r = Redis() # XXX: Trying out the connection. A better way must be implemented to handle # the redis server try: r.ping() except ConnectionError: print("Warning: Could not connect to redis server! Run setup() to configure") # Default channel: _c = 'statistics' # XXX: This class reuses assert isinstance checks - there should be a better # way to error handling! @classmethod def register(self, addr, timestamp=None): """Publishes a message to register the issuer""" if not timestamp: timestamp = time.time() else: assert isinstance(timestamp, float), 'parameter :time must be float' self._publish(addr, 'register', timestamp) @classmethod def set_count(self, addr, op, value=1): """Publishes a message containg issuers' address, increase operation and value. :addr -> string1 :op -> string, either 'recv', 'success' or 'error' :value -> int,string, either int, '+' or '-' """ ops = ['recv', 'success', 'error'] if op not in ops: raise ValueError('Invalid value for parameter :op') if value == "+": value = 1 elif value == "-": value = -1 assert isinstance(value, int), 'parameter :value must be integer' self._publish(addr, op, value) @classmethod def set_time(self, addr, op, timestamp=None): """Publishes a message containg issuers' address, time operation and timestamp. :addr -> string1 :op -> string, either 't_open' or 't_close' :time -> float, should be time.time() """ ops = ['t_open','t_close'] if op not in ops: raise ValueError('Invalid value for parameter :op') if not timestamp: timestamp = time.time() else: assert isinstance(timestamp, float), 'parameter :time must be float' self._publish(addr, op, timestamp) @classmethod def _publish(self, addr, op, value): """Helper method to prepare and publish the message""" msg = "{} {} {}".format(str(addr), op, value) try: self.r.publish(self._c, msg) except ConnectionError as err: print("Connection Error: Could not publish message") @classmethod def set_channel(self, channel): """Sets the class channel for statistics""" assert isinstance(channel, str), ':channel should be a string' channel.strip() if len(channel.split()) > 1: raise ValueError('Invalid value for :channel') self._c = channel @classmethod def get_channel(self): """Used to retreive current class channel""" return self._c
{ "repo_name": "thunderstruck47/exercise02", "path": "interface.py", "copies": "1", "size": "2871", "license": "mit", "hash": -1212293584882003500, "line_mean": 34.8875, "line_max": 87, "alpha_frac": 0.6269592476, "autogenerated": false, "ratio": 4.179039301310044, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5305998548910044, "avg_score": null, "num_lines": null }
""" A file designed to have lines of similarity when compared to similar_lines_b We use lorm-ipsum to generate 'random' code. """ # Copyright (c) 2020 Frank Harrison <frank@doublethefish.com> def adipiscing(elit): etiam = "id" dictum = "purus," vitae = "pretium" neque = "Vivamus" nec = "ornare" tortor = "sit" return etiam, dictum, vitae, neque, nec, tortor class Amet: def similar_function_3_lines(self, tellus): # line same #1 agittis = 10 # line same #2 tellus *= 300 # line same #3 return agittis, tellus # line diff def lorem(self, ipsum): dolor = "sit" amet = "consectetur" return (lorem, dolor, amet) def similar_function_5_lines(self, similar): # line same #1 some_var = 10 # line same #2 someother_var *= 300 # line same #3 fusce = "sit" # line same #4 amet = "tortor" # line same #5 return some_var, someother_var, fusce, amet # line diff def __init__(self, moleskie, lectus="Mauris", ac="pellentesque"): metus = "ut" lobortis = "urna." Integer = "nisl" (mauris,) = "interdum" non = "odio" semper = "aliquam" malesuada = "nunc." iaculis = "dolor" facilisis = "ultrices" vitae = "ut." return ( metus, lobortis, Integer, mauris, non, semper, malesuada, iaculis, facilisis, vitae, ) def similar_function_3_lines(self, tellus): # line same #1 agittis = 10 # line same #2 tellus *= 300 # line same #3 return agittis, tellus # line diff
{ "repo_name": "ruchee/vimrc", "path": "vimfiles/bundle/vim-python/submodules/pylint/tests/input/similar_lines_a.py", "copies": "2", "size": "1742", "license": "mit", "hash": -7298065376492918000, "line_mean": 26.6507936508, "line_max": 80, "alpha_frac": 0.5350172216, "autogenerated": false, "ratio": 3.1107142857142858, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4645731507314285, "avg_score": null, "num_lines": null }
# A file downloader. import contextlib, os, tempfile, timer, urllib2, urlparse class Downloader: def __init__(self, dir=None): self.dir = dir # Downloads a file and removes it when exiting a block. # Usage: # d = Downloader() # with d.download(url) as f: # use_file(f) def download(self, url, cookie=None): suffix = os.path.splitext(urlparse.urlsplit(url)[2])[1] fd, filename = tempfile.mkstemp(suffix=suffix, dir=self.dir) os.close(fd) with timer.print_time('Downloading', url, 'to', filename): opener = urllib2.build_opener() if cookie: opener.addheaders.append(('Cookie', cookie)) num_tries = 2 for i in range(num_tries): try: f = opener.open(url) except urllib2.URLError, e: print('Failed to open url', url) continue length = f.headers.get('content-length') if not length: print('Failed to get content-length') continue length = int(length) with open(filename, 'wb') as out: count = 0 while count < length: data = f.read(1024 * 1024) count += len(data) out.write(data) @contextlib.contextmanager def remove(filename): try: yield filename finally: os.remove(filename) return remove(filename)
{ "repo_name": "thelink2012/gta3sc", "path": "deps/cppformat/cppformat/support/download.py", "copies": "9", "size": "1363", "license": "mit", "hash": -677804499743698000, "line_mean": 28.6304347826, "line_max": 64, "alpha_frac": 0.5869405723, "autogenerated": false, "ratio": 3.796657381615599, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.021405871097071812, "num_lines": 46 }
"""A file interface for handling local and remote data files. The goal of datasource is to abstract some of the file system operations when dealing with data files so the researcher doesn't have to know all the low-level details. Through datasource, a researcher can obtain and use a file with one function call, regardless of location of the file. DataSource is meant to augment standard python libraries, not replace them. It should work seamlessly with standard file IO operations and the os module. DataSource files can originate locally or remotely: - local files : '/home/guido/src/local/data.txt' - URLs (http, ftp, ...) : 'http://www.scipy.org/not/real/data.txt' DataSource files can also be compressed or uncompressed. Currently only gzip, bz2 and xz are supported. Example:: >>> # Create a DataSource, use os.curdir (default) for local storage. >>> ds = datasource.DataSource() >>> >>> # Open a remote file. >>> # DataSource downloads the file, stores it locally in: >>> # './www.google.com/index.html' >>> # opens the file and returns a file object. >>> fp = ds.open('http://www.google.com/index.html') >>> >>> # Use the file as you normally would >>> fp.read() >>> fp.close() """ from __future__ import division, absolute_import, print_function import os import sys import warnings import shutil import io from numpy.core.overrides import set_module _open = open def _check_mode(mode, encoding, newline): """Check mode and that encoding and newline are compatible. Parameters ---------- mode : str File open mode. encoding : str File encoding. newline : str Newline for text files. """ if "t" in mode: if "b" in mode: raise ValueError("Invalid mode: %r" % (mode,)) else: if encoding is not None: raise ValueError("Argument 'encoding' not supported in binary mode") if newline is not None: raise ValueError("Argument 'newline' not supported in binary mode") def _python2_bz2open(fn, mode, encoding, newline): """Wrapper to open bz2 in text mode. Parameters ---------- fn : str File name mode : {'r', 'w'} File mode. Note that bz2 Text files are not supported. encoding : str Ignored, text bz2 files not supported in Python2. newline : str Ignored, text bz2 files not supported in Python2. """ import bz2 _check_mode(mode, encoding, newline) if "t" in mode: # BZ2File is missing necessary functions for TextIOWrapper warnings.warn("Assuming latin1 encoding for bz2 text file in Python2", RuntimeWarning, stacklevel=5) mode = mode.replace("t", "") return bz2.BZ2File(fn, mode) def _python2_gzipopen(fn, mode, encoding, newline): """ Wrapper to open gzip in text mode. Parameters ---------- fn : str, bytes, file File path or opened file. mode : str File mode. The actual files are opened as binary, but will decoded using the specified `encoding` and `newline`. encoding : str Encoding to be used when reading/writing as text. newline : str Newline to be used when reading/writing as text. """ import gzip # gzip is lacking read1 needed for TextIOWrapper class GzipWrap(gzip.GzipFile): def read1(self, n): return self.read(n) _check_mode(mode, encoding, newline) gz_mode = mode.replace("t", "") if isinstance(fn, (str, bytes)): binary_file = GzipWrap(fn, gz_mode) elif hasattr(fn, "read") or hasattr(fn, "write"): binary_file = GzipWrap(None, gz_mode, fileobj=fn) else: raise TypeError("filename must be a str or bytes object, or a file") if "t" in mode: return io.TextIOWrapper(binary_file, encoding, newline=newline) else: return binary_file # Using a class instead of a module-level dictionary # to reduce the initial 'import numpy' overhead by # deferring the import of lzma, bz2 and gzip until needed # TODO: .zip support, .tar support? class _FileOpeners(object): """ Container for different methods to open (un-)compressed files. `_FileOpeners` contains a dictionary that holds one method for each supported file format. Attribute lookup is implemented in such a way that an instance of `_FileOpeners` itself can be indexed with the keys of that dictionary. Currently uncompressed files as well as files compressed with ``gzip``, ``bz2`` or ``xz`` compression are supported. Notes ----- `_file_openers`, an instance of `_FileOpeners`, is made available for use in the `_datasource` module. Examples -------- >>> np.lib._datasource._file_openers.keys() [None, '.bz2', '.gz', '.xz', '.lzma'] >>> np.lib._datasource._file_openers['.gz'] is gzip.open True """ def __init__(self): self._loaded = False self._file_openers = {None: io.open} def _load(self): if self._loaded: return try: import bz2 if sys.version_info[0] >= 3: self._file_openers[".bz2"] = bz2.open else: self._file_openers[".bz2"] = _python2_bz2open except ImportError: pass try: import gzip if sys.version_info[0] >= 3: self._file_openers[".gz"] = gzip.open else: self._file_openers[".gz"] = _python2_gzipopen except ImportError: pass try: import lzma self._file_openers[".xz"] = lzma.open self._file_openers[".lzma"] = lzma.open except (ImportError, AttributeError): # There are incompatible backports of lzma that do not have the # lzma.open attribute, so catch that as well as ImportError. pass self._loaded = True def keys(self): """ Return the keys of currently supported file openers. Parameters ---------- None Returns ------- keys : list The keys are None for uncompressed files and the file extension strings (i.e. ``'.gz'``, ``'.xz'``) for supported compression methods. """ self._load() return list(self._file_openers.keys()) def __getitem__(self, key): self._load() return self._file_openers[key] _file_openers = _FileOpeners() def open(path, mode='r', destpath=os.curdir, encoding=None, newline=None): """ Open `path` with `mode` and return the file object. If ``path`` is an URL, it will be downloaded, stored in the `DataSource` `destpath` directory and opened from there. Parameters ---------- path : str Local file path or URL to open. mode : str, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by path. Default is 'r'. destpath : str, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `io.open` uses. newline : {None, str}, optional Newline to use when reading text file. Returns ------- out : file object The opened file. Notes ----- This is a convenience function that instantiates a `DataSource` and returns the file object from ``DataSource.open(path)``. """ ds = DataSource(destpath) return ds.open(path, mode, encoding=encoding, newline=newline) @set_module('numpy') class DataSource(object): """ DataSource(destpath='.') A generic data source file (file, http, ftp, ...). DataSources can be local files or remote files/URLs. The files may also be compressed or uncompressed. DataSource hides some of the low-level details of downloading the file, allowing you to simply pass in a valid file path (or URL) and obtain a file object. Parameters ---------- destpath : str or None, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory. Notes ----- URLs require a scheme string (``http://``) to be used, without it they will fail:: >>> repos = DataSource() >>> repos.exists('www.google.com/index.html') False >>> repos.exists('http://www.google.com/index.html') True Temporary directories are deleted when the DataSource is deleted. Examples -------- :: >>> ds = DataSource('/home/guido') >>> urlname = 'http://www.google.com/index.html' >>> gfile = ds.open('http://www.google.com/index.html') # remote file >>> ds.abspath(urlname) '/home/guido/www.google.com/site/index.html' >>> ds = DataSource(None) # use with temporary file >>> ds.open('/home/guido/foobar.txt') <open file '/home/guido.foobar.txt', mode 'r' at 0x91d4430> >>> ds.abspath('/home/guido/foobar.txt') '/tmp/tmpy4pgsP/home/guido/foobar.txt' """ def __init__(self, destpath=os.curdir): """Create a DataSource with a local path at destpath.""" if destpath: self._destpath = os.path.abspath(destpath) self._istmpdest = False else: import tempfile # deferring import to improve startup time self._destpath = tempfile.mkdtemp() self._istmpdest = True def __del__(self): # Remove temp directories if hasattr(self, '_istmpdest') and self._istmpdest: shutil.rmtree(self._destpath) def _iszip(self, filename): """Test if the filename is a zip file by looking at the file extension. """ fname, ext = os.path.splitext(filename) return ext in _file_openers.keys() def _iswritemode(self, mode): """Test if the given mode will open a file for writing.""" # Currently only used to test the bz2 files. _writemodes = ("w", "+") for c in mode: if c in _writemodes: return True return False def _splitzipext(self, filename): """Split zip extension from filename and return filename. *Returns*: base, zip_ext : {tuple} """ if self._iszip(filename): return os.path.splitext(filename) else: return filename, None def _possible_names(self, filename): """Return a tuple containing compressed filename variations.""" names = [filename] if not self._iszip(filename): for zipext in _file_openers.keys(): if zipext: names.append(filename+zipext) return names def _isurl(self, path): """Test if path is a net location. Tests the scheme and netloc.""" # We do this here to reduce the 'import numpy' initial import time. if sys.version_info[0] >= 3: from urllib.parse import urlparse else: from urlparse import urlparse # BUG : URLs require a scheme string ('http://') to be used. # www.google.com will fail. # Should we prepend the scheme for those that don't have it and # test that also? Similar to the way we append .gz and test for # for compressed versions of files. scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path) return bool(scheme and netloc) def _cache(self, path): """Cache the file specified by path. Creates a copy of the file in the datasource cache. """ # We import these here because importing urllib2 is slow and # a significant fraction of numpy's total import time. if sys.version_info[0] >= 3: from urllib.request import urlopen from urllib.error import URLError else: from urllib2 import urlopen from urllib2 import URLError upath = self.abspath(path) # ensure directory exists if not os.path.exists(os.path.dirname(upath)): os.makedirs(os.path.dirname(upath)) # TODO: Doesn't handle compressed files! if self._isurl(path): try: openedurl = urlopen(path) f = _open(upath, 'wb') try: shutil.copyfileobj(openedurl, f) finally: f.close() openedurl.close() except URLError: raise URLError("URL not found: %s" % path) else: shutil.copyfile(path, upath) return upath def _findfile(self, path): """Searches for ``path`` and returns full path if found. If path is an URL, _findfile will cache a local copy and return the path to the cached file. If path is a local file, _findfile will return a path to that local file. The search will include possible compressed versions of the file and return the first occurrence found. """ # Build list of possible local file paths if not self._isurl(path): # Valid local paths filelist = self._possible_names(path) # Paths in self._destpath filelist += self._possible_names(self.abspath(path)) else: # Cached URLs in self._destpath filelist = self._possible_names(self.abspath(path)) # Remote URLs filelist = filelist + self._possible_names(path) for name in filelist: if self.exists(name): if self._isurl(name): name = self._cache(name) return name return None def abspath(self, path): """ Return absolute path of file in the DataSource directory. If `path` is an URL, then `abspath` will return either the location the file exists locally or the location it would exist when opened using the `open` method. Parameters ---------- path : str Can be a local file or a remote URL. Returns ------- out : str Complete path, including the `DataSource` destination directory. Notes ----- The functionality is based on `os.path.abspath`. """ # We do this here to reduce the 'import numpy' initial import time. if sys.version_info[0] >= 3: from urllib.parse import urlparse else: from urlparse import urlparse # TODO: This should be more robust. Handles case where path includes # the destpath, but not other sub-paths. Failing case: # path = /home/guido/datafile.txt # destpath = /home/alex/ # upath = self.abspath(path) # upath == '/home/alex/home/guido/datafile.txt' # handle case where path includes self._destpath splitpath = path.split(self._destpath, 2) if len(splitpath) > 1: path = splitpath[1] scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path) netloc = self._sanitize_relative_path(netloc) upath = self._sanitize_relative_path(upath) return os.path.join(self._destpath, netloc, upath) def _sanitize_relative_path(self, path): """Return a sanitised relative path for which os.path.abspath(os.path.join(base, path)).startswith(base) """ last = None path = os.path.normpath(path) while path != last: last = path # Note: os.path.join treats '/' as os.sep on Windows path = path.lstrip(os.sep).lstrip('/') path = path.lstrip(os.pardir).lstrip('..') drive, path = os.path.splitdrive(path) # for Windows return path def exists(self, path): """ Test if path exists. Test if `path` exists as (and in this order): - a local file. - a remote URL that has been downloaded and stored locally in the `DataSource` directory. - a remote URL that has not been downloaded, but is valid and accessible. Parameters ---------- path : str Can be a local file or a remote URL. Returns ------- out : bool True if `path` exists. Notes ----- When `path` is an URL, `exists` will return True if it's either stored locally in the `DataSource` directory, or is a valid remote URL. `DataSource` does not discriminate between the two, the file is accessible if it exists in either location. """ # We import this here because importing urllib2 is slow and # a significant fraction of numpy's total import time. if sys.version_info[0] >= 3: from urllib.request import urlopen from urllib.error import URLError else: from urllib2 import urlopen from urllib2 import URLError # Test local path if os.path.exists(path): return True # Test cached url upath = self.abspath(path) if os.path.exists(upath): return True # Test remote url if self._isurl(path): try: netfile = urlopen(path) netfile.close() del(netfile) return True except URLError: return False return False def open(self, path, mode='r', encoding=None, newline=None): """ Open and return file-like object. If `path` is an URL, it will be downloaded, stored in the `DataSource` directory and opened from there. Parameters ---------- path : str Local file path or URL to open. mode : {'r', 'w', 'a'}, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by `path`. Default is 'r'. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `io.open` uses. newline : {None, str}, optional Newline to use when reading text file. Returns ------- out : file object File object. """ # TODO: There is no support for opening a file for writing which # doesn't exist yet (creating a file). Should there be? # TODO: Add a ``subdir`` parameter for specifying the subdirectory # used to store URLs in self._destpath. if self._isurl(path) and self._iswritemode(mode): raise ValueError("URLs are not writeable") # NOTE: _findfile will fail on a new file opened for writing. found = self._findfile(path) if found: _fname, ext = self._splitzipext(found) if ext == 'bz2': mode.replace("+", "") return _file_openers[ext](found, mode=mode, encoding=encoding, newline=newline) else: raise IOError("%s not found." % path) class Repository (DataSource): """ Repository(baseurl, destpath='.') A data repository where multiple DataSource's share a base URL/directory. `Repository` extends `DataSource` by prepending a base URL (or directory) to all the files it handles. Use `Repository` when you will be working with multiple files from one base URL. Initialize `Repository` with the base URL, then refer to each file by its filename only. Parameters ---------- baseurl : str Path to the local directory or remote location that contains the data files. destpath : str or None, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory. Examples -------- To analyze all files in the repository, do something like this (note: this is not self-contained code):: >>> repos = np.lib._datasource.Repository('/home/user/data/dir/') >>> for filename in filelist: ... fp = repos.open(filename) ... fp.analyze() ... fp.close() Similarly you could use a URL for a repository:: >>> repos = np.lib._datasource.Repository('http://www.xyz.edu/data') """ def __init__(self, baseurl, destpath=os.curdir): """Create a Repository with a shared url or directory of baseurl.""" DataSource.__init__(self, destpath=destpath) self._baseurl = baseurl def __del__(self): DataSource.__del__(self) def _fullpath(self, path): """Return complete path for path. Prepends baseurl if necessary.""" splitpath = path.split(self._baseurl, 2) if len(splitpath) == 1: result = os.path.join(self._baseurl, path) else: result = path # path contains baseurl already return result def _findfile(self, path): """Extend DataSource method to prepend baseurl to ``path``.""" return DataSource._findfile(self, self._fullpath(path)) def abspath(self, path): """ Return absolute path of file in the Repository directory. If `path` is an URL, then `abspath` will return either the location the file exists locally or the location it would exist when opened using the `open` method. Parameters ---------- path : str Can be a local file or a remote URL. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. Returns ------- out : str Complete path, including the `DataSource` destination directory. """ return DataSource.abspath(self, self._fullpath(path)) def exists(self, path): """ Test if path exists prepending Repository base URL to path. Test if `path` exists as (and in this order): - a local file. - a remote URL that has been downloaded and stored locally in the `DataSource` directory. - a remote URL that has not been downloaded, but is valid and accessible. Parameters ---------- path : str Can be a local file or a remote URL. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. Returns ------- out : bool True if `path` exists. Notes ----- When `path` is an URL, `exists` will return True if it's either stored locally in the `DataSource` directory, or is a valid remote URL. `DataSource` does not discriminate between the two, the file is accessible if it exists in either location. """ return DataSource.exists(self, self._fullpath(path)) def open(self, path, mode='r', encoding=None, newline=None): """ Open and return file-like object prepending Repository base URL. If `path` is an URL, it will be downloaded, stored in the DataSource directory and opened from there. Parameters ---------- path : str Local file path or URL to open. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. mode : {'r', 'w', 'a'}, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by `path`. Default is 'r'. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `io.open` uses. newline : {None, str}, optional Newline to use when reading text file. Returns ------- out : file object File object. """ return DataSource.open(self, self._fullpath(path), mode, encoding=encoding, newline=newline) def listdir(self): """ List files in the source Repository. Returns ------- files : list of str List of file names (not containing a directory part). Notes ----- Does not currently work for remote repositories. """ if self._isurl(self._baseurl): raise NotImplementedError( "Directory listing of URLs, not supported yet.") else: return os.listdir(self._baseurl)
{ "repo_name": "ryfeus/lambda-packs", "path": "Opencv_pil/source36/numpy/lib/_datasource.py", "copies": "1", "size": "25512", "license": "mit", "hash": -6332042566699343000, "line_mean": 31.1309823678, "line_max": 80, "alpha_frac": 0.5833725306, "autogenerated": false, "ratio": 4.378990731204944, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00013317289000504514, "num_lines": 794 }
# A file that defines the custom data structs used in our assignment from helper import * from collections import deque variables = [] facts_raw = [] rules = [] _and = '&' _or = '|' _not = '!' _inclusive_not = '@' class Variable(object): """ Class that represents the basic state of a variable """ def __init__(self, name="", str_val="", bool_val=False, bool_val_soft=False, applied_rule=None): """ object state includes string value and truth value """ self.name = name self.string_value = str_val self.truth_value = bool_val self.truth_value_soft = bool_val_soft self.applied_rule = applied_rule def __eq__(self, other): return (isinstance(other, self.__class__) and self.name == other.name) def __str__(self): """ so str() operator can be used """ return '{} = "{}"'.format(self.name, self.string_value) class Rule(object): def __init__(self, exp, var): self.expression = exp # Expression Object self.variable = var # Variable object def __str__(self): return str(self.expression) + " -> " + self.variable.name def __repr__(self): return str(self) def evaluate(self): pass def validate(self): """ validates that all variables """ class Expression(object): def __init__(self, string): self.expr_str = string self.token_list = self.tokenize() def __str__(self): return str(self.expr_str) def why_stringify(self): agg_string = '' operators = ['(',')', _and, _or, _not] operators_map = { '(': '(', ')': ')', _and: 'AND', _or: 'OR', _not: 'NOT' } for item in self.token_list: if item not in operators: var = find_var(variables, item) agg_string = agg_string + ' ' + var.string_value else: agg_string = agg_string + ' ' + operators_map.get(item) return agg_string def tokenize(self): """ Parses a string into token list """ operators = ['(',')', _and, _or, _not] array = list() # hold the tokens aggregator = "" # accumulates the characters in a variable string for char in self.expr_str: if char in operators: #if an operator, add current variable and the op if aggregator != "": array.append(aggregator) aggregator = "" array.append(char) elif char == " ": # if a space, stop aggregating and add the variable if aggregator != "": array.append(aggregator) aggregator = "" elif char.isalpha() or char == '_': # if A-Z, a-z, or _, add to current variable string aggregator = aggregator + char else: pass if aggregator != "": array.append(aggregator) return array def evaluate(self): queue = get_RPN(self.token_list) root_node = build_tree(queue) return calc_tree(root_node) def soft_evaluate(self): queue = get_RPN(self.token_list) root_node = build_tree(queue) return calc_tree_soft(root_node) class TreeNode(object): """ Class used to make abstract syntax tree for Expressions""" def __init__(self, value="", left=None, right=None, neg=False): self.value = value self.left = left self.right = right self.negate = neg def __str__(self): # expects v if not self.negate: return str(self.value) else: return "Not " + str(self.value) def get_RPN(token_list): """ Uses shunting-yard algo to get infix into RPN form Handles '!' outside a Parenthesis in a stateful way Returns None if malformed input Returns a queue of Variables in reverse polish notation if successful Most comments come from the wikipedia article on this algo """ # initialize data structures : SY is stack based stack = list() # stack holds operator and parenthesis queue = deque([]) # queue holds expression in RPN nm_stack = list() # holds if expression is in negate mode or not nm_stack.append(False) # start off in a state that is not negate mode # convienence array to easily check check char is an 'and' or 'or' operators = [_and, _or] def is_in_negate_mode(): """ True if in negate mode, false otherwise""" l = len(nm_stack) if l > 0: return nm_stack[l-1] else: return False # Read a token for i in range(0, len(token_list)): token = token_list[i] # if current token is a variable, append it to output queue if is_var(variables, token): var = find_var(variables, token) # if in negate mode, apply demorgan if is_in_negate_mode(): queue.append('!') queue.append(var) # manage nots based on negate mode elif is_valid_op(token): if token == _not: next_token = token_list[i+1] if is_in_negate_mode(): if next_token == '(': nm_stack.append(False) else: queue.append(token) else: if next_token == '(': nm_stack.append(True) else: queue.append(token) # if token is an operator (o1) elif token in operators: # while there is an operator token on top of the stack (o2), and either: # o1 is left associative and its precedence is <= o2 # o1 is right associative and it precedence is < o2 while len(stack) > 0 and stack[len(stack) -1] in operators: # pop o2 and append to output queue op = stack.pop() queue.append(op) # then push o1 onto the stack # if in negate mode, apply demorgan first if is_in_negate_mode(): stack.append(negate_op(token)) else: stack.append(token) # If the token is a left parenthesis, then push it onto the stack. elif token == '(': stack.append(token) # if negate mode was not altered by previous token # maintain negate mode from outer scope if (i-1 >= 0) and token_list[i-1] != '!': nm_stack.append(is_in_negate_mode()) # if the token is a right parenthesis: elif token == ')': paren_matched = False # Until the token at the top of the stack is a left parenthesis, # pop operators off the stack onto the output queue. while len(stack) > 0: item = stack.pop() if item == '(': paren_matched = True if len(nm_stack) > 1: nm_stack.pop() break else: queue.append(item) # If the stack runs out without finding a left parenthesis, # then there are mismatched parentheses if not paren_matched: return None else: #TODO: failure mode here, token matches nothing we can identify return None # When there are no more tokens to read # While there are still operator tokens in the stack while (len(stack) > 0): top = stack.pop() # If the operator token on the top of the stack is a parenthesis, # then there are mismatched parentheses if top == '(' or top == ')': return None # Pop the operator onto the output queue else: queue.append(top) # if there are two negatives right after eachother, they cancel eachother for i in range(0,len(queue)-1): if queue[i] == '!' and queue[i+1] == '!': queue[i] = '' queue[i+1] = '' return queue def build_tree(queue): """ Uses queue built in get_RPN method to build a tree ... Head node is returned in success None is returned in failure """ operators = [_and, _or] stack = list() while len(queue) > 0: item = queue.popleft(); if item == '': pass elif type(item) is Variable: stack.append(TreeNode(value=item)) elif item == _not: if len(queue) > 0: item2 = queue.popleft() else: return None stack.append(TreeNode(value=item2, neg=True)) elif item in operators: right=stack.pop() left= stack.pop() stack.append(TreeNode(value=item, right=right, left=left, neg=False)) return stack.pop() ## gets a truth value given an expression Node def calc_tree(node): # if leaf, it is a Variable if node.right is None and node.left is None: if node.negate: return not node.value.truth_value else: return node.value.truth_value elif node.value == _and: return calc_tree(node.right) and calc_tree(node.left) elif node.value == _or: return calc_tree(node.right) or calc_tree(node.left) ## gets a truth value given an expression Node def calc_tree_soft(node): # if leaf, it is a Variable if node.right is None and node.left is None: if node.negate: return not node.value.truth_value_soft else: return node.value.truth_value_soft elif node.value == _and: return calc_tree_soft(node.right) and calc_tree_soft(node.left) elif node.value == _or: return calc_tree_soft(node.right) or calc_tree_soft(node.left) def print_inorder(node): if node is not None: if node.left is not None: print_inorder(node.left) print node if node.right is not None: print_inorder(node.right) def forward_chain(rules, facts): flag = True while(flag): flag = False for rule in rules: expr = rule.expression # var must exist in variables, add check var = rule.variable expr_truth_value = expr.evaluate() if expr_truth_value and (var not in facts): var.truth_value = True facts.append(var) flag = True def query_for_fact(var, rule_dict): """ var is variable obj returns nothing, but updates soft truth values in var objs """ if var in facts_raw: var.truth_value_soft = True else: rule_exists = False for rule in rule_dict.keys(): if rule.variable == var and rule_dict[rule] is False: rule_exists = True rule_dict[rule] = True expr = rule.expression for item in expr.token_list: if item not in [_and, _not, _or, '(', ')']: # it is a var new_var = find_var(variables, item) query_for_fact(new_var, rule_dict) truth = expr.soft_evaluate() var.truth_value_soft = truth var.applied_rule = rule break if rule_exists is False: var.truth_value_soft = False def query(expression): rule_dict = {} for rule in rules: rule_dict[rule] = False for item in expression.token_list: if item not in [_and, _not, _or, '(', ')']: # it is a var var = find_var(variables, item) query_for_fact(var, rule_dict) result = expression.soft_evaluate() # inorder_clean(node) return result # see note above why() for more info def why_for_fact(var, rule_dict, string_queue, used_vars): """ var is variable obj rule dict holds what rules have / have not been used to prevent looping string queue hold order of found rules returns nothing, but updates soft truth values in var objs """ if var in facts_raw: if var not in used_vars: # do not want to evaluate same var twice if var.truth_value == True: var.truth_value_soft = True string = 'I KNOW THAT {}'.format(var.string_value) else: var.string_value string = 'I KNOW IT IS NOT TRUE THAT {}'.format(var.string_value) used_vars.append(var) # mark this var as evaluated string_queue.append(string) # add this to the string queue, will eventually be printed else: # not in facts list, need to eval rules rule_exists = False # flag if a rule exists that can help determine our variable found_positive = False # flag that marks if variable can be proven true neg_list = [] # temp container that holds negative results (see piazza) for rule in rule_dict.keys(): if rule.variable == var and rule_dict[rule] is False and rule.variable not in used_vars: rule_exists = True expr = rule.expression for item in expr.token_list: if item not in [_and, _not, _or, '(', ')']: # it is a var new_var = find_var(variables, item) if new_var not in used_vars: why_for_fact(new_var, rule_dict, string_queue, used_vars) truth = expr.soft_evaluate() var.truth_value_soft = truth if truth == True: result_str = 'BECAUSE {} I KNOW THAT {}'.format(expr.why_stringify(), var.string_value) rule_dict[rule] = True found_positive = True string_queue.append(result_str) used_vars.append(var) # mark this var as evaluated else: result_str = \ 'BECAUSE IT IS NOT TRUE THAT {} I CANNOT PROVE {}'.format(expr.why_stringify(), var.string_value) neg_list.append(result_str) if found_positive == False: for item in neg_list: string_queue.append(item) used_vars.append(var) # mark this var as evaluated var.truth_value_soft = False if rule_exists is False: var.truth_value_soft = False used_vars.append(var) # mark this var as evaluated # Current idea is to build up string responses in a queue # this queue is built in both why_for_fact as well as explain_result_2 # in w_f_f, strings are found corresponding to variables in the variables array and the rules list # therefore, all strings in the 'I Know', 'I KNOW IT IS NOT', 'BECAUSE', and 'BECAUSE it is not true' # are built here # in e_r_2, strings are found that need truth values to be evalutated # therefore, all 'THUS I know that' and 'Thus I cannot porve' strings are built there # The used Variables list makes sure you do not check a variable's status more than once def why(expression): rule_dict = {} string_queue = deque([]) used_variables = [] for rule in rules: rule_dict[rule] = False for item in expression.token_list: if item not in [_and, _not, _or, '(', ')']: # it is a var var = find_var(variables, item) result_str = why_for_fact(var, rule_dict, string_queue, used_variables) result = expression.soft_evaluate() #for item in string_queue: print item token_list = expression.token_list queue = get_RPN_2(token_list) node = build_tree_2(queue) truth, result_str = explain_result_2(node, string_queue) print truth while len(string_queue) > 0: print string_queue.popleft() inorder_clean(node) return result, result_str def inorder_clean(node): """ Resets the soft truth values and the associated rules in an expression tree""" if node is not None: if node.left is not None: inorder_clean(node.left) if type(node.value) == Variable: node.value.truth_value_soft = False node.value.applied_rule = None if node.right is not None: inorder_clean(node.right) ################################## def get_RPN_2(token_list): """ Uses shunting-yard algo to get infix into RPN form Handles '!' outside a Parenthesis in a stateful way Returns None if malformed input Returns a queue of Variables in reverse polish notation if successful """ # initialize data structures : SY is stack based stack = list() # stack holds operator and parenthesis queue = deque([]) # queue holds expression in RPN # convienence array to easily check check char is an 'and' or 'or' operators = [_and, _or, _not] #Read a token for i in range(0, len(token_list)): #print str(queue) token = token_list[i] # if current token is a variable, append it to output queue if is_var(variables, token): var = find_var(variables, token) queue.append(var) # if token is an operator (o1) elif token in operators: # determine type of not used if token == _not: next_token = token_list[i+1] if next_token == '(': token = _inclusive_not # while there is an operator token on top of the stack (o2), and either: # o1 is left associative and its precedence is <= o2, or # o1 is right associative and it precedence is < o2 while (len(stack) > 0) and (stack[len(stack) -1] in operators) and \ ((is_left_assoc(token) and has_less_precedence(token, stack[len(stack) -1])) or \ ((not is_left_assoc(token)) and has_less_precedence(token, stack[len(stack) -1]))): # pop o2 and append to output queue op = stack.pop() queue.append(op) # then push o1 onto the stack stack.append(token) # If the token is a left parenthesis, then push it onto the stack. elif token == '(': stack.append(token) # if the token is a right parenthesis: elif token == ')': paren_matched = False # Until the token at the top of the stack is a left parenthesis, # pop operators off the stack onto the output queue. while len(stack) > 0: item = stack.pop() if item == '(': paren_matched = True break else: queue.append(item) # If the stack runs out without finding a left parenthesis, # then there are mismatched parentheses if not paren_matched: print 'mismatched parenthesis' return None else: #TODO: failure mode here, token matches nothing we can identify print "Invalid token: " + token return None # When there are no more tokens to read # While there are still operator tokens in the stack while (len(stack) > 0): top = stack.pop() # If the operator token on the top of the stack is a parenthesis, if top == '(' or top == ')': # then there are mismatched parentheses print 'mismatched parenthesis' return None # Pop the operator onto the output queue else: queue.append(top) return queue def build_tree_2(queue): """ Uses queue built in get_RPN method to build a tree ... Head node is returned in success None is returned in failure """ operators = [_and, _or] stack = list() while len(queue) > 0: item = queue.popleft(); if item == '': pass elif type(item) is Variable: stack.append(TreeNode(value=item)) elif item == _inclusive_not: right=stack.pop() stack.append(TreeNode(value=item, right=right, left=None, neg=False)) elif item == _not: last_node = stack.pop() last_node.negate = not last_node.negate stack.append(last_node) elif item in operators: right=stack.pop() left= stack.pop() stack.append(TreeNode(value=item, right=right, left=left, neg=False)) return stack.pop() ## gets a truth value given an expression Node def calc_tree_2(node): # if leaf, it is a Variable if node.right is None and node.left is None: if node.negate: return not node.value.truth_value else: return node.value.truth_value elif node.value == _inclusive_not: if node.negate: return calc_tree_2(node.right) else: return not calc_tree_2(node.right) elif node.value == _and: return calc_tree_2(node.right) and calc_tree_2(node.left) elif node.value == _or: return calc_tree_2(node.right) or calc_tree_2(node.left) def calc_tree_soft_2(node): # if leaf, it is a Variable if node.right is None and node.left is None: if node.negate: return not node.value.truth_value_soft else: return node.value.truth_value_soft elif node.value == _inclusive_not: if node.negate: return calc_tree_soft_2(node.right) else: return not calc_tree_soft_2(node.right) elif node.value == _and: return calc_tree_soft_2(node.right) and calc_tree_soft_2(node.left) elif node.value == _or: return calc_tree_soft_2(node.right) or calc_tree_soft_2(node.left) def explain_result(node): # if leaf, it is a Variable if node.right is None and node.left is None: if node.value.applied_rule is None: if node.negate: print 'I KNOW IT IS NOT TRUE THAT ' + node.value.string_value return 'I KNOW IT IS NOT TRUE THAT ' + node.value.string_value else: print 'I KNOW THAT ' + node.value.string_value return 'I KNOW THAT ' + node.value.string_value else: print 'BECAUSE ' + node.value.applied_rule.exp.why_stringify() + ' I know that ' + str(node.value.truth_value_soft) return 'BECAUSE ' + node.value.applied_rule.exp.why_stringify() + ' I know that ' + str(node.value.truth_value_soft) elif node.value == _inclusive_not: if node.applied_rule is None: if node.negate: print 'I know that not not ' + explain_result(node.right) return 'I know that not not ' + explain_result(node.right) else: print 'I know that not ' + node.value.string_value + ' is ' + str(node.value.truth_value_soft) return 'I know that not ' + node.value.string_value + ' is ' + str(node.value.truth_value_soft) elif node.value == _and: print 'I know that ( ' + explain_result(node.right) + ' and ' + explain_result(node.left) + ' )' return 'I know that ( ' + explain_result(node.right) + ' and ' + explain_result(node.left) + ' )' elif node.value == _or: print 'I know that ( ' + explain_result(node.right) + ' or ' + explain_result(node.left) + ' )' return 'I know that ( ' + explain_result(node.right) + ' or ' + explain_result(node.left) + ' )' # see note by 'why' function # email me if you need any of this explained before sunday night def explain_result_2(node, string_queue): # if leaf, it is a Variable if node.right is None and node.left is None: if node.negate: return not node.value.truth_value_soft, node.value.string_value else: return node.value.truth_value_soft, node.value.string_value elif node.value == _inclusive_not: if node.negate: truth, string = explain_result_2(node.right, string_queue) if truth == True: string_queue.append('THUS I KNOW THAT NOT NOT {}'.format(string)) else: string_queue.append('THUS I CANNOT PROVE NOT NOT {}'.format(string)) info_string = 'NOT NOT {}'.format(string) return truth, info_string else: truth, string = explain_result_2(node.right, string_queue) truth = not truth if truth == True: string_queue.append('THUS I KNOW THAT NOT {}'.format(string)) else: string_queue.append('THUS I CANNOT PROVE NOT {}'.format(string)) info_string = 'NOT NOT {}'.format(string) return not truth, info_string elif node.value == _and: r_truth, r_string = explain_result_2(node.right, string_queue) l_truth, l_string = explain_result_2(node.left, string_queue) truth = r_truth and l_truth string = '( {} AND {} )'.format(r_string, l_string) if truth == True: string_queue.append('THUS I KNOW THAT {}'.format(string, string_queue)) else: string_queue.append('THUS I CANNOT PROVE {}'.format(string, string_queue)) return truth, string elif node.value == _or: r_truth, r_string = explain_result_2(node.right) l_truth, l_string = explain_result_2(node.left) truth = r_truth or l_truth string = '( {} OR {} )'.format(r_string, l_string) if truth == True: string_queue.append('THUS I KNOW THAT {}'.format(string, string_queue)) else: string_queue.append('THUS I CANNOT PROVE {}'.format(string, string_queue)) return truth, string
{ "repo_name": "A-Beck/Theorem_Prover", "path": "src/datastructures.py", "copies": "1", "size": "26415", "license": "mit", "hash": -193252287472937150, "line_mean": 37.5635036496, "line_max": 128, "alpha_frac": 0.5491955328, "autogenerated": false, "ratio": 4.083951762523191, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.01115937784348981, "num_lines": 685 }
"""A file to calculate the pose transformation between a camera and robot and a tool offset from correspondences. """ # The MIT License (MIT) # # Copyright (c) 2016 GTRC. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import division import argparse import json from scipy import optimize import datetime import os import math import numpy as np import cv2 def main(): """ Exposes :py:func:`compute_transformation` to the commandline. Run with arg `-h` for more info. """ # Parse in arguments parser = argparse.ArgumentParser( description="Compute transformation between camera and robot given " "existing correspondences") parser.add_argument("--correspondences", type=str, help='The filename for the file containing the list of' 'correspondences, which is generated by' 'get_correspondences.py. ' 'Defaults to: correspondences.json', default="correspondences.json") parser.add_argument("--out", type=str, help="File to save output to", default="transformation.json") parser.add_argument("--cam2rob", type=float, nargs=6, help="Initial guess for the camera to robot " "transformation, x,y,z,rotation vector", metavar=('x','y','z','a','b','c'), default=np.array([0, 0, 1000, 0, 0, 0]).tolist()) parser.add_argument("--tcp2target", type=float, nargs=6, help="Initial guess for the tcp to target " "(robot tool), x,y,z,rotation vector", metavar=('x', 'y', 'z', 'a', 'b', 'c'), default=np.array([0, 0, 0, 0, 0, 0]).tolist()) parser.add_argument("--max_cam2rob", type=float, help="Maximum deviation of the cam2robot " "transformation from the guess", default=2000) parser.add_argument("--max_tcp2target", type=float, help="Maximum deviation of the cam2target " "transformation from the guess", default=500) parser.add_argument("--iter", type=int, help="number of iterations to " "perform of the basin hopping" "routine.", default=250) parser.add_argument("--minimizer", type=str, help="The minimizer to use at " "each basin hopping stop" "Valid options are: SLSQP" "TNC, and L-BFGS-B", default="SLSQP") args = parser.parse_args() result = compute_transformation( correspondences=args.correspondences, file_out=args.out, cam2rob_guess=args.cam2rob, tcp2target_guess=args.tcp2target, max_cam2rob_deviation=args.max_cam2rob, max_tcp2target_deviation=args.max_tcp2target, iterations=args.iter, minimizer=args.minimizer ) print('Final Result:\n{}'.format(result)) def compute_transformation(correspondences, file_out, cam2rob_guess, tcp2target_guess, max_cam2rob_deviation, max_tcp2target_deviation, iterations, minimizer): """Computes the camera to robot base and tcp to target (flange to tcp in some cases) transformations. Uses matched coorespondences of transformations from the camera to a fixed point past the final robot axis (for example a grid or other marker) and the robot base to tcp transformation. Args: correspondences (string): The filename of the correspondences file. This file should be a json file with fields: 'time', 'tcp2robot', 'camera2grid'. 'tcp2robot' and 'camera2grid' should be lists of lists, with each individual list being a Rodrigues vector (x,y,z,3 element rotation vector/axis-angle). Linear distance must be consistent (mm are recommended). Angular distances must be in radians. file_out (string): The name of the file to be output (no extension) cam2rob_guess (6 element list): The Rodrigues vector for the initial guess of the camera to robot transformation tcp2target_guess (6 element list): The Rodrigues vector for the initial guess of the tcp to target transformation max_cam2rob_deviation (float): The x,y,z range around the initial camera to robot guess which should be searched. max_tcp2target_deviation (float): The x,y,z range around the initial camera to target guess which should be searched. iterations (int): The number of iterations of basin hopping to perform. minimizer (str): The minimizer to use at each basin hopping stop Valid options are: SLSQP TNC, and L-BFGS-B Returns: The results as a dictionary """ with open(correspondences, 'r') as correspondences_file: correspondences_dictionary = json.load(correspondences_file) write_time = correspondences_dictionary['time'] # nx6 arrays x,y,z,axis-angle: tcp2robot = correspondences_dictionary['tcp2robot'] camera2grid = correspondences_dictionary['camera2grid'] print("Loaded data from {}".format(write_time)) #optimize guess = np.concatenate((cam2rob_guess, tcp2target_guess)) bounds = Bounds([guess[0] + max_cam2rob_deviation, guess[1] + max_cam2rob_deviation, guess[2] + max_cam2rob_deviation, np.pi, np.pi, np.pi, guess[6] + max_tcp2target_deviation, guess[7] + max_tcp2target_deviation, guess[8] + max_tcp2target_deviation, np.pi, np.pi, np.pi], [guess[0] - max_cam2rob_deviation, guess[1] - max_cam2rob_deviation, guess[2] - max_cam2rob_deviation, -np.pi, -np.pi, -np.pi, guess[6] - max_tcp2target_deviation, guess[7] - max_tcp2target_deviation, guess[8] - max_tcp2target_deviation, -np.pi, -np.pi, -np.pi]) bounds_tuple = [(low, high) for low, high in zip(bounds.xmin, bounds.xmax)] # define the new step taking routine and pass it to basinhopping take_step = RandomDisplacementBounds(bounds.xmin, bounds.xmax) minimizer_kwargs = {"args": (tcp2robot, camera2grid), "method": minimizer, "bounds": bounds_tuple, "options":{"maxiter": 25000}} print('starting basinhopping') result = optimize.basinhopping( func=error, x0=guess, minimizer_kwargs=minimizer_kwargs, accept_test=bounds, disp=False, callback=callback, take_step=take_step, niter=iterations, interval=25, niter_success=math.ceil(iterations/7.5)) json_dict = {"time": str(datetime.datetime.now()), "cam2robot": {"xyz-angle": result.x[:6].tolist(), "Tmatrix": vector2mat(result.x[:6]).tolist()}, "tcp2target": {"xyz-angle": result.x[6:].tolist(), "Tmatrix": vector2mat(result.x[6:]).tolist()}, "minimization": {"terminated for":result.message, "Number of minimization failures":result.minimization_failures, "Number of iterations":result.nit, "Number of executions of error function":result.nfev, "method": minimizer, "best result":{"success":str(result.lowest_optimization_result.success), "message": result.lowest_optimization_result.message, "error": result.lowest_optimization_result.fun} } } with open(os.path.splitext(file_out)[0] + '.json', 'w') as \ result_json_file: json.dump(json_dict, result_json_file, indent=4) return json_dict class Bounds(object): def __init__(self, xmax, xmin): self.xmax = np.array(xmax) self.xmin = np.array(xmin) def __call__(self, **kwargs): x = kwargs["x_new"] tmax = bool(np.all(x <= self.xmax)) tmin = bool(np.all(x >= self.xmin)) return tmax and tmin def error(guess, tcp2robot, camera2grid, ratio=0.25): """ Calculates the difference between a guess at robot 2 cam transformations compared to gathered data. Uses manhattan error for the distance (as opposed to true line distance). Finds the angular difference between two points. Takes the weighted sum of the manhattan distance and angular distance based on the ratio. Args: guess (1x12 array): Input guess array. Values will range between the bounds passed in the optimize function. 6 dof camera 2 robot (x,y,z,axis-angle), 6 dof tcp 2 target (x,y,z,axis-angle) tcp2robot (nx6 array): Array of gathered data for the pose of the robot tool center point wrt. the robot coordinate base camera2grid (nx6 array): Array of gathered data for the transformation from the camera to the target ratio (float): The ratio of weight given to the manhattan error vs the angular error. A higer value will give more weight to the manhattan error and less to the the angular error. Must be in the range [0,1] Returns: A float, the total error between the guess and the collected data """ errors = np.zeros(len(tcp2robot)) total_error = 0 if ratio < 0: raise ValueError("ratio must be greater than or equal to zero") if ratio > 1: raise ValueError("ratio must be less than or equal to one") for i in range(len(tcp2robot)): guess_cam2rob = vector2mat(guess[:6]) guess_tcp2target = vector2mat(guess[6:]) guess_cam2tcp = np.matmul(guess_cam2rob, vector2mat(np.concatenate( (np.array(tcp2robot[i][:3]), np.array(tcp2robot[i][3:]))))) guess_cam2target = np.matmul(guess_cam2tcp, guess_tcp2target) euclidean_distance = np.sqrt(np.sum(np.square( np.array(guess_cam2target[:3, 3]) - np.array(camera2grid[i][:3]) ))) angular_error = math.acos( (np.trace(np.matmul(vector2mat(np.array(camera2grid[i]))[:3, :3].T, guess_cam2target[:3, :3]))-1)/2) errors[i] = euclidean_distance*ratio + angular_error*(1-ratio) return np.mean(errors[ np.where(mad_based_outlier(np.array(errors)) == False)]) def mad_based_outlier(points, thresh=3.5): """http://stackoverflow.com/questions/22354094/pythonic-way-of-detecting- outliers-in-one-dimensional-observation-data/22357811#22357811""" if len(points.shape) == 1: points = points[:,None] median = np.median(points, axis=0) diff = np.sum((points - median)**2, axis=-1) diff = np.sqrt(diff) med_abs_deviation = np.median(diff) modified_z_score = 0.6745 * diff / med_abs_deviation return modified_z_score > thresh def vector2mat(vector): """ Converts a vector in form x,y,z,axis-angle to a homogenous transformation matrix Args: vector (6 element list): a vector representation form of a transformation matrix. x,y,z,axis-angle Returns: A 4x4 np.ndarry of the homogenous transformation matrix """ transformation_matrix = np.zeros((4, 4)) transformation_matrix[3, 3] = 1 try: transformation_matrix[0:3, 3] = vector[:3, 0] except: transformation_matrix[0:3, 3] = vector[:3] rotation_matrix, _ = cv2.Rodrigues(np.array(vector[3:])) transformation_matrix[:3, :3] = rotation_matrix return transformation_matrix def mat2vector(mat): """ Converts a transformatiion matrix into a 6 dof vector. x,y,z,axis-angle Args: mat (4x4 ndarray): the transformation matrix Returns: A 6 element list, x,y,z,axis-angle """ vector = [0]*6 vector[:3] = np.asarray(mat[:3, 3]) axis_angle, _ = cv2.Rodrigues(np.array(mat[:3, :3])) vector[3:] = axis_angle return vector def callback(x, f, accept): """Prints out the local minimum result found in each iteration of the basinhopping routine.""" print('minimized to: {}\nWith an error of: {}. This is {}ACCEPTED\n'.format(x, f, '' if accept else 'NOT ')) class RandomDisplacementBounds(object): """random displacement with bounds. For use with the baisnhopping routine. Based on: http://stackoverflow.com/questions/21670080""" def __init__(self, xmin, xmax, stepsize=0.5): """Initializes a displacement generator Args: xmin (list of floats): The minimum values for all of the paramaters xmin (list of floats): The maximum values for all of the paramaters stepsize: The initial stepsize for the algorithim. This will be overwritten by the basinhopping routine. """ self.xmin = xmin self.xmax = xmax self.stepsize = stepsize def __call__(self, x): """Take a random step, from the prior, proportional to the stepsize wrt the bounds. Ensure the new position is within the bounds Args: x (np.array of floats): The prior position Returns: The new starting position for optimization """ print('generating points with step size {}, yielding a range of: {} to {}'.format(self.stepsize, x + np.multiply( [-self.stepsize]*x.size, (self.xmax-self.xmin)), x + np.multiply( [self.stepsize]*x.size, (self.xmax-self.xmin)))) while True: xnew = x + np.multiply( np.random.uniform(-self.stepsize, self.stepsize, np.shape(x)), (self.xmax-self.xmin)) if np.all(xnew < self.xmax) and np.all(xnew > self.xmin): break print('finished generating new guess: {}'.format(xnew)) return xnew if __name__ == "__main__": main()
{ "repo_name": "mjsobrep/robot2camera-calibration", "path": "robot2cam_calibration/compute_transformations.py", "copies": "1", "size": "16661", "license": "mit", "hash": -6132702665430488000, "line_mean": 43.0767195767, "line_max": 121, "alpha_frac": 0.5629313967, "autogenerated": false, "ratio": 4.250255102040816, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0013107455458515038, "num_lines": 378 }
# A file to crop blocks from a boxm2 scene # Takes boxm2_dir as input and assumes scene.xml file is present at that location # Writes the cropped parameters to scene-cropped.xml import optparse; from xml.etree.ElementTree import ElementTree #Parse inputs parser = optparse.OptionParser(description='Update BOXM2 Scene without refinement 0'); parser.add_option('--boxm2_dir', action="store", dest="boxm2_dir"); parser.add_option('--min_i', action="store", dest="min_i", type="int"); parser.add_option('--min_j', action="store", dest="min_j", type="int"); parser.add_option('--min_k', action="store", dest="min_k", type="int"); parser.add_option('--max_i', action="store", dest="max_i", type="int"); parser.add_option('--max_j', action="store", dest="max_j", type="int"); parser.add_option('--max_k', action="store", dest="max_k", type="int"); options, args = parser.parse_args() boxm2_dir = options.boxm2_dir; min_i = options.min_i; min_j = options.min_j; min_k = options.min_k; max_i = options.max_i; max_j = options.max_j; max_k = options.max_k; scene_input_file = boxm2_dir + '/scene.xml'; scene_output_file = boxm2_dir + '/scene_cropped.xml'; print 'Parsing: ' print scene_input_file #parse xml file tree_in = ElementTree(); tree_in.parse(scene_input_file); tree_out = ElementTree(); #find all blocks removing those outside the limits blocks = tree_in.getroot().findall('block'); for block in blocks: if block is None: print "Invalid info file: No resolution" sys.exit(-1); i = float(block.get('id_i')); j = float(block.get('id_j')); k = float(block.get('id_k')); if (not (i in range(min_i, max_i))) or (not (j in range(min_j, max_j))) or (not (k in range(min_k, max_k))): tree_in.getroot().remove(block) tree_in.write(scene_output_file);
{ "repo_name": "mirestrepo/voxels-at-lems", "path": "boxm2/boxm2_crop_scene.py", "copies": "1", "size": "1815", "license": "bsd-2-clause", "hash": 5194626558475257000, "line_mean": 30.8596491228, "line_max": 113, "alpha_frac": 0.6655647383, "autogenerated": false, "ratio": 2.9416531604538085, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8960680515357766, "avg_score": 0.029307476679208615, "num_lines": 57 }
# A file to crop blocks from a boxm2 scene # Takes boxm2_dir as input and assumes scene.xml file is present at that location # Writes the cropped parameters to scene-cropped.xml import optparse; from xml.etree.ElementTree import ElementTree #Parse inputs parser = optparse.OptionParser(description='Update BOXM2 Scene without refinement 0'); parser.add_option('--boxm2_dir', action="store", dest="boxm2_dir"); parser.add_option('--min_i', action="store", dest="min_i", type="int"); parser.add_option('--min_j', action="store", dest="min_j", type="int"); parser.add_option('--min_k', action="store", dest="min_k", type="int"); parser.add_option('--max_i', action="store", dest="max_i", type="int"); parser.add_option('--max_j', action="store", dest="max_j", type="int"); parser.add_option('--max_k', action="store", dest="max_k", type="int"); options, args = parser.parse_args() boxm2_dir = options.boxm2_dir; min_i = options.min_i; min_j = options.min_j; min_k = options.min_k; max_i = options.max_i; max_j = options.max_j; max_k = options.max_k; print min_i print min_j print min_k print max_i print max_j print max_k scene_input_file = boxm2_dir + '/scene.xml'; scene_output_file = boxm2_dir + '/scene_cropped.xml'; print 'Parsing: ' print scene_input_file #parse xml file tree_in = ElementTree(); tree_in.parse(scene_input_file); tree_out = ElementTree(); #find all blocks removing those outside the limits blocks = tree_in.getroot().findall('block'); for block in blocks: if block is None: print "Invalid info file: No resolution" sys.exit(-1); i = float(block.get('id_i')); j = float(block.get('id_j')); k = float(block.get('id_k')); if (not (i in range(min_i, max_i))) or (not (j in range(min_j, max_j))) or (not (k in range(min_k, max_k))): tree_in.getroot().remove(block) tree_in.write(scene_output_file);
{ "repo_name": "mirestrepo/voxels-at-lems", "path": "super3d/boxm2_crop_scene.py", "copies": "1", "size": "1949", "license": "bsd-2-clause", "hash": -9193615640268062000, "line_mean": 28.9682539683, "line_max": 113, "alpha_frac": 0.6475115444, "autogenerated": false, "ratio": 2.8874074074074074, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8911980039954148, "avg_score": 0.024587782370651973, "num_lines": 63 }
""" A file to hold all test utilities. Note the project specific overrrides are not being used in the GDC currently. """ from collections import defaultdict import copy import os import yaml import unittest from jsonschema import validate from gdcdictionary import ROOT_DIR, GDCDictionary def load_yaml(path): with open(path, 'r') as f: return yaml.safe_load(f) DATA_DIR = os.path.join(ROOT_DIR, 'examples') project1 = load_yaml(os.path.join(ROOT_DIR, 'schemas/projects/project1.yaml')) projects = {'project1': project1} class BaseTest(unittest.TestCase): def setUp(self): self.dictionary = GDCDictionary() self.definitions = load_yaml(os.path.join(ROOT_DIR, 'schemas', '_definitions.yaml')) def merge_schemas(a, b, path=None): """Recursively zip schemas together """ path = path if path is not None else [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge_schemas(a[key], b[key], path + [str(key)]) elif a[key] == b[key]: pass else: print("Overriding '{}':\n\t- {}\n\t+ {}".format( '.'.join(path + [str(key)]), a[key], b[key])) a[key] = b[key] else: print("Adding '{}':\n\t+ {}".format( '.'.join(path + [str(key)]), b[key])) a[key] = b[key] return a def get_project_specific_schema(projects, project, schema, entity_type): """Look up the core schema for its type and override it with any project level overrides """ root = copy.deepcopy(schema) project_overrides = projects.get(project) if project_overrides: overrides = project_overrides.get(entity_type) if overrides: merge_schemas(root, overrides, [entity_type]) return root def validate_entity(entity, schemata, project=None, name=''): """Validate an entity by looking up the core schema for its type and overriding it with any project level overrides """ local_schema = get_project_specific_schema( projects, project, schemata[entity['type']], entity['type']) result = validate(entity, local_schema) return result def validate_schemata(schemata, metaschema): # validate schemata print('Validating schemas against metaschema... '), for s in schemata.values(): validate(s, metaschema) def assert_link_is_also_prop(link): assert link in s['properties'],\ "Entity '{}' has '{}' as a link but not property".format( s['id'], link) for link in [l['name'] for l in s['links'] if 'name' in l]: assert_link_is_also_prop(link) for subgroup in [l['subgroup'] for l in s['links'] if 'name' not in l]: for link in [l['name'] for l in subgroup if 'name' in l]: assert_link_is_also_prop(link) def check_for_cycles(schemata, ignored_types=None): """Assert the given schemata contain no cycles (outside ignored types).""" if ignored_types is None: ignored_types = [] # Build a bidirectional map representing the links between schema types. forward = defaultdict(set) backward = defaultdict(set) for schema_type, schema in schemata.items(): # Ignore cycles involving types that we know don't hurt anything so we # can detect new cycles that might actually hurt. if schema_type in ignored_types: continue for link in schema.get('links', []): if 'subgroup' in link: target_types = [g['target_type'] for g in link['subgroup']] else: target_types = [link['target_type']] for target_type in target_types: # It's fine for a type to link to itself. Ignore such links # to avoid confusing the below cycle detection algorithm. if target_type != schema_type: forward[schema_type].add(target_type) backward[target_type].add(schema_type) # Iteratively remove types that have no links pointing to them. # If there are no cycles, this will continue to free up types without # any links until the entire map is cleared out. If a cycle exists, # this process will fail to remove all of the links. removable_types = [ schema_type for schema_type in forward if schema_type not in backward ] while removable_types: schema_type = removable_types.pop() for target_type in forward[schema_type]: backward[target_type].remove(schema_type) if not backward[target_type]: removable_types.append(target_type) del backward[target_type] assert not backward, 'cycle detected among {}'.format(backward.keys())
{ "repo_name": "NCI-GDC/gdcdictionary", "path": "tests/utils.py", "copies": "1", "size": "4889", "license": "apache-2.0", "hash": -4748747267612478000, "line_mean": 33.1888111888, "line_max": 92, "alpha_frac": 0.6109633872, "autogenerated": false, "ratio": 3.961912479740681, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.507287586694068, "avg_score": null, "num_lines": null }
# A file to keep all sorts of unrelated utilities # Mostly used in tests. import pytest eng_freqs = {'E': 12.70, 'T': 9.06, 'A': 8.17, 'O': 7.51, 'I': 6.97, 'N': 6.75, 'S': 6.33, 'H': 6.09, 'R': 5.99, 'D': 4.25, 'L': 4.03, 'C': 2.78, 'U': 2.76, 'M': 2.41, 'W': 2.36, 'F': 2.23, 'G': 2.02, 'Y': 1.97, 'P': 1.93, 'B': 1.29, 'V': 0.98, 'K': 0.77, 'J': 0.15, 'X': 0.15, 'Q': 0.10, 'Z': 0.07, ' ': 2} def shortest_repeater(s: str) -> str: # Taken from Stack Overflow, by Buge # https://stackoverflow.com/questions/6021274/finding-shortest-repeating-cycle-in-word/33864413#33864413 if not s: return s nxt = [0] * len(s) for i in range(1, len(nxt)): k = nxt[i - 1] while True: if s[i] == s[k]: nxt[i] = k + 1 break elif k == 0: nxt[i] = 0 break else: k = nxt[k - 1] small_piece_len = len(s) - nxt[-1] if len(s) % small_piece_len != 0: return s return s[0:small_piece_len]
{ "repo_name": "avyfain/Cryptopals-Hypothesis", "path": "cryptopals/util.py", "copies": "1", "size": "1126", "license": "mit", "hash": -5039092332873155000, "line_mean": 32.1176470588, "line_max": 108, "alpha_frac": 0.4351687389, "autogenerated": false, "ratio": 2.6186046511627907, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3553773390062791, "avg_score": null, "num_lines": null }
"""A file to make sure we are setting the mean and variance for PyMC Lognormal variables correctly--since we are used to describing them with the mean and variance in log base 10.""" from pymc import deterministic, stochastic, MvNormal, Normal, Lognormal, Uniform from pymc import MCMC, Model import numpy as np from pylab import * # The mu and tau are in log units; to get to log units, # do the following # (has mean around 1e2, with a variance of 9 logs in base 10) mean_b10 = 2 var_b10 = 9 print "Setting mean (base 10) to %f, variance (base 10) to %f" % (mean_b10, var_b10) # The lognormal variable k = Lognormal('k', mu=np.log(10 ** mean_b10), tau=1./(np.log(10) * np.log(10 ** var_b10))) # Sample it m = MCMC(Model([k])) m.sample(iter=50000) ion() # Plot the distribution in base e figure() y = log(m.trace('k')[:]) y10 = log10(m.trace('k')[:]) hist(y, bins=100) print print "Mean, base e: %f; Variance, base e: %f" % (mean(y), var(y)) # Plot the distribution in base 10 figure() hist(y10, bins=100) print "Mean, base 10: %f; Variance, base 10: %f" % (mean(y10), var(y10))
{ "repo_name": "jmuhlich/bayessb", "path": "examples/pymc/lognormal_test.py", "copies": "1", "size": "1107", "license": "bsd-2-clause", "hash": -2713394771060931000, "line_mean": 27.3846153846, "line_max": 84, "alpha_frac": 0.6702800361, "autogenerated": false, "ratio": 2.816793893129771, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8853774520909938, "avg_score": 0.02665988166396663, "num_lines": 39 }
"""A file to move a UR robot with a grid and save correspondences between camera and robot pose for future processing. todo: generalize this to other robot types """ # The MIT License (MIT) # # Copyright (c) 2016 GTRC. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import argparse import datetime import os import robot2cam_calibration.track_grid as ci import ur_cb2.cb2_robot as cb2_robot import json import time import numpy as np def main(): """ Exposes :py:func:`get_correspondences` to the commandline. Run with arg `-h` for more info. """ # Parse in arguments parser = argparse.ArgumentParser( description="Get correspondences between camera and UR Robot", epilog="Gets correspondences between a camera and UR Robot with a " "grid attached. Relies on pre-trained points to direct " "robot motion. Will try to find the grid 5 times per " "position. Generates a json file with all of the data " "needed to then calculate the tool offset and the camera " "to robot transformation.") parser.add_argument("--samples", type=str, help='The filename for the file containing the list of' 'points which the robot should move through. This' 'file can be generated using the `cb2-record`' 'command from the ur_cb2 package.', required=True) parser.add_argument("-s", "--spacing", type=float, help="The grid spacing in mm.", required=True) parser.add_argument("-c", "--columns", type=int, help="the number of inner corners horizontally", required=True) parser.add_argument("-r", "--rows", type=int, help="the number of inner corners vertically", required=True) parser.add_argument("--calibration", type=str, help="The filename of the camera calibration " "information. This file can be generated using " "the`calibrate-camera` command from the " "camera-calibration toolbox.", required=True) parser.add_argument("--camera", type=str, help="The name of the camera to be used." "Valid options are:" "- `flycap`", default="flycap") parser.add_argument("--address", type=str, help="The address of the robot in form: `###.###.###`", required=True) parser.add_argument("--port", type=int, help="The port of the robot", default=30003) parser.add_argument("--out", type=str, help="File to save output to", default="correspondences.json") args = parser.parse_args() get_correspondences( robot_samples=args.samples, calibration=args.calibration, rows=args.rows, cols=args.columns, spacing=args.spacing, camera=args.camera, robot_address=args.address, robot_port=args.port, file_out=args.out ) def get_correspondences(robot_samples, calibration, rows, cols, spacing, camera, robot_address, robot_port, file_out): """ Gets correspondences between a camera and UR Robot with a grid attached. Relies on pre-trained points to direct robot motion. Will try to find the grid 5 times per position. Generates a json file with all of the data needed o then calculate the tool offset and the camera to robot transformation. Args: robot_samples (str): The filename for the file containing the list of points which the robot should move through. This file can be generated using the `cb2-record` command from the ur_cb2 package. calibration (str): The filename of the camera calibration information. This file can be generated using the `calibrate-camera` command from the camera-calibration toolbox. rows (int): The number of rows on the grid which is attached to the robot cols (int): The number of columns on the grid which is attached to the robot spacing (float): The spacing in mm between grid corners on the grid which is attached to the robot camera (str): The name of the camera to be used. Valid options are: - `flycap` robot_address (str): The address of the robot in form: `###.###.###` robot_port (int): The port of the robot file_out (str): The file in which to save all of the generated data. """ with open(robot_samples, 'r') as f: data = json.load(f) write_time = data['time'] points = data['points'] print('read in {} points, written at: {}'.format(len(points.keys()), write_time)) camera2grid = [] tcp2robot = [] with ci.GridLocation(calibration, rows, cols, spacing, camera) as calib: with cb2_robot.URRobot(robot_address, robot_port) as robot: for number in sorted([int(x) for x in points.keys()]): robot.add_goal(cb2_robot.Goal(points[str(number)]['joint'], False, 'joint')) # TODO: this appears to skip the first point! robot.move_on_stop() print('Beginning move: {}'.format(number)) while not (robot.at_goal() and robot.is_stopped()): time.sleep(.25) time.sleep(.25) # let everything settle print("reached goal") go_on = 0 while go_on <= 5: try: camera2grid.append(calib.get_cam2grid()) calib.show_images() with robot.receiver.lock: tcp2robot.append(robot.receiver.position) print("got the grid") go_on = 6 except RuntimeError as e: print("something went wrong: {}".format(e)) go_on += 1 tcp2robot = np.array(tcp2robot) tcp2robot[:, 0:3] = tcp2robot[:, 0:3] * 1000 tcp2robot = tcp2robot.tolist() print(np.asarray(tcp2robot)) # Axis-Angle [x,y,z,ax,ay,az] print(np.asarray(camera2grid)) json_dict = {"grid": {"rows": rows, "cols": cols, "spacing": spacing}, "time": str(datetime.datetime.now()), "calibration": calibration, "tcp2robot": tcp2robot, "camera2grid": camera2grid} with open(os.path.splitext(file_out)[0] + '.json', 'w') as \ result_json_file: json.dump(json_dict, result_json_file, indent=4) if __name__ == '__main__': main()
{ "repo_name": "mjsobrep/robot2camera-calibration", "path": "robot2cam_calibration/get_correspondences.py", "copies": "1", "size": "8369", "license": "mit", "hash": -8641338658890129000, "line_mean": 41.6989795918, "line_max": 79, "alpha_frac": 0.565539491, "autogenerated": false, "ratio": 4.588267543859649, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5653807034859649, "avg_score": null, "num_lines": null }
"""A file to move a UR robot with a grid and save images and robot pose for future processing. todo: generalize this to any robot type """ # The MIT License (MIT) # # Copyright (c) 2016 GTRC. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import argparse import datetime import os import robot2cam_calibration.track_grid as ci import ur_cb2.cb2_robot as cb2_robot import json import time import numpy as np import camera import cv2 def main(): """ Exposes :py:func:`get_images_poses` to the commandline. Run with arg `-h` for more info. """ # Parse in arguments parser = argparse.ArgumentParser( description="Get images from camera and poses from UR Robot") parser.add_argument("--samples", type=str, help='The filename for the file containing the list of' 'points which the robot should move through. This' 'file can be generated using the `cb2-record`' 'command from the ur_cb2 package.', required=True) parser.add_argument("--camera", type=str, help="The name of the camera to be used." "Valid options are:" "- `flycap`", default="flycap") parser.add_argument("--address", type=str, help="The address of the robot in form: `###.###.###`", required=True) parser.add_argument("--port", type=int, help="The port of the robot", default=30003) parser.add_argument("--out_folder", type=str, help="Folder to save output to", default="result") parser.add_argument("--out_file", type=str, help="File to save output to", default="correspondences.json") args = parser.parse_args() get_images_poses( robot_samples=args.samples, cam_name=args.camera, robot_address=args.address, robot_port=args.port, folder_out=args.out_folder, file_out=args.out_file ) def get_images_poses(robot_samples, cam_name, robot_address, robot_port, folder_out, file_out): """ Gets images from a cam_name and and poses of a UR Robot. Relies on pre-trained points to direct robot motion. Generates a json file with the pose of the robot and filename of the corresponding image. Args: robot_samples (str): The filename for the file containing the list of points which the robot should move through. This file can be generated using the `cb2-record` command from the ur_cb2 package. cam_name (str): The name of the cam_name to be used. Valid options are: - `flycap` robot_address (str): The address of the robot in form: `###.###.###` robot_port (int): The port of the robot folder_out (str): The folder in which to save the data. file_out (str): The file in which to save all of the generated data. """ with open(robot_samples, 'r') as f: data = json.load(f) write_time = data['time'] points = data['points'] print('read in {} points, written at: {}'.format(len(points.keys()), write_time)) tcp2robot = [] im_num = 0 if not os.path.isdir(folder_out): os.mkdir(folder_out) with cb2_robot.URRobot(robot_address, robot_port) as robot: with camera.Camera(cam_name) as cam: for number in sorted([int(x) for x in points.keys()]): robot.add_goal(cb2_robot.Goal(points[str(number)]['joint'], False, 'joint')) # TODO: this appears to skip the first point! robot.move_on_stop() print('Beginning move: {}'.format(number)) while not (robot.at_goal() and robot.is_stopped()): time.sleep(.25) time.sleep(.25) # let everything settle with robot.receiver.lock: tcp2robot.append(robot.receiver.position) cv2.imwrite(os.path.join(folder_out, str(im_num) + '.png'), cam.capture_raw()) im_num += 1 print(np.asarray(tcp2robot)) # `[x,y,z,<rotation vector>]` where `<rotation vector>` is a three element # vector representing the an axis about which to rotate (`<x,y,z>`) in # radians equal to the magnitude of the vector. json_dict = {"time": str(datetime.datetime.now()), "tcp2robot": tcp2robot} with open( os.path.join(folder_out, os.path.splitext(file_out)[0] + '.json'), 'w') as \ result_json_file: json.dump(json_dict, result_json_file, indent=4) if __name__ == '__main__': main()
{ "repo_name": "mjsobrep/robot2camera-calibration", "path": "robot2cam_calibration/get_images.py", "copies": "1", "size": "6115", "license": "mit", "hash": 2641645598453308000, "line_mean": 37.7025316456, "line_max": 79, "alpha_frac": 0.5839738348, "autogenerated": false, "ratio": 4.240638002773925, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5324611837573925, "avg_score": null, "num_lines": null }
# A file to open Hearthstone cards from the command line, then export them in a file format readable to the neural network # Andrew Thomas 3/31/2017 import json def main(filename : str, ratingsFilename: str) -> None: with open(filename) as fp: cards = json.load(fp) with open(ratingsFilename) as fp: scores = json.load(fp)['Cards'] scores = list(map(lambda card: card['Name'].lower(), scores)) cards_sorted = sorted(cards, key=lambda card: card['name'].lower()) longest = 0 with open(filename + '_formatted_rnn.txt', 'w') as fp_2: with open(filename + '_formatted.txt', 'w') as fp: for card in cards: name = card.get('name', '') attack = card.get('attack', '') cardClass = card.get('cardClass', '') cost = card.get('cost', '') health = card.get('health', '') text = card.get('text', '').replace('\n', ' ').replace('<b>', '').replace('</b>', '').replace('<i>', '').replace('</i>', '').replace('[x]', '') cardType = card.get('type', '') rarity = card.get('rarity', '') tribe = card.get('race', '') # 0 - name # 1 - tribe # 2 - rarity # 3 - cardClass # 4 - cardType # 5 - cost # 6 - attack # 7 - health # 8 - text entry = '|0{0}|1{1}|2{2}|3{3}|4{4}|5{5}|6{6}|7{7}|8{8}'.format( name, tribe, rarity, cardClass, cardType, cost, attack, health, text) fp_2.write(entry + '\n') if card['name'].lower() in scores: if len(entry) > longest: longest = len(entry) longest_entry = entry entry = (entry + (' ' * 160))[:160] + '\n' fp.write(entry) print('Longest entry: {}\n{}'.format(longest, longest_entry)) if __name__=='__main__': import sys sys.exit(main(sys.argv[1], sys.argv[2]))
{ "repo_name": "chattahippie/Hearthstone-Card-Generator-AI-", "path": "hearthstoneJSONParser.py", "copies": "1", "size": "2379", "license": "apache-2.0", "hash": 3585379094609238000, "line_mean": 31.1621621622, "line_max": 159, "alpha_frac": 0.4153005464, "autogenerated": false, "ratio": 4.271095152603231, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5186395699003231, "avg_score": null, "num_lines": null }
# a file to simply implement some key algorithms in a procedural fashion from collections import namedtuple import logging import math class SolutionContext: def __init__(self , board=None , alpha=None , beta=None , depth=None , timeout=None , previous_move=None , fn_fitness=None , fn_terminate=None): self.beta = beta self.alpha = alpha self.previous_move = previous_move self.board = board self.depth = depth self.timeout = timeout self.fn_fitness = fn_fitness self.fn_terminate = fn_terminate class Solution: def __init__(self , move=None , board=None , is_max=None): self.board = board self.is_max = is_max self.move = move MinMove = namedtuple('MinMove', ['is_max', 'x', 'y', 'tile', 'prob']) MaxMove = namedtuple('MaxMove', ['is_max', 'direction']) def minimax(context: SolutionContext, solution: Solution): log = logging.getLogger('PlayerAI') log.info("minimax") if context.fn_terminate(context, solution): return context.fn_fitness(context, solution) moves = solution.board.get_moves(not solution.is_max) if solution.is_max: results = [] for m in moves: new_context, new_solution = create_call_vars(m, context, solution) results.append(minimax(context=new_context, solution=new_solution)) return max(results) else: results = [] for m in moves: new_context, new_solution = create_call_vars(m, context, solution) r = minimax(context=new_context, solution=new_solution) r2 = r * new_solution.move.prob results.append(r2) return min(results) def minimax_with_ab_pruning(context: SolutionContext, solution: Solution): log = logging.getLogger('PlayerAI') if context.fn_terminate(context, solution): return context.fn_fitness(context, solution) moves = solution.board.get_moves(solution.is_max) if solution.is_max: best_result = -float("inf") for m in moves: new_context, new_solution = create_call_vars(m, context, solution) result = minimax_with_ab_pruning(context=new_context, solution=new_solution) best_result = max(result, best_result) context.alpha = max(best_result, context.alpha) if context.alpha <= context.beta: log.debug("alpha cut") break return best_result else: # PROBLEM: # - MIN is not playing to minimise the eventual score of MAX, it is generating tiles at random # The result from MIN should be the average score achieved given the move by MAX. # So, how is beta calculated to allow the alpha-beta pruning algorithm to be implemented? # KNOWN: # - MIN should return the average across all possible moves # - MAX can maximise the alpha based on that # - MIN will be called on across several possible moves by MAX # IDEA: # - Just set beta to the average? # best_result = float("inf") for m in moves: new_context, new_solution = create_call_vars(m, context, solution) result = minimax_with_ab_pruning(context=new_context, solution=new_solution) best_result = min(result, best_result) context.beta = min(best_result, context.beta) if context.alpha <= context.beta: log.debug("beta cut") break return best_result # acc = 0.0 # for m in moves: # new_context, new_solution = create_call_vars(m, context, solution) # r = minimax_with_ab_pruning(context=new_context, solution=new_solution) # acc += r * new_solution.move.prob # avg_score = acc / (len(moves) / 2) # context.beta = min(context.beta, avg_score) # return avg_score def create_call_vars(move, context, solution): new_context = SolutionContext(board=solution.board, depth=context.depth + 1, timeout=context.timeout, previous_move=move, fn_fitness=context.fn_fitness, fn_terminate=context.fn_terminate) new_solution = Solution(move=move, board=new_context.board.move(move), is_max=not solution.is_max) return new_context, new_solution def prairie_fire(g): def set_fire_to(B, x, y, t, code): # if off edge if x < 0 or x > 3 or y < 0 or y > 3: return False # if done already if B[x, y] == code: return False # if no match if B[x, y] != t: return False B[x, y] = code set_fire_to(B, x - 1, y, t, code) set_fire_to(B, x + 1, y, t, code) set_fire_to(B, x, y - 1, t, code) set_fire_to(B, x, y + 1, t, code) return True B = g.clone() result = dict() tiles = [2 ** l if l > 0 else 0 for l in range(0, 17)] for t in tiles: result[t] = [] for t in tiles: code = -1 for x in range(0, 4): for y in range(0, 4): lit = set_fire_to(B, x, y, t, code) if lit: code -= 1 # now gather the stats for c in range(-1, code - 1, -1): stats = {'count': 0, 'minx':1000, 'maxx': -1, 'miny':5, 'maxy': -1, 'adjacent_tiles': []} for x in range(0, 4): for y in range(0, 4): if B[x,y] == c: stats['count'] += 1 stats['minx'] = min(stats['minx'], x) stats['maxx'] = max(stats['maxx'], x) stats['miny'] = min(stats['miny'], y) stats['maxy'] = max(stats['maxy'], y) B[x,y] = 0 if stats['count'] > 0: result[t].append(stats) return result def sigmoid(x): return 1 / (1 + math.exp(-x))
{ "repo_name": "aabs/edx-ai-week4-project", "path": "algorithms.py", "copies": "1", "size": "6391", "license": "apache-2.0", "hash": -8384928497102931000, "line_mean": 34.5111111111, "line_max": 103, "alpha_frac": 0.5251134408, "autogenerated": false, "ratio": 3.8592995169082127, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9864149779766211, "avg_score": 0.004052635588400273, "num_lines": 180 }
"""A file to visually check the result of camera coordinate to robot base transformation """ # The MIT License (MIT) # # Copyright (c) 2016 GTRC. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import cv2 import os import numpy as np import json import track_grid import re import compute_transformations import argparse def main(): """ Exposes :py:func:`check_transformation` to the commandline. Run with arg `-h` for more info. """ # Parse in arguments parser = argparse.ArgumentParser( description="Visualize computed transformations") parser.add_argument("--r2c_calibration", type=str, help='JSON file generated by compute_transformations', default='transformation.json') parser.add_argument("--robot_data", type=str, help="The filename of the robot poses in the images. " "This file should be a json file with fields: " "'time', 'tcp2robot', 'camera2grid'. 'tcp2robot' " "and 'camera2grid' should be lists of lists, with " "each individual list being a Rodrigues vector " "(x,y,z,3 element rotation vector/axis-angle). " "Linear distance must be consistent with each " "other and the camera intrinsic and distortion " "data (mm are recommended). Angular distances " "must be in radians.", default='correspondences.json') parser.add_argument("--image_folder", type=str, help="The name of the folder to read images from", default='input_images') parser.add_argument("--result_folder", type=str, help="The name of the folder to save the output " "images in", default='output_images') parser.add_argument("--cam_calibration", type=str, help="The JSON file holding the camera calibration " "data as generated by: " "https://pypi.python.org/pypi/camera_calibration/", default='calibration.json') args = parser.parse_args() check_transformation( r2c_calibration=args.r2c_calibration, robot_data=args.robot_data, image_folder=args.image_folder, result_folder=args.result_folder, cam_calibration=args.cam_calibration ) def check_transformation(r2c_calibration, robot_data, image_folder, result_folder, cam_calibration): """Plots transformed 3D world points onto camera image Args: r2c_calibration (str): JSON file generated by compute_transformations robot_data (str): The filename of the robot poses in the images. This file should be a json file with fields: 'time', 'tcp2robot', 'camera2grid'. 'tcp2robot' and 'camera2grid' should be lists of lists, with each individual list being a Rodrigues vector (x,y,z,3 element rotation vector/axis-angle). Linear distance must be consistent with each other and the camera intrinsic and distortion data (mm are recommended). Angular distances must be in radians. image_folder (str): The name of the folder to read images from result_folder (str): The name of the folder to save the output images in cam_calibration (str): The JSON file holding the camera calibration data as generated by: https://pypi.python.org/pypi/camera_calibration/ """ if len(result_folder) and (result_folder[0] == '/' or result_folder[0] == '\\'): result_folder = result_folder[1:] if len(result_folder) and (result_folder[-1] == '/' or result_folder[-1] == '\\'): result_folder = result_folder[:-1] if len(image_folder) and (image_folder[0] == '/' or image_folder[0] == '\\'): image_folder = image_folder[1:] if len(image_folder) and (image_folder[-1] == '/' or image_folder[-1] == '\\'): image_folder = image_folder[:-1] with open(cam_calibration, 'r') as open_file: calib_dict = json.load(open_file) intrinsic = np.array(calib_dict['intrinsic']) distortion = np.array(calib_dict['distortion']) print("Loaded camera calibration data from {}".format( calib_dict['time'])) with open(robot_data, 'r') as open_file: robot_dict = json.load(open_file) # nx6 arrays x,y,z,axis-angle: tcp2robot = robot_dict['tcp2robot'] camera2target = robot_dict['camera2grid'] print("Loaded calibration data from {}".format( robot_dict['time'])) with open(r2c_calibration, 'r') as open_file: r2c_dict = json.load(open_file) # nx6 arrays x,y,z,axis-angle: tcp2target = r2c_dict['tcp2target']['Tmatrix'] cam2rob = r2c_dict['cam2robot']['Tmatrix'] print("Loaded calibration results from {}".format(r2c_dict['time'])) target_directory = os.path.join(os.getcwd(), image_folder) directory_out = os.path.join(os.getcwd(), result_folder) file_names = os.listdir(target_directory) if not os.path.exists(directory_out): os.makedirs(directory_out) axis_length = 250 axis = np.float32([[0, 0, 0], [axis_length, 0, 0], [0, axis_length, 0], [0, 0, axis_length]]).reshape(-1, 3) number_found = 0 for image_file in sort_nicely(file_names): image_file = os.path.join(target_directory, image_file) # Try to read in image as gray scale img = cv2.imread(image_file, 0) # If the image_file isn't an image, move on if img is not None: img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) labels = ['base_est', 'tcp_est', 'target_est', 'target_measured'] tcp_est = np.matmul(cam2rob, compute_transformations.vector2mat( tcp2robot[number_found])) target_est = np.matmul(tcp_est, tcp2target) coordinates = np.array([cam2rob, tcp_est, target_est, compute_transformations.vector2mat(camera2target[number_found])]) for j in range(coordinates.shape[0]): cam2target = np.array(coordinates[j]) rvec, jac = cv2.Rodrigues(cam2target[0:3,0:3]) image_points, jac = cv2.projectPoints(axis, rvec, cam2target[0:3, 3], intrinsic, distortion) img = track_grid.draw_axes(image_raw=img, corners=image_points[0], image_points=image_points[1:], label=labels[j]) cv2.imwrite( os.path.join( result_folder, "result" + str(number_found) + ".jpg"), img) print("finished processing Image {}".format(image_file)) number_found += 1 print("Done processing all images") # http://stackoverflow.com/questions/4623446/how-do-you-sort-files-numerically def tryint(s): try: return int(s) except: return s def alphanum_key(s): """ Turn a string into a list of string and number chunks. "z23a" -> ["z", 23, "a"] """ return [tryint(c) for c in re.split('([0-9]+)', s)] def sort_nicely(l): """ Sort the given list in the way that humans expect. """ return sorted(l, key=alphanum_key) if __name__ == "__main__": main()
{ "repo_name": "mjsobrep/robot2camera-calibration", "path": "robot2cam_calibration/check_transformation.py", "copies": "1", "size": "9237", "license": "mit", "hash": 886587872964038000, "line_mean": 41.9674418605, "line_max": 131, "alpha_frac": 0.5653350655, "autogenerated": false, "ratio": 4.270457697642164, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5335792763142164, "avg_score": null, "num_lines": null }
"""A file to wrap up various cameras into a common class. Currently this houses: - Flycapture2 TODO: Add some more: - webcam - folder of images """ # The MIT License (MIT) # # Copyright (c) 2016 GTRC. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import threading import numpy as np import cv2 class Camera(object): """Wraps various camera and image capture technologies. Supported Cameras: - Flycapture2 devices : `flycap`, `flycap2`, `flycapture`, `flycapture2` Attributes: intrinsic: A numpy array of the camera intrinsic matrix distortion: A numpy array of the camera distortion parameters cam: A camera or other image acquisition device, which this class wraps. """ def __init__(self, name, intrinsic=None, distortion=None): """Sets up camera acquisition and reads calibration data. Args: name (str): Name of the camera to use intrinsic (numpy.ndarray): The camera intrinsic matrix distortion (numpy.ndarray): The camera distortion parameters Raises: NotImplementedError: The camera type selected is not yet implemented Value Error: The value entered for the camera is not valid. """ if name.lower() in ('flycap', 'flycap2', 'flycapture', 'flycapture2'): self.cam = FlyCap2() elif name.lower() in ('wc', 'webcam'): raise NotImplementedError elif name.lower() in ('file', 'files', 'folder', 'pictures', 'picture', 'image', 'images'): raise NotImplementedError else: raise ValueError('unknown camera type') self.intrinsic = intrinsic self.distortion = distortion def capture_image(self): """Capture an and rectify an image. Returns: The newly captured image, rectified, as a numpy array. Raises: RuntimeError: It was not possible to capture and rectify an image """ raw_image = self.cam.capture_image() if self.intrinsic is not None and self.distortion is not None: rectified_image = cv2.undistort(raw_image, self.intrinsic, self.distortion) else: rectified_image = raw_image if rectified_image is None: raise RuntimeError("Unable to capture and rectify image") return rectified_image def capture_raw(self): """ Return the raw (still distorted) image. Returns: The most recent raw image as a numpy array """ return self.cam.capture_image() def __del__(self): self.cam.__del__() def __enter__(self): """Enters the camera from a with statement""" return self def __exit__(self, *_): """Exits at the end of a context manager statement by destructing.""" self.__del__() class FlyCap2(object): """A wrapper to capture images from a flycapture2 camera Attributes: context: flycapture2.Context of the camera context fc2_image: flycapture2.Image which represents the image buffer of the camera images """ def __init__(self): """Setup the communications with the flycapture2 device.""" import flycapture2 as fc2 # FlyCapture Info printing and setup: print "\n\nlibrary version: {}\n".format(fc2.get_library_version()) self.context = fc2.Context() print "Number of Cameras: {}\n".format( self.context.get_num_of_cameras()) self.context.connect(*self.context.get_camera_from_index(0)) print "Camera Info: {}\n".format(self.context.get_camera_info()) m, f = self.context.get_video_mode_and_frame_rate() print "Video Mode: {}\nFrame Rate:{}\n".format(m, f) print "Frame Rate Property Info: {}\n".format( self.context.get_property_info(fc2.FRAME_RATE)) p = self.context.get_property(fc2.FRAME_RATE) print "Frame Rate Property: {}\n".format(p) self.context.set_property(**p) self.context.start_capture() self.fc2_image = fc2.Image() print "done with flycap2 setup" self.cam_on = True self.image = None cv2.namedWindow('raw', cv2.WINDOW_NORMAL) cv2.waitKey(5) self.__acquisition_thread = None self.lock = threading.Lock() self.run = True self.__acquisition_thread = threading.Thread(group=None, target=self.acquire, name='acquisition_thread', args=(), kwargs={}) self.__acquisition_thread.start() def __del__(self): """Shutdown the communications with the flycapture2 device.""" self.stop() if self.cam_on: print("flycap cam already disconnected") else: self.context.stop_capture() self.context.disconnect() cv2.destroyWindow('raw') def capture_image(self): """Return the latest image from the camera Returns: np.array of the latest image from the camera. """ with self.lock: return np.copy(self.image) def stop(self): if self.__acquisition_thread is not None: if self.__acquisition_thread.is_alive(): print("shutting down acquisition thread") self.run = False self.__acquisition_thread.join() if self.__acquisition_thread.is_alive(): print('failed to shutdown auxiliary thread') else: print('shutdown auxiliary thread') else: print('auxiliary thread already shutdown') else: print('no auxiliary threads exist') def acquire(self): while self.run: with self.lock: self.image = np.array(self.context.retrieve_buffer(self.fc2_image)) cv2.imshow('raw', self.image) cv2.waitKey(5)
{ "repo_name": "mjsobrep/robot2camera-calibration", "path": "robot2cam_calibration/camera.py", "copies": "1", "size": "7218", "license": "mit", "hash": 8368559120765263000, "line_mean": 35.4545454545, "line_max": 83, "alpha_frac": 0.6041839845, "autogenerated": false, "ratio": 4.374545454545455, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5478729439045454, "avg_score": null, "num_lines": null }
"""A filled polygon component""" # Major package imports. from numpy import array # Enthought library imports. from kiva.constants import EOF_FILL_STROKE, FILL, FILL_STROKE from kiva.agg import points_in_polygon from traits.api import Any, Event, Float, HasTraits, Instance, List, \ Property, Trait, Tuple from traitsui.api import Group, View # Local imports. from enable.api import border_size_trait, Component from enable.colors import ColorTrait class PolygonModel(HasTraits): """ The data model for a Polygon. """ # The points that make up the vertices of this polygon. points = List(Tuple) def reset(self): self.points = [] return class Polygon(Component): """ A filled polygon component. """ #-------------------------------------------------------------------------- # Trait definitions. #-------------------------------------------------------------------------- # The background color of this polygon. background_color = ColorTrait("white") # The color of the border of this polygon. border_color = ColorTrait("black") # The dash pattern to use for this polygon. border_dash = Any # The thickness of the border of this polygon. border_size = Trait(1, border_size_trait) # Event fired when the polygon is "complete". complete = Event # The rule to use to determine the inside of the polygon. inside_rule = Trait('winding', {'winding':FILL_STROKE, 'oddeven':EOF_FILL_STROKE }) # The points that make up this polygon. model = Instance(PolygonModel, ()) # Convenience property to access the model's points. points = Property # The color of each vertex. vertex_color = ColorTrait("black") # The size of each vertex. vertex_size = Float(3.0) traits_view = View(Group('<component>', id = 'component'), Group('<links>', id = 'links'), Group('background_color', '_', 'border_color', '_', 'border_size', id = 'Box', style = 'custom')) colorchip_map = {'color': 'color', 'alt_color': 'border_color'} #-------------------------------------------------------------------------- # Traits property accessors #-------------------------------------------------------------------------- def _get_points(self): return self.model.points #-------------------------------------------------------------------------- # 'Polygon' interface #-------------------------------------------------------------------------- def reset(self): "Reset the polygon to the initial state" self.model.reset() self.event_state = 'normal' return #-------------------------------------------------------------------------- # 'Component' interface #-------------------------------------------------------------------------- def _draw_mainlayer(self, gc, view_bounds=None, mode="normal"): "Draw the component in the specified graphics context" self._draw_closed(gc) return #-------------------------------------------------------------------------- # Protected interface #-------------------------------------------------------------------------- def _is_in(self, point): """ Test if the point (an x, y tuple) is within this polygonal region. To perform the test, we use the winding number inclusion algorithm, referenced in the comp.graphics.algorithms FAQ (http://www.faqs.org/faqs/graphics/algorithms-faq/) and described in detail here: http://softsurfer.com/Archive/algorithm_0103/algorithm_0103.htm """ point_array = array((point,)) vertices = array(self.model.points) winding = self.inside_rule == 'winding' result = points_in_polygon(point_array, vertices, winding) return result[0] #-------------------------------------------------------------------------- # Private interface #-------------------------------------------------------------------------- def _draw_closed(self, gc): "Draw this polygon as a closed polygon" if len(self.model.points) > 2: # Set the drawing parameters. gc.set_fill_color(self.background_color_) gc.set_stroke_color(self.border_color_) gc.set_line_width(self.border_size) gc.set_line_dash(self.border_dash) # Draw the path. gc.begin_path() gc.move_to(self.model.points[0][0] - self.x, self.model.points[0][1] + self.y) offset_points = [(x - self.x, y + self.y) for x, y in self.model.points] gc.lines(offset_points) gc.close_path() gc.draw_path(self.inside_rule_) # Draw the vertices. self._draw_vertices(gc) return def _draw_open ( self, gc ): "Draw this polygon as an open polygon" if len(self.model.points) > 2: # Set the drawing parameters. gc.set_fill_color( self.background_color_ ) gc.set_stroke_color( self.border_color_ ) gc.set_line_width( self.border_size ) gc.set_line_dash( self.border_dash ) # Draw the path. gc.begin_path() gc.move_to(self.model.points[0][0] - self.x, self.model.points[0][1] + self.y) offset_points = [(x - self.x, y + self.y) for x, y in self.model.points ] gc.lines(offset_points) gc.draw_path(self.inside_rule_) # Draw the vertices. self._draw_vertices(gc) return def _draw_vertices(self, gc): "Draw the vertices of the polygon." gc.set_fill_color(self.vertex_color_) gc.set_line_dash(None) offset = self.vertex_size / 2.0 offset_points = [(x + self.x, y + self.y) for x, y in self.model.points] if hasattr(gc, 'draw_path_at_points'): path = gc.get_empty_path() path.rect(-offset, -offset, self.vertex_size, self.vertex_size) gc.draw_path_at_points(offset_points, path, FILL_STROKE) else: for x, y in offset_points: gc.draw_rect((x - offset, y - offset, self.vertex_size, self.vertex_size), FILL) return # EOF
{ "repo_name": "tommy-u/enable", "path": "enable/primitives/polygon.py", "copies": "1", "size": "6625", "license": "bsd-3-clause", "hash": -7750892051255394000, "line_mean": 32.4595959596, "line_max": 85, "alpha_frac": 0.4892075472, "autogenerated": false, "ratio": 4.452284946236559, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.003107325331751343, "num_lines": 198 }
"""A filter for turning json into viewable HTML.""" import json import cgi import rowan.http as http import base class JSONViewer(base.Wrapper): """ This wrapper is designed to wrap any controller that is likely to generate JSON results. If the controller returns JSON in a 200 HTTP response code, then it will render the result into HTML and return a HTML response. Any other response passes through untouched. """ def __call__(self, request): response = self.controller(request) if (response.status_code != 200 or response.content_type != "application/json"): return response # Parse the json json_data = json.loads(response.content) # Create the HTML response response = http.HttpResponse(content_type = "text/html") response.write(before) self._output(response, json_data) response.write(after) return response def _output(self, response, data): if isinstance(data, list): self._output_array(response, data) elif isinstance(data, dict): self._output_object(response, data) elif data in (True, False): self._output_boolean(response, data) elif isinstance(data, basestring): self._output_string(response, data) else: self._output_number(response, data) def _output_boolean(self, response, boolean): response.write("<div class='boolean'>%s</div>" % str(boolean).lower()) def _output_string(self, response, literal): response.write( "<div class='string'>\"%s\"</div>" % cgi.escape(literal) ) def _output_number(self, response, literal): response.write("<div class='number'>%s</div>" % str(literal)) def _output_object(self, response, obj): response.write("<div class='object'>") count = len(obj) if count: response.write("<table>") for key, value in sorted(obj.items()): response.write("<tr><th>%s:</th><td>" % cgi.escape(key)) self._output(response, value) response.write("</td></tr>") response.write("</table>") else: response.write("{}") response.write("</div>") def _output_array(self, response, seq): response.write("<div class='array'>") count = len(seq) if count: response.write("<table>") for i, item in enumerate(seq): response.write("<tr><th>%d</th><td>" % i) self._output(response, item) response.write("</td></tr>") response.write("</table>") else: response.write("[]") response.write("</div>") class OptionalJSONViewer(JSONViewer): """ This wrapper is a JSONViewer only when 'format=html' is passed into the request. """ def __call__(self, request): if request.query_params.get('format', None) == ['html']: return JSONViewer.__call__(self, request) else: return self.controller(request) before = """ <!DOCTYPE HTML><html><head><style> body { line-height: 16px; font-size: 14px; font-family: sans; } table { border: 1px solid black; background-color: white; } table tr { vertical-align: top; } .array table tr:nth-child(odd) { background-color: #dee; } .array table tr:nth-child(even) { background-color: #eff; } .object table tr:nth-child(odd) { background-color: #ede; } .object table tr:nth-child(even) { background-color: #fef; } .boolean { color: #600; } .string { color: #060; } .number { color: #009; } th { text-align: left; padding: 2px 10px 2px 2px; font-weight: normal; } td { padding: 2px; } p { margin: 0; padding: 0; font-style: italic; color: #999 } .array th { font-style: italic; color: #999 } </style></head><body><h1>JSON Result - Debug View</h1> """ after = """</body></html>"""
{ "repo_name": "cargocult/rowan-python", "path": "rowan/controllers/debug.py", "copies": "1", "size": "3968", "license": "mit", "hash": 7612079870172178000, "line_mean": 32.9145299145, "line_max": 78, "alpha_frac": 0.5912298387, "autogenerated": false, "ratio": 3.863680623174294, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9904376296212911, "avg_score": 0.010106833132276383, "num_lines": 117 }
"""A filter that can parse sphinx docs """ __author__ = 'jay' __version__ = (0, 0, 1, 'alpha', 0) catalog = ['read'] form = { "lang" : { "verbose": "Language", "require": False, "type": "select", "choices": [["python2", "Python 2"], ["python3", "Python 3"]], "value": "python2", }, "trigger_pattern": { "verbose": "Trigger Pattern", "require": False, "helper_text": "Sphinx will regenerate docs once trigger is matched." " Empty means regenerate docs every commit.", }, "docs_root": { "verbose": "Documentation Root", "helper_text": "Where the generated docs locate." }, "working_dir": { "verbose": "Working Directory", "require": False, "helper_text": "Path to working tree that build command run in.", }, "build_command": { "verbose": "Build Command", "require": False, "type": "textarea", "helper_text": "Command that builds docs. Empty means docs are" " already there", }, "ignore_errors": { "verbose": "Ignore Errors", "type": "checkbox", "value": False, }, } def on_install(db): pass def on_upgrade(db, pre): pass def on_uninstall(db): pass from main import Filter __all__ = ['Filter']
{ "repo_name": "BusyJay/sokoban", "path": "docs/examples/filters/f_sphinx/__init__.py", "copies": "1", "size": "1368", "license": "mit", "hash": -2291964355237257200, "line_mean": 22.186440678, "line_max": 77, "alpha_frac": 0.5197368421, "autogenerated": false, "ratio": 3.82122905027933, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9828254027972549, "avg_score": 0.002542372881355932, "num_lines": 59 }
"""A filter that parse documentation from confluence and enhance documentation to confluence. """ import contextlib __author__ = 'jay' __version__ = (0, 0, 1, 'alpha', 0) catalog = ['write'] from main import Filter __all__ = ['Filter'] form = None def on_install(db): """will be execute when installed. raise any exception to revert the installation. :param db: a database connection used for creating its tables if needed """ with contextlib.closing(db.cursor()) as c: c.execute("set sql_notes=0") c.execute("create table if not exists resources (" "id int(11) primary key auto_increment," "res_type varchar(10) not null," # should be 'page' or 'attachment' "path varchar(255) not null," # relative path of resources base on work root "project varchar(255) not null" ")") c.execute("create table if not exists pages (" "oid int(11) primary key," "parent_id int(11) default null," "resource_id int(11) not null references resources(id)," "title varchar(255) not null," "postfix varchar(256) default null," "version int(11) default 0," "create_time timestamp" ")") c.execute("create table if not exists attachments (" "oid int(11) primary key," "parent_id int(11) not null references pages(id) ON DELETE CASCADE," "resource_id int(11) not null references resources(id)," "resource_name varchar(256) not null," "create_time timestamp" # following key is removed because it's too large. # but should be checked during operation. # "unique key (parent_id, resource_name)" ")") c.execute("set sql_notes=1") def on_upgrade(db, pre): """will be execute when upgrade. raise any exception to revert the upgrade. :param db: :param pre: previous version code :return: """ on_install(db) def on_uninstall(db): """will be execute when uninstalled. no matter what happened, the plugin will be removed eventually. """ with contextlib.closing(db.cursor()) as c: c.execute("drop table attachments") c.execute("drop table pages") c.execute("drop table resources") def on_project_delete(db, project_id): with contextlib.closing(db.cursor()) as c: c.execute("delete from attachments " "join resources on attachments.resource_id=resources.id " "where resources.project=%s", project_id) c.execute("delete from pages " "join resources on pages.resource_id=resources.id " "where resources.project=%s", project_id) c.execute("delete from resources " "where resources.project=%s", project_id) db.commit()
{ "repo_name": "BusyJay/sokoban", "path": "docs/examples/filters/f_confluence/__init__.py", "copies": "1", "size": "3046", "license": "mit", "hash": 5197373344734815000, "line_mean": 33.6136363636, "line_max": 95, "alpha_frac": 0.573867367, "autogenerated": false, "ratio": 4.339031339031339, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5412898706031339, "avg_score": null, "num_lines": null }
"""A filter that uses "# pragma: no mutate" to determine when specific mutations should be skipped. """ import logging import re import sys from functools import lru_cache from cosmic_ray.tools.filters.filter_app import FilterApp from cosmic_ray.work_item import WorkerOutcome, WorkResult log = logging.getLogger() class PragmaNoMutateFilter(FilterApp): """Implements the pragma-no-mutate filter.""" def description(self): return __doc__ def filter(self, work_db, _args): """Mark lines with "# pragma: no mutate" as SKIPPED For all work_item in db, if the LAST line of the working zone is marked with "# pragma: no mutate", This work_item will be skipped. """ @lru_cache() def file_contents(file_path): "A simple cache of file contents." with file_path.open(mode="rt") as handle: return handle.readlines() re_is_mutate = re.compile(r".*#.*pragma:.*no mutate.*") for item in work_db.work_items: for mutation in item.mutations: print(mutation.module_path) lines = file_contents(mutation.module_path) try: # item.{start,end}_pos[0] seems to be 1-based. line_number = mutation.end_pos[0] - 1 if mutation.end_pos[1] == 0: # The working zone ends at begin of line, # consider the previous line. line_number -= 1 line = lines[line_number] if re_is_mutate.match(line): work_db.set_result( item.job_id, WorkResult(output=None, test_outcome=None, diff=None, worker_outcome=WorkerOutcome.SKIPPED), ) except Exception as ex: raise Exception( "module_path: %s, start_pos: %s, end_pos: %s, len(lines): %s" % (mutation.module_path, mutation.start_pos, mutation.end_pos, len(lines)) ) from ex def main(argv=None): """Run pragma-no-mutate filter with specified command line arguments.""" return PragmaNoMutateFilter().main(argv) if __name__ == "__main__": sys.exit(main())
{ "repo_name": "sixty-north/cosmic-ray", "path": "src/cosmic_ray/tools/filters/pragma_no_mutate.py", "copies": "1", "size": "2346", "license": "mit", "hash": 1794989627714020900, "line_mean": 34.5454545455, "line_max": 120, "alpha_frac": 0.5507246377, "autogenerated": false, "ratio": 4.137566137566138, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5188290775266138, "avg_score": null, "num_lines": null }
"""A first attempt to decode conditions from motion detrending coefs""" import numpy as np from more_datasets import fetch_abide_movements bunch = fetch_abide_movements() # Get diagnosis group 1: autist, 2: control # Transform to 1: autist, -1: control aut_target = 2 * (1.5 - bunch.pheno["DX_GROUP"]) # There seems to be a different number of frames depending on site # I am hoping at least TR is equal across sites. The way I implemented # the detrending coefs will cause bias which will make acquisition # length visible. So for the beginning I will crop everything to # the shortest acquisition length acquisition_lengths = [len(mov) for mov in bunch.movement] min_acquisition_length = np.min(acquisition_lengths) movement = [mov[:min_acquisition_length] for mov in bunch.movement] # Use this movement as the baseline features. Yes it is brutal # and shouldn't work features = np.array(movement).reshape(len(movement), -1) # Do a simple SVM on these features from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.cross_validation import cross_val_score, ShuffleSplit from sklearn.dummy import DummyClassifier svm = SVC(kernel="rbf", C=1.) logreg = LogisticRegression(C=1.) # Watch out with cross validation! # Our first approach will not stratify across sites # But this absolutely needs to be tested # We also have slightly unbalanced classes cv = ShuffleSplit(len(features), n_iter=100, test_size=0.1) scores = cross_val_score(svm, features, aut_target, cv=cv, n_jobs=8) dummy_scores_1 = cross_val_score(DummyClassifier("stratified"), features, aut_target, cv=cv, n_jobs=8) dummy_scores_2 = cross_val_score(DummyClassifier("most_frequent"), features, aut_target, cv=cv, n_jobs=8) dummy_scores_3 = cross_val_score(DummyClassifier("uniform"), features, aut_target, cv=cv, n_jobs=8) print "Scores using shuffle split on time courses:" print "%1.3f +- %1.3f" % (scores.mean(), scores.std() / np.sqrt(len(scores))) print "Dummy scores using different dummy strategies" print "%1.3f +- %1.3f" % (dummy_scores_1.mean(), dummy_scores_1.std() / np.sqrt(len(scores))) print "%1.3f +- %1.3f" % (dummy_scores_2.mean(), dummy_scores_2.std() / np.sqrt(len(scores))) print "%1.3f +- %1.3f" % (dummy_scores_3.mean(), dummy_scores_3.std() / np.sqrt(len(scores)))
{ "repo_name": "AlexandreAbraham/movements", "path": "nilearn_private/baseline.py", "copies": "1", "size": "2515", "license": "mit", "hash": -7900626741903657000, "line_mean": 39.564516129, "line_max": 77, "alpha_frac": 0.6771371769, "autogenerated": false, "ratio": 3.3758389261744965, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45529761030744964, "avg_score": null, "num_lines": null }
# A first cut at a class that embodies many simulations sharing the same # physical domain. import os, shutil, sys, getopt, glob, datetime from shapely import wkb, geometry import logging from .depender import rule,make,clear,DependencyGraph from ...grid import (paver,orthomaker,trigrid) from ...spatial import linestring_utils, wkb2shp from . import sunreader from ... import parse_interval import interp_depth import instrument,adcp,forcing import field import edge_depths import domain_plotting try: from osgeo import ogr,osr except ImportError: print("falling back to direct ogr in domain") import ogr,osr from safe_pylab import * from numpy import * import numpy as np # for transition to better style... from numpy import random def empty_create(target,deps=None): fp = open(target,'wt') fp.close() def relpath(path, start=os.curdir): """Return a relative version of a path copied from python 2.6 posixpath (unavailable in 2.5) """ if not path: raise ValueError("no path specified") start_list = os.path.abspath(start).split(os.sep) path_list = os.path.abspath(path).split(os.sep) # Work out how much of the filepath is shared by start and path. i = len(os.path.commonprefix([start_list, path_list])) rel_list = [os.pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return os.curdir return os.path.join(*rel_list) def mylink(src,dst): # given two paths that are either absolute or relative to # pwd, create a symlink that includes the right number of # ../..'s if os.path.isabs(src): # no worries os.symlink(src,dst) else: pre = relpath(os.path.dirname(src),os.path.dirname(dst)) os.symlink( os.path.join(pre,os.path.basename(src)), dst ) def ensure_real_file( fn ): """ If fn is a symlink, replace it with a copy of the target """ if os.path.islink(fn): shutil.copyfile(fn,'tmp') os.unlink(fn) shutil.move('tmp',fn) class VirtualInstrument(object): """ Define locations of 'virtual' instruments which can be realized from simulation output data. """ def __init__(self,name,xy): self.name = name self.xy = xy class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) default_suntans_dat_template_txt = """######################################################################## # # Input file for SUNTANS. # ######################################################################## Nkmax 1 # Number of vertical grid points stairstep 0 # 1 if stair-stepping, 0 if partial-stepping rstretch 1 # Stretching factor for vertical grid (1<=rstretch<1.1) CorrectVoronoi 2 # Whether or not to correct Voronoi points 1: dist-ratio 2: angle VoronoiRatio 85.0 # Adjust the voronoi points by this amount if 1 then = centroid. vertgridcorrect 0 # Correct vertical grid if Nkmax is too small IntDepth 0 # 1 if interpdepth, 0 otherwise dzsmall 0 # obsolete scaledepth 0 # Scale the depth by scalefactor scaledepthfactor 0 # Depth scaling factor (to test deep grids with explicit methods) thetaramptime 86400 # Timescale over which theta is ramped from 1 to theta (fs theta only) theta 0.55 # 0: fully explicit, 1: fully implicit thetaS 0.55 # For scalar advection thetaB 0.55 # For scalar advection beta 0.00078 # Coefficient of expansivity of salt kappa_s 0 # Vertical mass diffusivity kappa_sH 0 # Horizontal mass diffusivity gamma 0 # Coefficient of expansivity of temperature. kappa_T 0 # Vertical thermal diffusivity kappa_TH 0 # Horizontal thermal diffusivity nu 1e-6 # Laminar viscosity of water (m^2 s^-1) (w*w*dt=1e-3*1e-3*90) nu_H 0.0 # Horizontal laminar viscosity of water (m^2 s^-1) (.1*.1*90) tau_T 0.0 # Wind shear stress z0T 0.0 # Top roughness z0B 0.0001 # Bottom roughness CdT 0.0 # Drag coefficient at surface CdB 0.0 # Drag coefficient at bottom CdW 0.0 # Drag coefficient at sidewalls turbmodel 1 # Turbulence model (0 for none, 1 for MY25) dt 120 # Time step Cmax 10 # Maximum permissible Courant number nsteps 20000 ntout 10 # How often to output data ntprog 1 # How often to report progress (in %) ntconserve 1 # How often to output conserved data nonhydrostatic 0 # 0 = hydrostatic, 1 = nonhydrostatic cgsolver 1 # 0 = GS, 1 = CG maxiters 5000 # Maximum number of CG iterations qmaxiters 2000 # Maximum number of CG iterations for nonhydrostatic pressure hprecond 1 # 1 = preconditioned 0 = not preconditioned qprecond 2 # 2 = Marshall et al preconditioner(MITgcm), 1 = preconditioned, 0 = not preconditioned epsilon 1e-10 # Tolerance for CG convergence qepsilon 1e-10 # Tolerance for CG convergence for nonhydrostatic pressure resnorm 0 # Normalized or non-normalized residual relax 1.0 # Relaxation parameter for GS solver. amp 0 # amplitude omega 0 # frequency flux 0 # flux timescale 0 # timescale for open boundary condition volcheck 0 # Check for volume conservation masscheck 0 # Check for mass conservation nonlinear 3 # 2 2nd order central, 1 if 1st Order upwind for horizontal velocity, 0 for u^(n+1)=u^n newcells 0 # 1 if adjust momentum in surface cells as the volume changes, 0 otherwise wetdry 1 # 1 if wetting and drying, 0 otherwise Coriolis_f 9.36e-5 # Coriolis frequency f=2*Omega*sin(phi) sponge_distance 0 # Decay distance scale for sponge layer sponge_decay 0 # Decay time scale for sponge layer readSalinity 1 # Whether or not to read initial salinity profile from file InitSalinityFile readTemperature 0 # Whether or not to read initial temperature profile from file InitTemperatureFile start_day 0 # Offset for tides from start of simulation year (in days) GMT!!! start_year 2005 # start day is relative to the beginning of this year ######################################################################## # # Grid Files # ######################################################################## pslg oned.dat # Planar straight line graph (input) points points.dat # Vertices file (input) edges edges.dat # Edge file (input) cells cells.dat # Cell centered file (input) depth depth.dat # Depth file for interpolation (if INTERPDEPTH=1) (input) edgedepths edgedepths.dat celldata celldata.dat # Cell-centered output (output) edgedata edgedata.dat # Edge-centered output (output) vertspace vertspace.dat # Vertical grid spacing (output) topology topology.dat # Grid topology data ######################################################################## # # Output Data Files # ######################################################################## FreeSurfaceFile fs.dat HorizontalVelocityFile u.dat VerticalVelocityFile w.dat SalinityFile s.dat BGSalinityFile s0.dat TemperatureFile T.dat PressureFile q.dat VerticalGridFile g.dat ConserveFile e.dat ProgressFile step.dat StoreFile store.dat StartFile start.dat EddyViscosityFile nut.dat ScalarDiffusivityFile kappat.dat # LagrangianFile lagra.dat ######################################################################## # # Input Data Files # ######################################################################## InitSalinityFile mbay_salinity.dat InitTemperatureFile Tinit.dat TideInput tidecomponents.dat BoundaryInput boundaries.dat TideOutput tidexy.dat ######################################################################## # # For output of data # ######################################################################## ProfileVariables husnb # Only output free surface and currents DataLocations dataxy.dat # dataxy.dat contains column x-y data ProfileDataFile profdata.dat # Information about profiles is in profdata.dat ntoutProfs 10 # 10 minutes. Output profile data every n time steps NkmaxProfs 0 # Only output the top 1 z-level numInterpPoints 1 # Output data at the nearest neighbor. """ def default_suntans_dat_template(): return sunreader.SunConfig(text=default_suntans_dat_template_txt) class Domain(domain_plotting.DomainPlotting): """ A recipe for creating a ready to run set of input files Requires a suntans.dat.template file in datadir """ np = 1 # some commands can utilize mpi - it has to be specified on the command line # before the command (python mydomain.py -m my_command datadir ...) # experimental! (but what isn't?) mpicomm = False # when spinning up a fine grid to match the timing of a # coarse grid (in preparation for copying the coarse grid # salinity to the fine grid), this is the lead time used: hydro_spinup_days = 3 # coordinate reference - defaults to UTM Zone 10, NAD83, meters spatial_ref='EPSG:26910' # the projection of the grid lonlat_ref = 'WGS84' # the specific system to use for lat/lon inputs # Thalwegging: starting from any inflow edges, search (breadth-first) # for a cell that is at least as deep as thalweg_depth, then set up # to thalweg_max_cells along that path to thalweg_depth. # set thalweg_max_cells = 0 to disable thalweg_max_cells = 0 # disabled. thalweg_depth = 0.0 # positive down, and must account for bathy_offset enable_edge_based_bathymetry = True # whether thin bed cells should be removed. if this is not enabled, you probably # want to have a nonzero dz_lump_bed_frac in suntans.dat trim_depths = True private_rundata = False # Names of other config files: sedi_dat = "sedi.dat" sedi_ls_dat = "sedi_ls.dat" wave_dat = "wave.dat" contiguous_dat = "contiguous.dat" def __init__(self,datadir = 'rundata'): # self.rundata_dir is where all the global grid, bc, etc. information is kept, # plus partitioned grids for each number of processors. # if this is a private_rundata Domain, though, these are kept in the initial # directory of a particular run. self.log=logging.getLogger(self.__class__.__name__) self.rundata_dir = datadir self.conf = self.suntans_config() # sediment configuration: self.sedi_conf = self.sedi_config() # old sediment code - not really supported at this point self.sedi_ls_conf = self.sedi_ls_config() # new sediment code. def sedi_config(self): return None # disabled by default def sedi_ls_config(self): return None # disabled by default def suntans_config(self): """ Returns a SunConfig object used as the base suntans.dat. the usage here is migrating - it used to be that if the template file did not exist, it would be initialized from code like this, and if it did exist, it would be used as is. but that allows the domain code and the suntans.dat file to get out of sync, and it's too confusing to know which is in charge. so now the base suntans.dat always comes from here. the file is used only to timestamp when the settings have changed. so this method starts with the base suntans.dat above, and allows programmatic modifications. code elsewhere takes care of writing this out to the suntans_dat_template_file() if there is a relevant change. """ conf = default_suntans_dat_template() # Make changes based on settings that are already known if self.enable_edge_based_bathymetry: conf['edgedepths'] = 'edgedepth.dat' else: del conf['edgedepths'] # assume for now that we're always specifying the exact layers conf['rstretch']=0 conf['Nkmax'] = len(self.vertspace()) return conf def virtual_instruments(self): return [] def original_grid_dir(self): return os.path.join(self.rundata_dir,'original_grid') def depth_untrimmed_file(self): return os.path.join(self.rundata_dir,self.conf['depth'] + '.untrimmed') def edgedepth_untrimmed_file(self): return os.path.join(self.rundata_dir,self.conf['edgedepths'] + '.untrimmed') def depth_thalwegged_file(self): return os.path.join(self.rundata_dir,'depth.dat.thalwegged') def edgedepth_thalwegged_file(self): return os.path.join(self.rundata_dir,self.conf['edgedepths'] + '.thalwegged') def depth_file(self): return os.path.join(self.rundata_dir,self.conf['depth']) def edgedepth_file(self): return os.path.join(self.rundata_dir,self.conf['edgedepths']) def global_bc_grid_dir(self): return self.rundata_dir def vertspace_dat_in_file(self): return os.path.join(self.rundata_dir,'vertspace.dat.in') def partitioned_grid_dir(self): if self.private_rundata: return os.path.join(self.rundata_dir) else: return os.path.join(self.rundata_dir,'np%03d'%self.np) def salinity_file(self): readSalinity = self.conf.conf_int('readSalinity') if readSalinity == 1: # just reads vertical profile return os.path.join(self.partitioned_grid_dir(),self.conf.conf_str("InitSalinityFile")) elif readSalinity == 2: return os.path.join(self.partitioned_grid_dir(),self.conf.conf_str("InitSalinityFile")+".0") else: return None def temperature_file(self): readTemperature = self.conf.conf_int('readTemperature') if readTemperature == 1: # just reads vertical profile return os.path.join(self.partitioned_grid_dir(),self.conf.conf_str("InitTemperatureFile")) elif readTemperature == 2: return os.path.join(self.partitioned_grid_dir(),self.conf.conf_str("InitTemperatureFile")+".0") else: return None def sedi_file(self): return os.path.join(self.rundata_dir, self.sedi_dat) def sedi_ls_file(self): return os.path.join(self.rundata_dir,self.sedi_ls_dat) def dataxy_file(self): return os.path.join(self.rundata_dir,'dataxy.dat') def suntans_dat_template_file(self): return os.path.join(self.original_grid_dir(),'suntans.dat') def create_suntans_dat_template(self,target,deps): self.log.debug("Writing self.conf to %s"%target) if not os.path.exists(self.rundata_dir): os.mkdir(self.rundata_dir) self.conf.write_config(filename=target,check_changed=True) self.log.debug("Done writing self.conf") def vertspace(self): """ definitive source for z-layer elevations. these are the thickness of the cells, starting from 0 going from the surface to the bed. """ # typically this would be overridden in the subclass return np.loadtxt("path/to/vertspace.dat.in") def create_vertspace_dat_in(self,target,deps): # 2015-10-08: try having the definitive z vertical spacing # set as a method, self.zlevels(). # In order to avoid unnecessarily modifying file timestamps, # this method compares self.zlevels() and the contents of # an existing vertspace.dat.in, updating the file if they differ. vals=self.vertspace() if os.path.exists(target): target_vals=np.loadtxt(target) if len(vals) == len(target_vals) and np.allclose(vals,target_vals): self.log.debug("vertspace file %s is up to date"%target) return vals.tofile(target,"\n") ## Create the original, global grid def interior_lines(self): """ If there are internal guidelines for the grid creation. This would be for forcing cells to be aligned with some isobath, or for defining sections for flux analysis. """ return [] def tweak_paver(self): """ gives subclasses a chance to make minor changes to the paving instance before a grid is created """ pass def prep_paver(self): """ Create the paving instance, get everything ready to start paving. Useful for debugging the paving process. """ rings = self.shoreline() degenerates = self.interior_lines() density = self.density() p = paver.Paving(rings,density,degenerates=degenerates) self.p = p self.tweak_paver() def grid_create(self,target,deps): if not os.path.exists(self.original_grid_dir()): os.makedirs( self.original_grid_dir() ) self.prep_paver() self.p.verbose = 1 self.p.pave_all() self.p.renumber() self.p.write_suntans(self.original_grid_dir()) def grid_read(self): return orthomaker.OrthoMaker( suntans_path=self.original_grid_dir() ) def global_markers_create(self,target,deps): """ mark edges according to the forcing in the global grid. Try to avoid actually loading any data, just figure out which edges/cells will be forced. """ # in the past, this copied the files over, but if there was an error # while marking them, the unmarked files were left. # now, try to catch any exceptions long enough to remove the unmarked # grid # another option would be to read in the original grid, and write # the marked grid, but this way there is at least a chance of # realizing that the marks have not changed, and the grid can be # left as is (so modification doesn't trigger unnecessary repartitioning # and so forth). remove_on_exception = [] try: # Copy the original grid to here, then update with boundary markers for f in ['cells.dat','edges.dat','points.dat']: self.log.debug("Copying %s to %s"%(f,self.global_bc_grid_dir())) fn = os.path.join(self.global_bc_grid_dir(),f) remove_on_exception.append(fn) src = os.path.join( self.original_grid_dir(),f ) dst = fn try: shutil.copy(os.path.join(self.original_grid_dir(),f), fn) except: self.log.error("Problem while copying %s => %s"%(src,dst)) raise # and copy the template suntans.dat to here: sdat_template = self.suntans_dat_template_file() sdat_global_bc = os.path.join(self.global_bc_grid_dir(),'suntans.dat') if not os.path.exists( sdat_global_bc ): self.log.debug("Copying suntans.dat template to global BC directory") shutil.copy(sdat_template,sdat_blobal_bc) # Read the original grid, but write a global grid into # global_bc_grid_dir() gforce = self.global_forcing( datadir=self.global_bc_grid_dir() ) gforce.update_grid() except: self.log.error("Exception while marking grid - removing potentially unmarked grid files") for f in remove_on_exception: if os.path.exists( f ): os.unlink(f) raise def boundaries_dat_create(self,target,deps): gforce = self.global_forcing(datadir=self.partitioned_grid_dir()) gforce.write_boundaries_dat() # Spatial reference convenience routines: geo_to_local = None local_to_geo = None def convert_geo_to_local(self,lonlat): self.set_transforms() x,y,z = self.geo_to_local.TransformPoint(lonlat[0],lonlat[1],0) return [x,y] def convert_local_to_geo(self,xy): self.set_transforms() lon,lat,z = self.geo_to_local.TransformPoint(xy[0],xy[1],0) return [lon,lat] def set_transforms(self,force=False): if force or (self.geo_to_local is None or self.local_to_geo is None): local = osr.SpatialReference() ; local.SetFromUserInput(self.spatial_ref) geo = osr.SpatialReference() ; geo.SetFromUserInput(self.lonlat_ref) self.geo_to_local = osr.CoordinateTransformation(geo,local) self.local_to_geo = osr.CoordinateTransformation(local,geo) # Utility methods for defining freshwater sources: def add_flows_from_shp(self,gforce,flows_shp,bc_type='bc_type'): """ Reads flow sources from the given shapefile and adds them to the global forcing Since flows will use domain-dependent datasources, this will make calls back to self.flow_datasource(driver,{fields}) to get the relevant datasource. if bc_type is given, it is the name of a text field in the shapefile which gives the type of element which is forced: BOUNDARY: boundary edges BED: bed cell (which is currently turned into surface cell) others... """ if not os.path.exists(flows_shp): self.log.error("While trying to open shapefile %s"%flows_shp) raise Exception("Failed to find flows shapefile") flows=wkb2shp.shp2geom(flows_shp) groups=gforce.add_groups_bulk(flows,bc_type_field=bc_type) # zero = forcing.Constant('zero',0) for feat_id in range(len(flows)): grp=groups[feat_id] fields={ fld:flows[fld][feat_id] for fld in flows.dtype.names } self.log.debug("Processing flow data from shapefile: %s"%fields.get('name','n/a')) # geo = fields['geom'] # might be either a point or a line - just process all the points # points = np.array(geo) # if bc_type is not None: # typ=fields[bc_type] # else: # typ="FORCE_Q" # # if typ=='FORCE_BED_Q': # typ='FORCE_SURFACE_Q' # print "Will fake the bed source with a surface source" # # Define the forcing group: # if typ in ['FORCE_SURFACE_Q','FORCE_BED_Q']: # grp = gforce.new_group( nearest_cell=points[0] ) # else: # if len(points) == 1: # grp = gforce.new_group( nearest=points[0] ) # else: # # just use endpoints to define an arc along the boundary. # grp = gforce.new_group( points=[points[0], # points[-1]] ) self.attach_datasources_to_group(grp,fields) # flow = self.flow_datasource(fields['driver'],fields) # # grp.add_datasource(flow,typ) # if grp.edge_based(): # grp.add_datasource(zero,"FORCE_S") # # currently surface fluxes can only have zero salinity def partitioned_create(self,target,deps): # setup the partitioned subdirectory, then partition if not os.path.exists(self.partitioned_grid_dir()): os.mkdir(self.partitioned_grid_dir()) if os.path.abspath(self.global_bc_grid_dir()) != os.path.abspath(self.partitioned_grid_dir()): for f in ['cells.dat','edges.dat','points.dat','depth.dat','suntans.dat']: self.log.debug("Copying %s"%f) shutil.copy(os.path.join(self.global_bc_grid_dir(),f), os.path.join(self.partitioned_grid_dir(),f)) # these may exist - copy if they do: section_input_file = self.conf.conf_str("SectionsInputFile") if section_input_file: section_inputs = [section_input_file] else: section_inputs = [] if self.sedi_conf: self.sedi_conf.write_config( os.path.join( self.global_bc_grid_dir(),self.sedi_dat) ) if self.sedi_ls_conf: self.sedi_ls_conf.write_config( os.path.join( self.global_bc_grid_dir(),self.sedi_ls_dat) ) for f in [self.wave_dat,self.contiguous_dat] + section_inputs: if os.path.exists( os.path.join(self.global_bc_grid_dir(),f) ): self.log.debug("Copying %s"%f) shutil.copy(os.path.join(self.global_bc_grid_dir(),f), os.path.join(self.partitioned_grid_dir(),f)) if self.conf.conf_int('outputPTM',0) > 0: srcfile = os.path.join(self.global_bc_grid_dir(),'ptm.in') if os.path.exists(srcfile): shutil.copy(srcfile, self.partitioned_grid_dir()) shutil.copy(self.dataxy_file(), os.path.join(self.partitioned_grid_dir())) else: # for some files like sedi.dat may need to create them even when there is # no copying to an npXX directory to worry about. if self.sedi_conf: self.sedi_conf.write_config( os.path.join( self.partitioned_grid_dir(),self.sedi_dat) ) if self.sedi_ls_conf: self.sedi_ls_conf.write_config( os.path.join( self.partitioned_grid_dir(),self.sedi_ls_dat)) rstretch=self.conf.conf_float('rstretch') if rstretch == 0.0: if not os.path.exists( os.path.join(self.partitioned_grid_dir(),'vertspace.dat.in')): self.log.debug("Copying vertspace.dat.in from %s to %s"%(self.vertspace_dat_in_file(), self.partitioned_grid_dir())) shutil.copy(self.vertspace_dat_in_file(), os.path.join(self.partitioned_grid_dir(),'vertspace.dat.in')) else: self.log.debug("No need for vertspace.dat.in because rstretch=%s"%rstretch) sun = sunreader.SunReader(self.partitioned_grid_dir()) sun.domain_decomposition(np=self.np) def file_copy(self,target,deps): shutil.copy(deps[0],target) def run_create(self): """ create the time-invariant portios of a run in rundata/npNNN """ # There are too many things going on in here - making it impossible # for subclasses to override selectively. clear() # the grid doesn't depend on anyone original_grid_file = os.path.join( self.original_grid_dir(), 'edges.dat') rule( original_grid_file,[],self.grid_create ) # template file: if it doesn't exist, create one with the default contents # which also takes care of creating rundata rule( self.suntans_dat_template_file(), [], self.create_suntans_dat_template, always_run=True ) # 2 copies of the suntans.dat file # can we get rid of this one? # og_suntans_dat = os.path.join(self.original_grid_dir(),'suntans.dat') suntans_dat = os.path.join(self.global_bc_grid_dir(),'suntans.dat') # rule( og_suntans_dat, self.suntans_dat_template_file(), lambda target,deps: shutil.copyfile(deps[0],target)) sdtf = self.suntans_dat_template_file() self.log.debug("Template file: %s"%sdtf) rule( self.global_bc_grid_dir(),[], lambda target,deps: os.mkdir(self.global_bc_grid_dir())) rule( suntans_dat, [self.suntans_dat_template_file(),self.global_bc_grid_dir()], lambda target,deps: shutil.copyfile(deps[0],target)) global_markers_file = os.path.join(self.global_bc_grid_dir(),'edges.dat') rule(global_markers_file, [original_grid_file, suntans_dat], self.global_markers_create ) ## BATHYMETRY # several steps depend on knowing the dz distribution from vertspace.dat.in - if self.conf.conf_float('rstretch') == 0.0: vertspace_req = [ self.vertspace_dat_in_file() ] else: vertspace_req = [] self.log.debug("vertspace_req is %s"%vertspace_req ) ## First, the recipe for edge-based depths, if enabled: if self.enable_edge_based_bathymetry: self.log.info("Adding rules for edge-based bathymetry") rule( self.edgedepth_untrimmed_file(), [original_grid_file] + self.extra_depth_depends(), self.edgedepth_untrimmed_create ) if self.thalweg_max_cells > 0: # global markers are in here so we can add thalwegs for freshwater sources rule( self.edgedepth_thalwegged_file(), [self.edgedepth_untrimmed_file(),global_markers_file], self.edgedepth_thalwegged_create ) file_to_trim = self.edgedepth_thalwegged_file() else: file_to_trim = self.edgedepth_untrimmed_file() # the trimmed rule should be the same for everyone, though rule( self.edgedepth_file(), [suntans_dat,file_to_trim]+vertspace_req, self.edgedepth_trimmed_create ) # In the case of edge-based bathymetry, we still want to generate cell depths since # they will be read in, but they are basically slaved to the edge bathymetry rule( self.depth_file(), [self.edgedepth_file(),original_grid_file], self.depth_from_edges_create ) else: ## Only cell-based bathymetry ## Then the recipe for cell-based depths: rule( self.depth_untrimmed_file(), [original_grid_file] + self.extra_depth_depends(), self.depth_untrimmed_create ) if self.thalweg_max_cells > 0: # global markers are in here so we can add thalwegs for freshwater sources rule( self.depth_thalwegged_file(), [self.depth_untrimmed_file(),global_markers_file], self.depth_thalwegged_create ) file_to_trim = self.depth_thalwegged_file() else: file_to_trim = self.depth_untrimmed_file() # the trimmed rule should be the same for everyone, though rule( self.depth_file(), [suntans_dat,file_to_trim] + vertspace_req, self.depth_trimmed_create ) partitioned_file = os.path.join(self.partitioned_grid_dir(),'edges.dat.0') partition_deps = [global_markers_file, self.depth_file(), suntans_dat, self.dataxy_file()] + vertspace_req # give subclasses the option of creating a vertspace.dat.in file rule( self.vertspace_dat_in_file(), [self.suntans_dat_template_file()], self.create_vertspace_dat_in ) rule( partitioned_file, partition_deps, self.partitioned_create ) boundaries_dat_file = os.path.join( self.partitioned_grid_dir(),'boundaries.dat.0') # No longer create boundary data for npNNN - this will be created on a per-run # basis # rule( boundaries_dat_file, [partitioned_file,suntans_dat], # self.boundaries_dat_create) # the profile points - should depend on the original grid so that we can make sure # all points are within the grid rule( self.dataxy_file(), original_grid_file, self.create_dataxy_file) if self.enable_edge_based_bathymetry: # this used to get included regardless - now only do it if we are really using # edge depths, and fix the code to handle the case when the edge depths are missing. partitioned_edgedepths_file = self.partitioned_edgedepths_file() edge_deps = [partitioned_edgedepths_file] # include the step that fixes up the edge depths after partitioning. rule( partitioned_edgedepths_file, [self.edgedepth_file(), partitioned_file], self.partitioned_edgedepths_create ) else: edge_deps = [] # why was this here?? #rule( partitioned_edgedepths_file, [partitioned_file], # self.partitioned_edgedepths_create ) other_deps = [] if 0: # do this on a per-run basis - see cmd_replace_initcond() if self.salinity_file(): rule( self.salinity_file(), [partitioned_file,suntans_dat] + edge_deps, self.salinity_create) other_deps.append( self.salinity_file() ) if self.temperature_file(): rule( self.temperature_file(), [partitioned_file,suntans_dat] + edge_deps, self.temperature_create ) other_deps.append( self.temperature_file() ) # flux analysis sections if self.section_endpoints is not None: rule( self.sections_input_file(), [global_markers_file], self.sections_create ) rule( self.partitioned_sections_input_file(), [self.sections_input_file()], self.file_copy ) other_deps.append( self.partitioned_sections_input_file() ) # boundaries_dat_file rule('total',[partitioned_file,self.dataxy_file() ] + edge_deps + other_deps) make('total') def partitioned_edgedepths_file(self): # return os.path.join(self.partitioned_grid_dir(),'edgedepths.dat.0') return os.path.join(self.partitioned_grid_dir(),self.conf['edgedepths']) + ".0" edgedepths_delete_friction_strips = False def partitioned_edgedepths_create(self,target,deps): sun = sunreader.SunReader( self.partitioned_grid_dir() ) if self.enable_edge_based_bathymetry: edgedepth_file,partitioned_file = deps # The EdgeDepthWriter needs the global edge depths available, so symlink those # into the partitioned directory link_to_global_edgedepths = os.path.join(self.partitioned_grid_dir(), os.path.basename(edgedepth_file)) if not os.path.exists(link_to_global_edgedepths): mylink(edgedepth_file,link_to_global_edgedepths) # no direct check here to see that we're writing out the file that we think we are... # partitioned_file coming in is hopefully from the same place as partitioned_grid_dir, # and edgedepth_file is hopefully the same as sun.file_path('edgedepths',proc) ew = edge_depths.EdgeDepthWriter(delete_friction_strips=self.edgedepths_delete_friction_strips) ew.run( sun=sun ) else: partitioned_file = deps # pull edge depths from the shallower of the two neighboring cells sun = sunreader.SunReader( self.partitioned_grid_dir() ) global_grid = sun.grid() global_depth = loadtxt( self.depth_file() ) for proc in range(sun.num_processors()): localg = sun.grid(proc) edgedata = sun.edgedata(proc) fp = open(sun.file_path('edgedepths',proc),'wt') for j in range(localg.Nedges()): # find the global edge for this edge: global_j = global_grid.find_edge( localg.edges[j,:2] ) nc1,nc2 = global_grid.edges[global_j,3:5] if nc1 < 0: nc1 = nc2 elif nc2 < 0: nc2 = nc1 de = min( abs(global_depth[nc1,2]), abs(global_depth[nc2,2]) ) fp.write("%.6f %.6f %.6f\n"%(edgedata[j,4], edgedata[j,5], de) ) dataxy_shps = [] dataxy_fraction = 0.00 def create_dataxy_file(self,target,deps): """ For the long delta, we choose a small number of points randomly, plus exact points for the Polaris cruise stations. Also include exact locations of the instruments from the mar-09 deployment deps: [original_grid_file] """ grid = trigrid.TriGrid(suntans_path = self.original_grid_dir()) vcenters = grid.vcenters() data_points = [] # zeros( (0,2), float64) for typ,label,points in self.enumerate_dataxy_shps(): data_points.append( points ) if len(data_points) > 0: data_points = concatenate(data_points) else: data_points = zeros( (0,2), float64 ) # Now put all of those on the nearest cell center # everybody gets mapped to nearest for i in range(len(data_points)): c = grid.closest_cell( data_points[i] ) data_points[i] = vcenters[c] # And some random samples: if self.dataxy_fraction > 0.0: R = random.random(grid.Ncells()) random_points = vcenters[ R < self.dataxy_fraction ] if len(random_points)>0: if len(data_points) > 0: data_points = concatenate( (data_points,random_points) ) else: data_points = random_points savetxt( self.dataxy_file(), data_points ) # New depth approach - the subclass provides a depth field def extra_depth_depends(self): return [] def depth_field(self): """ a Field instance, returning elevations in natural units. The results here will be negated (to get soundins) and offset by 5m """ raise Exception("domain::depth_field() must be provided by subclasses") def depth_untrimmed_create(self,target,deps): """ target: something like ../depth.dat.untrimmed deps[0]: a file in the original grid dir """ f = self.depth_field() g = self.grid_read() vc = g.vcenters() # just evalute the depth field at the cell centers. For edge-based depths, this is # sufficient - for good cell-based depths, this should be an integration over the area # of the cell. # Note that the field gives us elevations, as in positive is up, and 0 is the datum 0. depths = f.value( vc ) # fix the sign and offset: offset = sunreader.read_bathymetry_offset() # 5m depths = -depths + offset # combine to one array: xyz = concatenate( (vc,depths[:,newaxis]), axis=1) savetxt(target,xyz) bad_count=np.sum(np.isnan(depths)) if bad_count: raise Exception("%d of %d cell-center depths were nan - see %s"%(bad_count, len(depths), target)) def depth_from_edges_create(self,target,deps): """ When bathymetry is specified on the edges, then this method can be used to create cell bathymetry directly from the edges. Assumes that any thalwegging and bed level trimming has been done in the edge bathymetry. """ g = self.grid_read() edge_depths = loadtxt(self.edgedepth_file()) cell_depths = zeros( (g.Ncells(),3), float64) for i in range(g.Ncells()): jlist = g.cell2edges(i) cell_depths[i] = edge_depths[jlist,2].max() cell_depths[:,:2] = g.vcenters() savetxt(target,cell_depths) def edgedepth_untrimmed_create(self,target,deps): """ target: something like ../edgedepths.dat.untrimmed deps[0]: a file in the original grid dir """ f = self.depth_field() g = self.grid_read() all_edge_depths = zeros( g.Nedges() ) for e in range(g.Nedges()): if e % 10000 == 0: self.log.debug("Edge depths: %d / %d"%(e,g.Nedges())) all_edge_depths[e] = f.value_on_edge(g.points[g.edges[e,:2]]) offset = sunreader.read_bathymetry_offset() all_edge_depths = -all_edge_depths + offset edge_field = field.XYZField(X=g.edge_centers(), F=all_edge_depths) edge_field.write_text(target) bad_count=np.sum(np.isnan(all_edge_depths)) if bad_count: raise Exception("%d of %d edge depths were nan - see %s"%(bad_count, len(all_edge_depths), target)) def edgedepth_thalwegged_create(self,thalwegged,deps): edge_untrimmed_file,global_markers_file = deps threshold = self.thalweg_depth # Load the grid and find all flow-forced boundaries (type 2) g = trigrid.TriGrid(suntans_path = os.path.dirname(global_markers_file) ) to_thalweg = nonzero( g.edges[:,2] == 2 )[0] # Load untrimmed depth data: xyz = loadtxt(edge_untrimmed_file) self.log.info("Edge thalwegs...") for j in to_thalweg: self.log.debug(" Carving from edge %d"%j) g.carve_thalweg(xyz[:,2],threshold,j,mode='edges',max_count=self.thalweg_max_cells) savetxt(thalwegged,xyz) def depth_thalwegged_create(self,thalwegged,deps): untrimmed_file,global_markers_file = deps threshold = self.thalweg_depth # Load the grid and find all flow-forced boundaries (type 2) g = trigrid.TriGrid(suntans_path = os.path.dirname(global_markers_file) ) to_thalweg = nonzero( g.edges[:,2] == 2 )[0] # Load untrimmed depth data: xyz = loadtxt(untrimmed_file) self.log.info( "Thalwegs...") for j in to_thalweg: self.log.debug( " Carving from edge %d"%j) g.carve_thalweg(xyz[:,2],threshold,j,mode='cells',max_count=self.thalweg_max_cells) fp = open(thalwegged,'wt') for i in range(len(xyz)): fp.write("%9.2f %9.2f %5.3f\n"%(xyz[i,0],xyz[i,1],xyz[i,2])) fp.close() def depth_trimmed_create(self,trimmed_file, deps): suntans_dat, untrimmed_file = deps[:2] if self.trim_depths: interp = interp_depth.DepthInterp() interp.create_trimmed(trimmed_file,suntans_dat,untrimmed_file) else: shutil.copyfile(untrimmed_file,trimmed_file) def edgedepth_trimmed_create(self,edge_trimmed_file,deps): suntans_dat, edge_untrimmed_file = deps[:2] if self.trim_depths: interp = interp_depth.DepthInterp() interp.create_trimmed(edge_trimmed_file,suntans_dat,edge_untrimmed_file) else: shutil.copyfile(edge_untrimmed_file,edge_trimmed_file) section_endpoints = None def sections_input_file(self): return os.path.join( self.global_bc_grid_dir(), self.conf.conf_str('SectionsInputFile') ) def partitioned_sections_input_file(self): return os.path.join( self.partitioned_grid_dir(), self.conf.conf_str('SectionsInputFile') ) def sections_create(self,sections_input_file,deps): """ Create section_defs.dat based on section_endpoints """ if self.section_shp is not None: # populate section_endpoints from section_shp ods = ogr.Open(self.section_shp) layer = ods.GetLayer(0) self.section_endpoints = [] while 1: feat = layer.GetNextFeature() if feat is None: break linestring = wkb.loads( feat.GetGeometryRef().ExportToWkb() ) self.section_endpoints.append( array(linestring) ) if self.section_endpoints is None: return fp = open(sections_input_file,"wt") fp.write("%d\n"%len(self.section_endpoints)) # Need to load the global grid... very slow........ sun = sunreader.SunReader( os.path.join(self.global_bc_grid_dir() ) ) self.log.info("Loading global grid. Patience, friend") g = sun.grid() self.log.info("Finding shortest paths for sections" ) # old code - just allowed endpoints - # new code - allow path for section_path in self.section_endpoints: self.log.debug("section: %s"%(section_path) ) this_path = [] for i in range(len(section_path)-1): a,b = section_path[i:i+2] n1 = g.closest_point(a) n2 = g.closest_point(b) this_path.append(g.shortest_path(n1,n2)) this_path = concatenate( this_path ) uniq = concatenate( ( [True], diff(this_path) != 0) ) linestring = this_path[ uniq ] fp.write("%d\n"%len(linestring)) fp.write(" ".join( [str(n) for n in linestring] ) + "\n") fp.close() ### Scalar initial conditions def salinity_create(self,datadir): """ default implementation calls self.initial_salinity() to figure out the salinity distribution. """ sun = sunreader.SunReader(datadir) readSalinity = sun.conf.conf_int('readSalinity') if readSalinity == 1: dimensions = 1 else: dimensions = 3 sun.write_initial_salinity(self.initial_salinity,dimensions=dimensions) def temperature_create(self,datadir): """ default implementation calls self.initial_temperature() to figure out the temperature distribution. """ sun = sunreader.SunReader(datadir) readTemperature = sun.conf.conf_int('readTemperature') if readTemperature == 1: dimensions = 1 else: dimensions = 3 sun.write_initial_temperature(self.initial_temperature,dimensions=dimensions) ### Virtual Instruments def find_jd0(self,sun): year = sun.conf.conf_int('start_year') return date2num( datetime.datetime(year,1,1) ) def get_instrument(self,name_or_inst,sun,chain_restarts=1): """ returns a ctd-like instrument with ADCP-like instrument as inst.adcp """ if isinstance(name_or_inst,str): # look up the instrument instance: vi = self.virtual_instruments() all_labels = [v.name for v in vi] i = all_labels.index(name_or_inst) virt = vi[i] else: virt = name_or_inst pnt = virt.xy label = virt.name self.log.debug("Creating virtual instrument at %s"%label) ### First, figure out grid-based metadata that will be the same # for all of the sunreader instances (in case we are chaining backwards) # This can be cached in the virtual instrument instance: try: prof_i,proc,cell,depth,bathymetry,nkmax,nk = virt.cached_invariant_data print("Using cached data for bathymetry, nk, etc.") except AttributeError: # get a freesurface timeseries to show at the same time: prof_i = sun.xy_to_profile_index(pnt) print( "Found profile index %d"%prof_i) print( "Finding closest cell") proc,cell = sun.closest_cell(pnt) depth = sun.depth_for_cell(cell,proc) # depth: negative, and without the bathymetry offset. # depth_for_cell returns the value from the file, and suntans doesn't # respect signs in the bathy input file, so we just have to force the # sign here, and let depth be the bed elevation, a negative number. depth = -abs(depth) # then bathymetry is what is physically out there bathymetry = depth + sun.bathymetry_offset() nkmax = sun.conf_int('Nkmax') nk = sun.Nk(proc)[cell] virt.cached_invariant_data = prof_i,proc,cell,depth,bathymetry,nkmax,nk ### Then per-sunreader instance things: all_records = [] all_records_wc = [] all_adcps = [] # U,V,t for each period if chain_restarts: suns = sun.chain_restarts() else: suns = [sun] jd0 = self.find_jd0(sun) for sun in suns: # sun.chain_restarts(): ## Figure out the times we want: prof_absdays = sun.timeline(units='absdays',output='profile') self.log.info("Processing sun run JD %g-%g"%(prof_absdays[0]-jd0, prof_absdays[-1]-jd0)) sun_t0 = sun.time_zero() self.log.debug(" Reading freesurface timeseries") h = sun.profile_data('FreeSurfaceFile')[:,prof_i] ctops = sun.h_to_ctop(h) # The top of the 'bottom' region: # take 2 cells, as long as they are valid top_of_bottom = maximum(nk-2,ctops) # and the bottom of the top region: bottom_of_top = minimum(ctops+2,nk) # these should be timestep,profile point,z-level salt = sun.profile_data('SalinityFile')[:,prof_i,:] nut = sun.profile_data('EddyViscosityFile')[:,prof_i,:] # this should be timestep,{u,v,w}, profile point, z-level U = sun.profile_data('HorizontalVelocityFile')[:,:,prof_i,:] # To allow for running this while a simulation is still going, # we have to be careful about how many profile steps there are. n_p_steps = [ h.shape[0], len(prof_absdays), U.shape[0], salt.shape[0] ] n_steps = min(n_p_steps) # create a record array that will have depth, salinity_surface # salinity_bed, jd records = zeros( (n_steps,), dtype=[('jd','f8'), ('h','f8'), ('Depth','f8'), ('salinity_surface','f8'), ('salinity_bed','f8'), ('salinity_avg','f8'), ('u_surface','f8'), ('u_bed','f8'), ('v_surface','f8'), ('v_bed','f8'), ('u_avg','f8'), ('v_avg','f8'), ('int_udz','f8'), ('int_vdz','f8'), ('k_top','i4'), ] ) # and for values that have a vertical dimension: # shares the same timeline as records. records_wc = zeros( (n_steps,nk), dtype=[('u','f8'), ('v','f8'), ('salinity','f8'), ('nut','f8'), ('z_top','f8'), ('z_bot','f8')] ) records['jd'] = prof_absdays[:n_steps] - jd0 # h is NAVD88-bathymetry_offset(), so adjust back to NAVD88 records['h' ] = h[:n_steps] + sun.bathymetry_offset() # and the difference is the depth records['Depth'] = h[:n_steps] - depth # tops of each z-level - sun.z_levels() gives positive values # so negate to get proper elevations z_tops = -concatenate( ( [0],sun.z_levels()) ) # adjust the bottom z-level # nk is the number of cells in the water column - so # z_top[0] is the top of z-level 0 # z_top[nk] is the top of z-level nk, blah blah blah. # this used to be nk+1 # keep going back and forth on whether there should be a minus # sign here. z_tops[nk] = depth # take the means z_mids = 0.5*(z_tops[:-1] + z_tops[1:]) ## Put together some ADCP-like records adcpU = U[:n_steps,0,:].copy() # copy so nans don't pollute summations below adcpV = U[:n_steps,1,:].copy() adcpU[:,nk:] = nan adcpV[:,nk:] = nan adcpt = prof_absdays[:n_steps]-jd0 # these will get nan'd out in the loop below, but go ahead and put # them in the list now. all_adcps.append( [adcpU,adcpV,adcpt]) ## ## For now, do both the adcp style output and a 3D record style output records_wc['u'] = U[:n_steps,0,:nk] records_wc['v'] = U[:n_steps,1,:nk] records_wc['salinity'] = salt[:n_steps,:nk] records_wc['nut'] = nut[:n_steps,:nk] for i in range(n_steps): # define vectors that will do various averages on the inputs z_tops_i = z_tops.copy() # adjust the surface height z_tops_i[ctops[i]] = h[i] records['k_top'][i] = ctops[i] # thickness of each z-level dzz = diff( z_tops_i ) k=arange(nkmax) ## some regions: surface = dzz* ((k>=ctops[i]) & (k<bottom_of_top[i])) bed = dzz* ((k>=top_of_bottom[i]) & (k<nk)) water = dzz* ((k>=ctops[i]) & (k<nk)) # Do some averaging... records['salinity_surface'][i] = sum( salt[i] * surface ) / sum(surface) records['salinity_bed'][i] = sum( salt[i] * bed ) / sum(bed) records['salinity_avg'][i] = sum( salt[i] * water ) / sum(water) records['u_surface'][i] = sum( U[i,0] * surface ) / sum(surface) records['u_bed'][i] = sum(U[i,0] * bed ) / sum(bed) records['u_avg'][i] = sum(U[i,0] * water) / sum(water) records['v_surface'][i] = sum( U[i,1] * surface ) / sum(surface) records['v_bed'][i] = sum(U[i,1] * bed ) / sum(bed) records['v_avg'][i] = sum(U[i,1] * water) / sum(water) records['int_udz'][i] = sum(U[i,0] * water) records['int_vdz'][i] = sum(U[i,1] * water) # NaN out the dry/empty cells in the adcp data adcpU[i,0:ctops[i]] = nan adcpV[i,0:ctops[i]] = nan # And just to make life easy, include the dimensions of the z-levels records_wc['z_top'][i,:] = z_tops_i[:nk] + sun.bathymetry_offset() records_wc['z_bot'][i,:] = z_tops_i[1:nk+1] + sun.bathymetry_offset() # doctor up the water column output: for col in 'z_top','z_bot','u','v','salinity','nut': records_wc[col][i,0:ctops[i]] = nan # profile outputs can overlap (when full output interval is not a # multiple of profile output interval), so we can get duplicate # data. if len(all_records) > 0: last_output_jd = all_records[-1]['jd'][-1] first_new_output = searchsorted( records['jd'], last_output_jd, side='right') if first_new_output < len(records): self.log.debug("Trimming a bit off the beginning of profile data from a restart") all_records.append( records[first_new_output:] ) all_records_wc.append( records_wc[first_new_output:] ) else: self.log.info("A restart didn't have any new profile data, so we skipped it") else: all_records.append(records) all_records_wc.append(records_wc) records = concatenate( all_records ) records_wc = concatenate( all_records_wc ) jd_base = sun.conf.conf_int('start_year') virt_ctd = instrument.Instrument(records=records,comment=label,records_wc=records_wc, xy=pnt,bathymetry=bathymetry, jd_base = jd_base) # copy everything because there seem to be some errors otherwise all_adcpU = array( transpose( concatenate( [adcpU for adcpU,adcpV,adcpt in all_adcps] ) ), copy=1) all_adcpV = array( transpose( concatenate( [adcpV for adcpU,adcpV,adcpt in all_adcps] ) ), copy=1 ) all_adcpt = concatenate( [adcpt for adcpU,adcpV,adcpt in all_adcps] ) virt_ctd.adcp = adcp.AdcpMoored.from_values( all_adcpU, all_adcpV, z_mids, all_adcpt, label) return virt_ctd ### METHODS for MANIPULATING RUNS ### def copy_to_datadir(self,dest_dir,src_dir=None,symlink=True): """ Symlink/Copy the requisite files from a rundata/npNNN directory to the given dest_dir. If symlink is true, then most files that are not expected to change (grid-related) are symlinked, and the others are copied. This is the python equivalent of copy_for_restart, without the restart part. sedi.dat and wave.dat files, if they exist in rundata/, will be copied to the new directory. Currently this isn't hooked into depender - it needs to be clearer how depender deals with a collection of files. if src_dir is not given, it is assumed to be the partitioned_grid_dir() corresponding to self.np """ if src_dir is None: src_dir = self.partitioned_grid_dir() if symlink: maybe_link = mylink else: maybe_link = shutil.copyfile if os.path.abspath(src_dir) == os.path.abspath(dest_dir): print( "copy_to_datadir: nothing to do") return if not os.path.exists(dest_dir): os.mkdir(dest_dir) for f in glob.glob(os.path.join(dest_dir,'*')): if os.path.isdir(f) and not os.path.islink(f): shutil.rmtree(f) else: os.unlink(f) # the @ prefix means it will use suntans.dat to look up the actual filename. # otherwise use the filename as given. per_processor = ['@topology','@BoundaryInput','@cells','@celldata','@edges','@edgedata'] global_files = ['@vertspace','@DataLocations','@points','@cells','@edges'] # If edgedepths is set, we need to copy them, too if self.conf.conf_str('edgedepths') is not None: per_processor.append('@edgedepths') # Temperature & salinity depend on configuration: read_salt=self.conf.conf_int('readSalinity') ; read_temp=self.conf.conf_int('readTemperature') if read_salt == 1: global_files.append('@InitSalinityFile') elif read_salt == 2: per_processor.append('@InitSalinityFile') if read_temp == 1: global_files.append('@InitTemperatureFile') elif read_temp == 2: per_processor.append('@InitTemperatureFile') ## particle tracking: if self.conf.conf_int('outputPTM',0) > 0: if os.path.exists( os.path.join(src_dir,'ptm.in') ): global_files.append('ptm.in') # Pre-processor files: for f in per_processor: if f[0]=='@': datname = self.conf.conf_str(f[1:]) else: datname = f for p in range(self.np): # may have to mangle the paths for symlink src_file = os.path.join(src_dir,datname+".%i"%p) if os.path.exists(src_file): maybe_link( src_file, os.path.join(dest_dir,datname+".%i"%p) ) # Global files: for f in global_files: if f[0] == '@': datname = self.conf.conf_str(f[1:]) else: datname = f src_file = os.path.join(src_dir,datname) if os.path.exists(src_file): maybe_link( src_file, os.path.join(dest_dir,datname) ) # Section analysis section_input_file = self.conf.conf_str("SectionsInputFile") if section_input_file is not None and os.path.exists( os.path.join(src_dir,section_input_file)): print( "Copying section definitions") maybe_link( os.path.join(src_dir,section_input_file), os.path.join(dest_dir,section_input_file) ) # Sediment, Waves: for dat_file in [self.sedi_dat,self.sedi_ls_dat,self.wave_dat]: if os.path.exists(os.path.join(src_dir,dat_file)): print( "Copying sediment data file") maybe_link( os.path.join(src_dir ,dat_file), os.path.join(dest_dir,dat_file) ) # BC Forcing data: if os.path.exists( os.path.join(src_dir,'datasources') ): print( "Copying boundary forcing data") shutil.copytree( os.path.join(src_dir,'datasources'), os.path.join(dest_dir,'datasources') ) if os.path.exists( os.path.join(src_dir,'fs_initial.dat') ): maybe_link( os.path.join(src_dir,'fs_initial.dat'), os.path.join(dest_dir,'fs_initial.dat') ) # suntans.dat is copied, not linked shutil.copy( os.path.join(src_dir,'suntans.dat'), os.path.join(dest_dir,'suntans.dat') ) def setup_startfiles(self,src_dir,dest_dir,symlink=True): """ Create symlinks from src_dir/storefiles to dest_dir/startfiles, and copy suntans.dat from the previous run """ # clean them up so the string substitutions below are safe src_dir = src_dir.rstrip('/') dest_dir = dest_dir.rstrip('/') start = self.conf.conf_str('StartFile') store = self.conf.conf_str('StoreFile') if symlink: copier = mylink else: copier = shutil.copy for p in range(self.np): copier( os.path.join(src_dir,store+".%i"%p), os.path.join(dest_dir,start+".%i"%p) ) # handles store_sedi and friends: for f in glob.glob(os.path.join(src_dir,"store_*.dat.*")): new_f = f.replace("store_","start_") new_f = new_f.replace(src_dir,dest_dir) copier( f, new_f) shutil.copy( os.path.join(src_dir,'suntans.dat'), os.path.join(dest_dir,'suntans.dat') ) # the old one may be write-protected - force writable os.chmod( os.path.join(dest_dir,'suntans.dat'), 0o644 ) def find_np_from_dir(self,datadir): # reads np from the first topology file topo_f = os.path.join( datadir,self.conf.conf_str('topology')+".0" ) fp = open(topo_f,'rb') np = int( fp.readline().split()[0] ) fp.close() return np def log_arguments(self,new_dir): fp = open( os.path.join(new_dir,'history.txt'), 'a+') def safely(s): if s.find(' ')>=0: return '"' + s + '"' else: return s fp.write("Created/updated with: %s\n"%(" ".join(map(safely,sys.argv)))) fp.close() def main(self,args=None): """ parse command line and start making things """ def usage(): print("python blah.py [-n #] [-tmM] [command]") print(" -n Specify number of processors") print(" -i Ignore timestamps") print(" -m parallelize using mpi - indicates that the script is being invoked by mpirun or friends ") print(" -M parallelize using mpi, and take care of queuing the process with the given number of processes from -n") print(" Command is one of:") print(" setup [<datadir>] - prepare the given directory for a run") print(" If no directory is given, the files are left in rundata/npNNN") print(" continue <old> <new> [+<duration>] - setup for continuing an ended or failed run in a new directory") print(" match_spinup <spin_dir> <new_dir> [date] - create a short run that ends at the same time") print(" as the spin_dir, or coincides with a full output step near/before the given date") print(" continue_with_spin <old> <spin> <new> [+<duration>] - like continue, but some scalars (currently only salt)") print(" write_instruments <datadir> - in a 'instruments' subdirectory, write virtual instrument data") print(" will be replaced with values interpolated from spin, and") print(" will replace symlinks to Storefiles with copies") print(" make_shps - write contour and boundary shapefiles") print(" plot_forcing <datadir>- dump plots of the various forcing datasources") if args is None: args = sys.argv[1:] self.check_timestamps = 1 try: opts,rest = getopt.getopt(args, "n:imM:") except getopt.GetoptError: usage() sys.exit(1) for opt,val in opts: if opt == '-n': self.np = int(val) elif opt == '-i': self.check_timestamps = 0 elif opt == '-m': import mpi4py.MPI self.mpicomm = mpi4py.MPI.COMM_WORLD elif opt == '-M': self.mpicomm = "SHELL" else: usage() sys.exit(1) if len(rest) > 0: cmd = rest[0] rest = rest[1:] else: # default action: cmd = 'setup' # try making all output unbuffered: sys.stdout = Unbuffered(sys.stdout) if self.mpicomm == 'SHELL': print( "Will start the as an mpi job with %d processes"%self.np) print( "argv: ",sys.argv) # the interpreter tends to get stripped out - this may cause some problems for scripts # that are directly executable and specify some extra stuff to the interpreter... sub_args = ['python'] for a in sys.argv: if a=='-M': # indicate to the subprocess that it *in* mpi a='-m' sub_args.append(a) sunreader.MPIrunner(sub_args,np=self.np,wait=0) print( "Job queued if you're lucky.") else: DependencyGraph.check_timestamps = self.check_timestamps self.invoke_command(cmd,rest) def run_has_completed(self,datadir): """ look at step.dat and return true if it exists and appears to represent a completed run """ if os.path.exists(datadir+"/step.dat"): sun = sunreader.SunReader(datadir) sd = sun.step_data() return sd['step'] == sd['total_steps'] return False def run_can_be_continued(self,datadir): """ slightly more permissive than run_has_completed - call this if you just want to make sure that a run was started, and got far enough such that continuing it makes sense. This does *not* check to see whether the given run is still running. The decision is made based on whether step.dat says that more than one step has been output (since the first step to be output is the initial condition...) """ if os.path.exists(datadir+"/step.dat"): sun = sunreader.SunReader(datadir) sd = sun.step_data() return sd['steps_output'] > 1 return False def run_crashed(self,datadir): """ Check to see if the given run crashed, as in the computations went unstable (as opposed to a case where it was killed by pbs, segfault'd, etc.) this depends on newer suntans code which differentiates storefile and crashfile. """ crash = datadir+"/crash.dat.0" store = datadir+"/store.dat.0" return os.path.exists(datadir+"/crash.dat.0") and os.stat(crash).st_mtime > os.stat(store).st_mtime def invoke_command(self,cmd,args): meth_name = "cmd_" + cmd f = getattr(self,meth_name) f(*args) def cmd_write_instruments(self,datadir): dest_dir = os.path.join( datadir, 'instruments') if not os.path.exists(dest_dir): os.mkdir(dest_dir) sun = sunreader.SunReader(datadir) for inst in self.virtual_instruments(): print( "processing instrument ",inst.name) v_inst = self.get_instrument(inst.name,sun,chain_restarts=1) fname = os.path.join( dest_dir, v_inst.safe_name() + ".inst" ) v_inst.save( fname ) def enumerate_dataxy_shps(self): """ Reads in the dataxy_shps, returns an iterator over profile points, (type,label,points) type = 'point' | 'transect' points = array( [[x,y],...] ), length 1 for single point samples Note that it returns the points as specified in the shapefiles, not nudged to be at cell centers. """ count = 0 for shp in self.dataxy_shps: print( "Loading profile points / transects from %s"%shp) if not os.path.exists(shp): raise Exception("Profile point shapefile not found: %s"%shp) feats=wkb2shp.shp2geom(shp) for idx,r in enumerate(feats): try: name=r['name'] except AttributeError: name='feat%d'%idx if r['geom'].geom_type=='Point': coords=np.array(r['geom'].coords) ftyp='point' elif r['geom'].geom_type=='LineString': ftyp='transect' coords=np.array(r['geom'].coords) try: resolution = r['resolution'] coords=linestring_utils.upsample_linearring(coords,resolution,closed_ring=0) except AttributeError: pass yield ftyp,name,coords # ods = ogr.Open(shp) # layer = ods.GetLayer(0) # # while 1: # count += 1 # feat = layer.GetNextFeature() # if feat is None: # break # try: # name = feat.GetField('name') # except ValueError: # name = "nameless%05d"%count # # g = wkb.loads( feat.GetGeometryRef().ExportToWkb() ) # if g.type == 'Point': # # everybody gets mapped to nearest # yield 'point',name,array(g.coords) # elif g.type == 'LineString': # points = array(g) # resolution = feat.GetField('resolution') # # points = linestring_utils.upsample_linearring(points,resolution,closed_ring=0) # yield 'transect',name,points # else: # raise Exception("create_dataxy can only handle Point or LineString layers, not %s"%g.type) def cmd_write_matlab(self,datadir,chain_restarts=1,insts=None): """ Like write_instruments, but (a) writes matlab files (b) grabs locations to dump from the self.dataxy_shps insts: generally leave it alone - this can be populated with a list of VirtualInstrument instances, in which case some data can be cached between processing restarts. """ dest_dir = os.path.join( datadir, 'matlab') if not chain_restarts: dest_dir += '-single' if not os.path.exists(dest_dir): os.mkdir(dest_dir) # Build the list of VirtualInstruments: if insts is None: insts = [] for ptype,label,points in self.enumerate_dataxy_shps(): if ptype == 'point': insts.append( VirtualInstrument(name=label,xy=points[0]) ) else: print( "Not ready for transects") else: print("Will use supplied list of instruments") sun = sunreader.SunReader(datadir) if chain_restarts: chained = sun.chain_restarts() for restart in chained: self.cmd_write_matlab(restart.datadir,chain_restarts=0,insts=insts) single_dirs =[ os.path.join( s.datadir, 'matlab-single') for s in chained] self.join_matlab_outputs(dest_dir,single_dirs) else: # compare timestamps step_mtime = os.stat( sun.file_path('ProgressFile') ).st_mtime for inst in insts: mat_fn = os.path.join( dest_dir, instrument.sanitize(inst.name) ) + ".mat" print("Checking timestamp of ",mat_fn) if os.path.exists(mat_fn) and os.stat( mat_fn ).st_mtime > step_mtime: print("Using pre-existing output") continue v_inst = self.get_instrument(inst,sun,chain_restarts=chain_restarts) fname = os.path.join( dest_dir, v_inst.safe_name() + ".mat" ) v_inst.save_matlab( fname ) def join_matlab_outputs(self,dest_dir,single_dirs): """ Go through each of the single_dirs, and concatenate the data across the different directories, creating a new matlab output file in dest_dir """ for matfile in glob.glob(single_dirs[0]+'/*.mat'): base_matfile = os.path.basename(matfile) print("Processing instrument %s"%base_matfile) mat_pieces = [os.path.join(sd,base_matfile) for sd in single_dirs] target_mat = os.path.join(dest_dir,base_matfile) instrument.Instrument.splice_matfiles(target_mat, mat_pieces) def cmd_setup(self): """ This handles all the steps to get a partitioned grid with BC markers and bathymetry ready, storing the result in rundata/npNNN """ self.run_create() def cmd_initialize_run(self,datadir,interval): """ Prepare a grid to simulate the given period """ if self.private_rundata: self.rundata_dir = datadir self.cmd_setup() # make sure the partitioned grid is ready to go # safer to initialize a run with a copy of the grid, in case things get regridded # or partitioned later on. if not self.private_rundata: self.copy_to_datadir(datadir,symlink=False) else: print("Private rundata: files are ready to go") self.log_arguments(datadir) sun = sunreader.SunReader(datadir) def_start,def_end = sun.simulation_period() start_date,end_date = parse_interval.parse_interval(interval, default_start = def_start, default_end = def_end) if 0: # sun.conf.set_simulation_period(start_date,end_date) sun.conf.write_config() else: if not self.conf.is_grid_compatible(sun.conf): raise Exception("Looks like the differences between these suntans.dat files would make incompatible grids") self.conf.set_simulation_period(start_date,end_date) self.conf.write_config(os.path.join(datadir,'suntans.dat')) self.cmd_replace_forcing(datadir) self.cmd_replace_initcond(datadir) def cmd_run(self,datadir,wait=1,max_retries="0"): """ retry: if true, then if the simulation stops but doesn't produce a crash file, try to restart the run and keep going. if it is necessary to restart, the earlier runs will be renamed, and the final run will be named datadir. """ wait = (wait in (True, 1,'yes','on','wait','sync')) if wait: print("Will wait for run to complete") sun = sunreader.SunReader(datadir) max_retries = int(max_retries) prev_count=0 while 1: sun.run_simulation(wait=wait) if not wait: print("Not waiting around for that to finish") break if self.run_has_completed(datadir): print("Looks like the run really did complete") break # otherwise - did it crash, or just disappear? if not self.run_can_be_continued(datadir): print("The run didn't finish, but didn't get far enough along to consider continuing") break if self.run_crashed(datadir): print("The run crashed - will not continue") if prev_count >= max_retries: print("Too many continuations: %d"%prev_count) break # So it's viable to restart this run. old_dir = datadir + "-pre%02d"%prev_count prev_count += 1 os.rename(datadir,old_dir) self.cmd_setup_completion(old_dir,datadir) def cmd_setup_completion(self,incomplete_dir,next_dir): """ Given a run in incomplete_dir which is... incomplete, setup a new run in next_dir which will reach the originally intended ending time. """ self.np = self.find_np_from_dir(incomplete_dir) self.copy_to_datadir(src_dir=incomplete_dir,dest_dir=next_dir,symlink=True) self.setup_startfiles(incomplete_dir,next_dir) ## Find when it was supposed to finish: old_sun = sunreader.SunReader(incomplete_dir) old_start,old_end = old_sun.simulation_period() ## And when the restart starts: sun = sunreader.SunReader(next_dir) new_start,new_end = sun.simulation_period() # So we have the start and end dates that we actually want it to run, but since # we're dealing with a restart, we just want to skip straight to specifying the # duration of the run. sim_days = date2num(old_end) - date2num(new_start) print("Old run was supposed to end %s"%old_end.strftime('%Y-%m-%d %H:%M')) print("New restart claims to begin %s"%new_start.strftime('%Y-%m-%d %H:%M')) print("So the simulation will be run for %g days"%sim_days) sun.conf.set_simulation_duration_days(sim_days) sun.conf.write_config() self.log_arguments(next_dir) def cmd_complete_run(self,incomplete_dir,next_dir,*args): """ setup_completion, then run it specify 'nowait' as an extra argument to queue the run and return """ self.cmd_setup_completion(incomplete_dir,next_dir) self.cmd_run(next_dir,*args) def cmd_continue(self,old_dir,new_dir,interval=None,symlink=True, base_config=None): """ interval: specification of what the simulation period should be symlink: create symbolic links from StartFile in the base_config: if specified, a SunConfig object which will be updated with the right period. Use to submit different settings than are in <old_dir>/suntans.dat """ if self.private_rundata: # should we chain this back to get to the first one? self.rundata_dir = old_dir # determine np from old_dir old_np = self.find_np_from_dir(old_dir) self.np = old_np print("Found np=%i"%self.np) # First step is the non-time varying files # actually, these are typically not that big - a small fraction of # even one step of output, so forget the symlinking and just copy. self.copy_to_datadir(src_dir=old_dir,dest_dir=new_dir,symlink=False) # Second link the storefiles and copy old_dir/suntans.dat over self.setup_startfiles(old_dir,new_dir,symlink=symlink) ## Make any changes to the run time: sun = sunreader.SunReader(new_dir) def_start,def_end = sun.simulation_period() start_date,end_date = parse_interval.parse_interval(interval, default_start = def_start, default_end = def_end) # in this case, it's a restart and we're not allowed to change the start date if start_date != def_start: print(interval) raise Exception("For restarts you can only specify :end_date, :+duration or +duration") # So we have the start and end dates that we actually want it to run, but since # we're dealing with a restart, we just want to skip straight to specifying the # duration of the run. sim_days = date2num(end_date) - date2num(start_date) print("So the simulation will be run for %g days"%sim_days) if base_config: conf = base_config conf.copy_t0(sun.conf) else: conf = sun.conf conf.set_simulation_duration(delta = end_date - start_date) conf.write_config(filename=sun.conf.filename) self.log_arguments(new_dir) self.cmd_replace_forcing(new_dir) def cmd_replace_forcing(self,data_dir): """ Replace the forcing data - this will pick up the fact that it's a restart, and will construct BC data for the whole period (so it actually duplicates the BC data for the simulation period that has already run) removes the old forcing files first, so that we don't overwrite older files that are symlinked in """ for f in glob.glob(os.path.join(data_dir, self.conf.conf_str('BoundaryInput')+"*")): os.unlink(f) gforce = self.global_forcing(datadir=data_dir) gforce.write_boundaries_dat() self.log_arguments(data_dir) def cmd_replace_initcond(self,datadir): sun = sunreader.SunReader(datadir) scalars = sun.scalars() if self.salinity_file() and 'SalinityFile' in scalars: self.salinity_create(datadir) if self.temperature_file() and 'TemperatureFile' in scalars: self.temperature_create(datadir) def cmd_match_spinup(self,spin_dir,new_dir,end_date=None): # self.hydro_spinup_days if self.private_rundata: self.rundata_dir = new_dir self.run_create() # First, load the spinup run to figure out the timing for this run spin_sun = sunreader.SunReader(spin_dir) spin_outputs = date2num(spin_sun.time_zero()) + spin_sun.timeline(units='days',output='grid') ## Figure out the ending time for the transition run if end_date is not None: # new format - YYYYMMDDHHMMSS - or a prefix thereof end_datetime = parse_interval.parse_date_or_interval(end_date) end_absdays = date2num(end_datetime) i = max(searchsorted(spin_outputs,end_absdays)-1,0) end_absdays = spin_outputs[i] else: end_absdays = spin_outputs[-1] end_date = num2date(end_absdays) print("This run will end on %s to match a spinup output time"%(end_date.strftime('%Y-%m-%d %H:%M:%S'))) start_date = end_date - datetime.timedelta( self.hydro_spinup_days ) ## Find a full grid output from the spinup run that can be used to initialize the # transition run i = max(searchsorted(spin_outputs,date2num(start_date))-1,0) start_absdays = spin_outputs[i] start_date = num2date(start_absdays) print("This run will start on %s, to match a spinup output time"%(start_date)) print("Hydro spinup time is %g days. This run will be %g days"%(self.hydro_spinup_days, end_absdays - start_absdays)) # First, copy the non time-varying files: self.copy_to_datadir(new_dir) # Doctor up the suntans.dat file to reflect the period we want: sunconf = sunreader.SunConfig( os.path.join(new_dir, 'suntans.dat') ) sunconf.set_simulation_period(start_date,end_date) sunconf.write_config() # Now setup the initial conditions - for now this is done the same way as # for a spinup run - self.cmd_replace_forcing(new_dir) self.cmd_copy_spin_scalars(spin_dir,new_dir) self.log_arguments(new_dir) def cmd_continue_with_spin(self,trans_dir,spin_dir,new_dir,interval=None): """ trans_dir: the full resolution, transition run (for hydro spinup) spin_dir: the coarse resolution run that provides an updated scalar field new_dir: where the create the combined run. """ if self.private_rundata: self.rundata_dir = trans_dir self.cmd_continue(trans_dir,new_dir,interval,symlink=False) self.cmd_copy_spin_scalars(spin_dir,new_dir) self.log_arguments(new_dir) def cmd_change_dt(self,data_dir,dt): sun = sunreader.SunReader(data_dir) sun.modify_dt(float(dt)) self.log_arguments(data_dir) def cmd_copy_spin_scalars(self,spin_dir,new_dir,unsymlink=True): """ Overwrite scalar initialization in new_dir with values interpolated in space, nearest in time, from spin_dir. if new_dir has StartFiles, those will be used. otherwise, initial salinity will be overwritten. unsymlink: if the StartFiles are symlinked, copy them into a real file same goes for initial salinity """ sun = sunreader.SunReader(new_dir) spin_sun = sunreader.SunReader(spin_dir) ## Do we have StartFiles? start_file_fn = sun.file_path('StartFile',0) if os.path.exists(start_file_fn): print( "Copy_spin_scalars: StartFile exists.") startfile = sunreader.StoreFile(sun,0,startfile=1) my_absdays = date2num( startfile.time() ) startfile.close() mapper = sunreader.spin_mapper(spin_sun=spin_sun, target_sun=sun, target_absdays=my_absdays, scalar='salinity') for proc in range(self.np): if unsymlink: ensure_real_file(sun.file_path('StartFile',proc)) startfile = sunreader.StoreFile(sun,proc,startfile=1) startfile.overwrite_salinity(mapper) startfile.close() else: print("Copy_spin_scalars: no start file - will overwrite salinity initial conditions") read_salinity = sun.conf_int('readSalinity') if read_salinity != 2: print("Modifying suntans.dat: readSalinity %d => %d"%(read_salinity,2)) sun.conf.set_value('readSalinity',2) sun.conf.write_config() # This needs to share code with the copy_salinity functionality. # Maybe one function that's not in either class, that takes a spinup run and # a target grid and date and returns the interpolated salt field. then each # implementation can write it out however they want. mapper = sunreader.spin_mapper(spin_sun=spin_sun, target_sun=sun, target_absdays= date2num(sun.time_zero()), scalar='salinity') if unsymlink: # remove existing files, and they will be recreated for proc in range(sun.num_processors()): fname = sun.file_path("InitSalinityFile",proc) if os.path.exists(fname): print("removing old initial salinity file",fname) os.unlink(fname) sun.write_initial_salinity(mapper,dimensions=3,func_by_index=1) self.log_arguments(new_dir) def cmd_make_shps(self,depth_fn=None): print("Assume that we're running in the directory above 'rundata'") if depth_fn is None: depth_fn = 'rundata/depth.dat.untrimmed' if self.private_rundata: raise Exception("Sorry - make_shps is not currently compatible with private_rundata") g = trigrid.TriGrid(suntans_path='rundata/original_grid') # just the shoreline: g.write_shp('grid-boundaries.shp',overwrite=1) if os.path.exists(depth_fn): ## And some depth contours # Read the untrimmed depth data xyz = loadtxt(depth_fn) cell_depths=xyz[:,2] # Plot a useful set of contours g.write_contours_shp('grid-contours.shp',cell_depths, array([4,5,6,7,8,9,10,12,15,20,25]), overwrite=1) else: print("No depth information - skipping contours") def cmd_make_subdomain_shps(self,datadir): """ Write boundary shapefiles for each of the subdomains in the given data directory. """ sun = sunreader.SunReader(datadir) Nprocs = sun.num_processors() for proc in range(Nprocs): print("Subdomain %d/%d\n"%(proc,Nprocs)) g = sun.grid(proc) g.write_shp(os.path.join(datadir,'grid-boundaries%03i.shp'%proc),overwrite=1) def cmd_plot_datasources(self,datadir): """ Kind of like plot_forcing, but reads each of the datasource files and makes a plot, hoping that the first line is a useful comment """ plotdir = os.path.join(datadir,'plots_datasources') if not os.path.exists(plotdir): os.mkdir( plotdir ) else: for f in os.listdir(plotdir): os.unlink( os.path.join(plotdir,f) ) sun = sunreader.SunReader(datadir) start_date,end_date = sun.simulation_period() for ds_fn in glob.glob(os.path.join(datadir,'datasources','*')): print("Reading datasource %s"%ds_fn) ds = forcing.read_datasource(ds_fn,sun) clf() ds.plot_overview(start_date,end_date) savefig( os.path.join(plotdir,os.path.basename(ds_fn)+".png") ) def cmd_plot_forcing(self,datadir): """ Make plots of all the forcing variables for the run in datadir. This will reload the data, rather than reading from boundaries.dat.* """ plotdir = os.path.join(datadir,'forcing') if not os.path.exists(plotdir): os.mkdir( plotdir ) else: for f in os.listdir(plotdir): os.unlink( os.path.join(plotdir,f) ) sun = sunreader.SunReader(datadir) start_date,end_date = sun.simulation_period() gforce = self.global_forcing( datadir=datadir ) i = 0 for d in gforce.datasources: clf() d.plot_overview(tmin=start_date,tmax=end_date) savefig(os.path.join(plotdir,"datasource%04i.pdf"%i)) i+=1 ##### Scalar releases def scalar_release_regions(self): """ Return closed polygons (assumed closed) representing the release regions. Used for defining how cell scalar value are set during the release (and potentially during grid generation) The linestrings here should *not* repeat the last vertex - they are assumed closed. """ return [] # update start.dat with a scalar release: # before calling this you'd have to do a continue, then this command # will be run in the new run. def process_scalar_release(self,sun,mapper,unsymlink=True,species='temperature'): """ sun: sunreader instance mapper: function of the form f(proc,cell,k) which returns concentration for the given cell unsymlink: if symlinked start files should be copied, rather than editing the original store files. species: 'temperature', 'salinity' for regular scalars 'sediNNN' for suspended sediment concentration in given sediment species 'bedNNN' for bed mass in given layer """ # branch off if this isn't for a regular scalar quantity. if species.find('sedi') == 0: species = int(species[ len('sedi'):]) self.process_ssc_release(sun,mapper,unsymlink,species) return elif species.find('bed') == 0: NL = int(species[ len('bed'):]) self.process_bed_release(sun,mapper,unsymlink,NL) return start_file_fn = sun.file_path('StartFile',0) if not os.path.exists(start_file_fn): raise Exception("scalar_release:: failed to find StartFile %s."%start_file_fn) for proc in range(self.np): if unsymlink: ensure_real_file(sun.file_path('StartFile',proc)) startfile = sunreader.StoreFile(sun,proc,startfile=1) if species=='temperature': startfile.overwrite_temperature(mapper) elif species=='salinity': startfile.overwrite_salinity(mapper) else: raise Exception("unknown species %s"%species) startfile.close() print("Overwrote %s"%species) def process_bed_release(self,sun,mapper,unsymlink,layer): """ see process_scalar_release. even though the layer is specified, the mapper must still accept a k argument, which will be the layer""" print("Will write over sediment bed layer %d"%layer) for proc in range(self.np): start_file_fn = sunreader.SediStoreFile.filename(sun,proc,startfile=1) if unsymlink: ensure_real_file(start_file_fn) sedi_startfile = sunreader.SediStoreFile(sun,proc,startfile=1) sedi_startfile.overwrite_bed(mapper,layer=layer) sedi_startfile.close() def process_ssc_release(self,sun,mapper,unsymlink,species): """ see process_scalar_release """ print("Will write over suspended sediment concentration for species %d"%species) for proc in range(self.np): start_file_fn = sunreader.SediStoreFile.filename(sun,proc,startfile=1) if unsymlink: ensure_real_file(start_file_fn) sedi_startfile = sunreader.SediStoreFile(sun,proc,startfile=1) sedi_startfile.overwrite_ssc(mapper,species=species) sedi_startfile.close() def cmd_scalar_release_polygon(self,datadir,n=0,unsymlink=True,species='temperature'): """ Defaults to the first release region datadir: the restart to operate on (currently does not support release with initial conditions) n: id of the scalar release region unsymlink: should symlinked start.dat files be copied first """ n = int(n) # cast to float because shapely is not so smart about that... release_region = array( self.scalar_release_regions()[n],float64 ) # make it into an easily queryable polygon: poly = geometry.Polygon(release_region) sun = sunreader.SunReader(datadir) print("scalar poly is",release_region) print(" with area ",poly.area) def mapper(proc,cell,k): g = sun.grid(proc) pnt = geometry.Point( g.vcenters()[cell]) if poly.contains(pnt): print("wrote some temp") return 1.0 else: return 0.0 return self.process_scalar_release(sun,mapper=mapper,unsymlink=unsymlink,species=species) def cmd_scalar_release_gaussian_2D(self,datadir,xy,sd,unsymlink=True,species='temperature'): """ create a 2D gaussian plume, centered at the given x,y point (which should be given as either a [x,y] list, or a string <x>,<y>. sd is the standard deviation [sd_x,sd_y], and may be infinite in one dimension. if a third value is included for sd, it will be used as the peak value of the distribution, otherwise 1.0 is assumed. """ if type(xy) == str: xy = [float(s) for s in xy.split(',')] if type(sd) == str: sd = [float(s) for s in sd.split(',')] if len(sd) == 3: peak = sd[2] else: peak = 1.0 sun = sunreader.SunReader(datadir) def mapper(proc,cell,k): g = sun.grid(proc) pnt = g.vcenters()[cell] return peak * exp( -(pnt[0]-xy[0])**2 / (2*sd[0]**2) - (pnt[1]-xy[1])**2 / (2*sd[1]**2) ) return self.process_scalar_release(sun,mapper,unsymlink,species) def cmd_batch_continue(self,base_dir,batch_dir,interval): """ base_dir - a completed run, from which this one will continue batch_dir - the name for the new runs, including trailing two digit id for the first of the continuations. interval - how long each continuation should be. probably for ponds this should be +2d """ if not self.run_can_be_continued(base_dir): print("Sorry - the base run does not appear to be complete.") return import re m = re.match('(.*[^0-9])([0-9]+)',batch_dir) prefix = m.group(1) ndigits = len(m.group(2)) starting_index = int(m.group(2)) index = starting_index prev_dir = base_dir while 1: cont_dir = prefix + "%0*i"%(ndigits,index) print("Checking status of %s"%cont_dir) if not self.run_has_completed(cont_dir): print("Preparing %s for run"%cont_dir) self.cmd_continue(prev_dir,cont_dir,interval) print("Running") self.cmd_run(cont_dir) if not self.run_has_completed(cont_dir): print("That run appears not to have finished. Bailing out") break else: print("Run %s appears to have already run"%cont_dir) index += 1 prev_dir = cont_dir def cmd_batch(self,datadir,interval): """ A combination of initialize_run and batch_continue - datadir is taken as the base name, and will have a five digit index appended """ initial_dir = "%s00000"%datadir continue_dir = "%s00001"%datadir self.cmd_initialize_run(initial_dir,interval) self.cmd_run(initial_dir) sun = sunreader.SunReader(initial_dir) dstart,dend = sun.simulation_period() interval_days = date2num(dend) - date2num(dstart) interval_str = "+%fd"%interval_days self.cmd_batch_continue(initial_dir,continue_dir,interval_str) def cmd_resymlink(self,*datadirs): """ for each of the given datadirs, see if there are chained runs where constant files can be turned back into symlinks. tries to symlink back to the original file, not just the previous run """ for datadir in datadirs: print("Checking %s"%datadir) sun = sunreader.SunReader(datadir) chain = sun.chain_restarts() if len(chain) <= 1: print("No chain.") continue
{ "repo_name": "rustychris/stompy", "path": "stompy/model/suntans/domain.py", "copies": "1", "size": "101238", "license": "mit", "hash": -1771916440854708200, "line_mean": 40.8338842975, "line_max": 134, "alpha_frac": 0.5682747585, "autogenerated": false, "ratio": 3.859773533112204, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9855205709032457, "avg_score": 0.014568516515949412, "num_lines": 2420 }
"""AfkMover Module for the Teamspeak3 Bot.""" from threading import Thread import sys import traceback from Moduleloader import * import ts3.Events as Events import threading import ts3 import Bot from ts3.utilities import TS3Exception afkMover = None afkStopper = threading.Event() bot = None autoStart = True channel_name = "AFK" @command('startafk', 'afkstart', 'afkmove',) def start_afkmover(sender=None, msg=None): """ Start the AfkMover by clearing the afkStopper signal and starting the mover. """ global afkMover if afkMover is None: afkMover = AfkMover(afkStopper, bot.ts3conn) afkStopper.clear() afkMover.start() @command('stopafk', 'afkstop') def stop_afkmover(sender=None, msg=None): """ Stop the AfkMover by setting the afkStopper signal and undefining the mover. """ global afkMover afkStopper.set() afkMover = None @command('afkgetclientchannellist') def get_afk_list(sender=None, msg=None): """ Get afkmover saved client channels. Mainly for debugging. """ if afkMover is not None: Bot.send_msg_to_client(bot.ts3conn, sender, str(afkMover.client_channels)) @event(Events.ClientLeftEvent,) def client_left(event): """ Clean up leaving clients. """ # Forgets clients that were set to afk and then left if afkMover is not None: if str(event.client_id) in afkMover.client_channels: del afkMover.client_channels[str(event.client_id)] @setup def setup(ts3bot,channel="AFK"): global bot,channel_name bot = ts3bot channel_name = channel if autoStart: start_afkmover() @exit def afkmover_exit(): global afkMover afkStopper.set() afkMover.join() afkMover = None class AfkMover(Thread): """ AfkMover class. Moves clients set to afk another channel. """ logger = logging.getLogger("afk") logger.propagate = 0 logger.setLevel(logging.WARNING) file_handler = logging.FileHandler("afk.log", mode='a+') formatter = logging.Formatter('AFK Logger %(asctime)s %(message)s') file_handler.setFormatter(formatter) logger.addHandler(file_handler) logger.info("Configured afk logger") logger.propagate = 0 def __init__(self, event, ts3conn): """ Create a new AfkMover object. :param event: Event to signalize the AfkMover to stop moving. :type event: threading.Event :param ts3conn: Connection to use :type: TS3Connection """ Thread.__init__(self) self.stopped = event self.ts3conn = ts3conn self.afk_channel = self.get_afk_channel(channel_name) self.client_channels = {} self.afk_list = None if self.afk_channel is None: AfkMover.logger.error("Could not get afk channel") def run(self): """ Thread run method. Starts the mover. """ AfkMover.logger.info("AFKMove Thread started") try: self.auto_move_all() except: self.logger.exception("Exception occured in run:") def update_afk_list(self): """ Update the list of clients. """ try: self.afk_list = self.ts3conn.clientlist(["away"]) AfkMover.logger.debug("Awaylist: " + str(self.afk_list)) except TS3Exception: AfkMover.logger.exception("Error getting away list!") self.afk_list = list() def get_away_list(self): """ Get list of clients with afk status. :return: List of clients that are set to afk. """ if self.afk_list is not None: AfkMover.logger.debug(str(self.afk_list)) awaylist = list() for client in self.afk_list: AfkMover.logger.debug(str(self.afk_list)) if "cid" not in client.keys(): AfkMover.logger.error("Client without cid!") AfkMover.logger.error(str(client)) elif "client_away" in client.keys() and client.get("client_away", '0') == '1' and int(client.get("cid", '-1')) != \ int(self.afk_channel): awaylist.append(client) return awaylist else: AfkMover.logger.error("Clientlist is None!") return list() def get_back_list(self): """ Get list of clients in the afk channel, but not away. :return: List of clients who are back from afk. """ clientlist = [client for client in self.afk_list if client.get("client_away", '1') == '0' and int(client.get("cid", '-1')) == int(self.afk_channel)] return clientlist def get_afk_channel(self, name="AFK"): """ Get the channel id of the channel specified by name. :param name: Channel name :return: Channel id """ try: channel = self.ts3conn.channelfind(name)[0].get("cid", '-1') except TS3Exception: AfkMover.logger.exception("Error getting afk channel") raise return channel def move_to_afk(self, clients): """ Move clients to the afk_channel. :param clients: List of clients to move. """ AfkMover.logger.info("Moving clients to afk!") for client in clients: AfkMover.logger.info("Moving somebody to afk!") AfkMover.logger.debug("Client: " + str(client)) try: self.ts3conn.clientmove(self.afk_channel, int(client.get("clid", '-1'))) except TS3Exception: AfkMover.logger.exception("Error moving client! Clid=" + str(client.get("clid", '-1'))) self.client_channels[client.get("clid", '-1')] = client.get("cid", '0') AfkMover.logger.debug("Moved List after move: " + str(self.client_channels)) def move_all_afk(self): """ Move all afk clients. """ try: afk_list = self.get_away_list() self.move_to_afk(afk_list) except AttributeError: AfkMover.logger.exception("Connection error!") def move_all_back(self): """ Move all clients who are back from afk. """ back_list = self.get_back_list() AfkMover.logger.debug("Moving clients back") AfkMover.logger.debug("Backlist is: " + str(back_list)) AfkMover.logger.debug("Saved channel list keys are:" + str(self.client_channels.keys()) + "\n") for client in back_list: if client.get("clid", -1) in self.client_channels.keys(): AfkMover.logger.info("Moving a client back!") AfkMover.logger.debug("Client: " + str(client)) AfkMover.logger.debug("Saved channel list keys:" + str(self.client_channels)) self.ts3conn.clientmove(self.client_channels.get(client.get("clid", -1)), int(client.get("clid", '-1'))) del self.client_channels[client.get("clid", '-1')] def auto_move_all(self): """ Loop move functions until the stop signal is sent. """ while not self.stopped.wait(2.0): AfkMover.logger.debug("Afkmover running!") self.update_afk_list() try: self.move_all_back() self.move_all_afk() except: AfkMover.logger.error("Uncaught exception:" + str(sys.exc_info()[0])) AfkMover.logger.error(str(sys.exc_info()[1])) AfkMover.logger.error(traceback.format_exc()) AfkMover.logger.error("Saved channel list keys are:" + str(self.client_channels.keys()) + "\n") AfkMover.logger.warning("AFKMover stopped!") self.client_channels = {}
{ "repo_name": "Murgeye/teamspeak3-python-bot", "path": "modules/afkmover.py", "copies": "1", "size": "8167", "license": "apache-2.0", "hash": -8310645126664280000, "line_mean": 33.5086956522, "line_max": 131, "alpha_frac": 0.5655687523, "autogenerated": false, "ratio": 3.703854875283447, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4769423627583447, "avg_score": null, "num_lines": null }
"""A flask API for generating (and retrieving) player details! Usage: api.py run [--no-debug] [--port=<p>] [--host=<h>] api.py (-h | --help) Options: -h --help Show this screen --no-debug Don't add debug=True when running --port=<p> The port to use [default: 5000] --host=<h> The host (address to listen on) [default: 0.0.0.0] """ import logging import random import docopt import flask from random_cricket_profiles import countries, player_generator, players, prettyint logging.basicConfig(level=logging.INFO) app = flask.Flask(__name__) app.config.from_object("random_cricket_profiles.settings.Config") generator = None def get_player_generator(): global generator filename = app.config["DATA_FILENAME"] min_profile_length = app.config["MIN_PROFILE_LENGTH"] if generator is None: sample_players = players.load_players(filename) generator = player_generator.PlayerGenerator(sample_players, min_profile_length) return generator @app.route("/p/<country_code>/<seed_string>") def player(country_code, seed_string): seed = prettyint.decode(seed_string) pg = get_player_generator() player, _seed = pg.generate(country_code=country_code, seed=seed) response = { "country": country_code, "firstnames": player.firstnames, "surname": player.surname, "profile": player.profile } return flask.jsonify(response) @app.route("/p/random") def random_player(): country = random.choice(countries.COUNTRIES) country_code = country.country_code seed = random.getrandbits(64) seed_string = prettyint.encode(seed) url = flask.url_for("player", country_code=country_code, seed_string=seed_string) return flask.redirect(url) if __name__ == "__main__": args = docopt.docopt(__doc__) if args.get("run"): port = int(args["--port"]) host = args["--host"] debug = not bool(args.get("--no-debug")) app.run(host=host, port=port, debug=debug)
{ "repo_name": "sujaymansingh/random_cricket_profiles", "path": "random_cricket_profiles/api.py", "copies": "1", "size": "2049", "license": "mit", "hash": -4866144102629947000, "line_mean": 25.6103896104, "line_max": 88, "alpha_frac": 0.6505612494, "autogenerated": false, "ratio": 3.5449826989619377, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46955439483619377, "avg_score": null, "num_lines": null }
"""A flask app for auto deploying Kubeflow. TODO(jlewi): Rather than use the multiprocessing package it might make sense just to run the server and reconciler in separate containers. They are already communicating through the filesystem so using multi-processing might just be complicating things. One problem we have right now is that exceptions in the reconciler aren't propogated to the server. """ import datetime from dateutil import parser as date_parser import fire import glob import logging import os import yaml from kubeflow.testing import gcp_util from kubeflow.testing import kf_logging from kubeflow.testing.auto_deploy import blueprint_reconciler from kubeflow.testing.auto_deploy import util import flask _deployments_dir = None app = flask.Flask(__name__) _deployments_dir = None app = flask.Flask(__name__) def _get_deployments(): """Return dictionary describing deployment manager deployments.""" match = os.path.join(_deployments_dir, "deployments.*") files = glob.glob(match) items = [] if not files: logging.info(f"No matching files for {match}") else: files = sorted(files) latest = files[-1] logging.info(f"Reading from {latest}") with open(os.path.join(latest)) as hf: deployments = yaml.load(hf) for v, deployments_list in deployments.items(): for d in deployments_list: create_time = date_parser.parse(d["create_time"]) age = datetime.datetime.now(tz=create_time.tzinfo) - create_time manifests_commit = d["labels"].get(util.MANIFESTS_COMMIT_LABEL, "") row = { "pipeline_run": "", "pipeline_run_url": "", "version": v, "deployment_name": d["deployment_name"], "creation_time": d.get("create_time", ""), "age": f"{age}", "manifests_git": manifests_commit, "manifests_url": (f"https://github.com/kubeflow/manifests/tree/" f"{manifests_commit}"), "kfctl_git": d["labels"].get("kfctl-git", ""), "endpoint": f"https://{d['deployment_name']}.endpoints." f"kubeflow-ci-deployment.cloud.goog", # TODO(jlewi): We are hardcoding the project and zone. "gcloud_command": (f"gcloud --project=kubeflow-ci-deployment " f"container clusters get-credentials " f"--zone={d['zone']} " f"{d['deployment_name']}") } labels = [] for label_key, label_value in d["labels"].items(): labels.append(f"{label_key}={label_value}") row["labels"] = ", ".join(labels) items.append(row) return items def _get_blueprints(): """Return dictionary describing blueprints.""" match = os.path.join(_deployments_dir, "clusters.*") files = glob.glob(match) items = [] if not files: logging.info(f"No files matched {match}") return items files = sorted(files) latest = files[-1] logging.info(f"Reading from {latest}") with open(os.path.join(latest)) as hf: deployments = yaml.load(hf) for _, clusters in deployments.items(): for c in clusters: create_time = date_parser.parse(c["metadata"]["creationTimestamp"]) age = datetime.datetime.now(tz=create_time.tzinfo) - create_time commit = c["metadata"]["labels"].get( blueprint_reconciler.BLUEPRINT_COMMIT_LABEL, "") pipeline_run = c["metadata"]["labels"].get("tekton.dev/pipelineRun", "") group = c["metadata"]["labels"].get( blueprint_reconciler.GROUP_LABEL, blueprint_reconciler.UNKNOWN_GROUP) name = c["metadata"]["name"] location = c["spec"]["location"] location_flag = gcp_util.location_to_type(location) row = { "version": group, "deployment_name": name, "creation_time": create_time, "age": f"{age}", "manifests_git": commit, # TODO(jlewi):We shouldn't hardcode the url we should add it # as annotation. "manifests_url": (f"https://github.com/kubeflow/gcp-blueprints/tree/" f"{commit}"), "kfctl_git": "", "pipeline_run": pipeline_run, # TODO(jlewi): We shouldn't hardcode endpoint. "pipline_run_url": (f"https://kf-ci-v1.endpoints.kubeflow-ci.cloud.goog/" f"tekton/#/namespaces/auto-deploy/pipelineruns/" f"{pipeline_run}"), # TODO(jlewi): Don't hard code the project "endpoint": (f"https://{name}.endpoints." f"kubeflow-ci-deployment.cloud.goog"), # TODO(jlewi): We are hardcoding the project and zone. "gcloud_command": (f"gcloud --project=kubeflow-ci-deployment " f"container clusters get-credentials " f"--{location_flag}={location} " f"{name}") } labels = [] for label_key, label_value in c["metadata"]["labels"].items(): labels.append(f"{label_key}={label_value}") row["labels"] = ", ".join(labels) items.append(row) return items @app.route("/") def auto_deploy_status(): """Return the status of the auto deployments.""" logging.info("Handle auto_deploy_status") try: logging.info("Get deployments") items = _get_deployments() logging.info("Get blueprints") blueprints = _get_blueprints() items.extend(blueprints) # Define a key function for the sort. # We want to sort by version and age def key_func(i): # We want unknown version to appear last # so we ad a prefix if i["version"] == "unknown": prefix = "z" else: prefix = "a" return f"{prefix}-{i['version']}-{i['age']}" items = sorted(items, key=key_func) # Return the HTML logging.info("Render template") result = flask.render_template("index.html", title="Kubeflow Auto Deployments", items=items) # It looks like when flask debug mode is off the Flask provides unhelpful log # messages in the logs. In debug mode the actual exception is returned in # the html response. except Exception as e: logging.error(f"Exception occured: {e}") raise return result class AutoDeployServer: def __init__(self): self._deployments_queue = None self._deployments_dir = None def serve(self, template_folder, deployments_dir=None, port=None): global _deployments_dir # pylint: disable=global-statement global app # pylint: disable=global-statement app.template_folder = template_folder # make sure things reload FLASK_DEBUG = os.getenv("FLASK_DEBUG", "false").lower() # Need to convert it to boolean if FLASK_DEBUG in ["true", "t"]: # pylint: disable=simplifiable-if-statement FLASK_DEBUG = True else: FLASK_DEBUG = False logging.info(f"FLASK_DEBUG={FLASK_DEBUG}") if FLASK_DEBUG: app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True _deployments_dir = deployments_dir logging.info(f"Deployments will be read from {self._deployments_dir}") app.run(debug=FLASK_DEBUG, host='0.0.0.0', port=port) if __name__ == '__main__': # Emit logs in json format. This way we can do structured logging # and we can query extra fields easily in stackdriver and bigquery. json_handler = logging.StreamHandler() json_handler.setFormatter(kf_logging.CustomisedJSONFormatter()) logger = logging.getLogger() logger.addHandler(json_handler) logger.setLevel(logging.INFO) fire.Fire(AutoDeployServer)
{ "repo_name": "kubeflow/testing", "path": "py/kubeflow/testing/auto_deploy/server.py", "copies": "1", "size": "7644", "license": "apache-2.0", "hash": -7030352931666305000, "line_mean": 32.5263157895, "line_max": 84, "alpha_frac": 0.6225798012, "autogenerated": false, "ratio": 3.7785467128027683, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9841643504064259, "avg_score": 0.011896601987701835, "num_lines": 228 }
"""A Flask app for redirecting documentation from the root / URL.""" import json from flask import Flask, make_response, redirect, request app = Flask(__name__) PRODUCTION_DOMAIN = 'readthedocs.org' @app.route('/') def redirect_front(): version = 'latest' language = 'en' single_version = False SUBDOMAIN = CNAME = False print "Got request {host}".format(host=request.host) if PRODUCTION_DOMAIN in request.host: SUBDOMAIN = True slug = request.host.split('.')[0] path = "/home/docs/checkouts/readthedocs.org/user_builds/{slug}/metadata.json".format(slug=slug) else: try: cname = request.host.split(':')[0] except: cname = request.host CNAME = True path = "/home/docs/checkouts/readthedocs.org/public_cname_project/{cname}/metadata.json".format(cname=cname) try: json_obj = json.load(file(path)) version = json_obj['version'] language = json_obj['language'] single_version = json_obj['single_version'] except Exception, e: print e if single_version: if SUBDOMAIN: sendfile = "/user_builds/{slug}/translations/{language}/{version}/".format(slug=slug, language=language, version=version) elif CNAME: sendfile = "/public_cname_root/{cname}/".format(cname=cname, language=language, version=version) print "Redirecting {host} to {sendfile}".format(host=request.host, sendfile=sendfile) return make_response('', 303, {'X-Accel-Redirect': sendfile}) else: url = '/{language}/{version}/'.format(language=language, version=version) print "Redirecting {host} to {url}".format(host=request.host, url=url) return redirect(url) if __name__ == '__main__': app.run()
{ "repo_name": "pombredanne/readthedocs.org", "path": "deploy/flask-redirects.py", "copies": "1", "size": "1811", "license": "mit", "hash": -1069365871930910500, "line_mean": 31.9272727273, "line_max": 133, "alpha_frac": 0.6289342904, "autogenerated": false, "ratio": 3.788702928870293, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9906724379598644, "avg_score": 0.002182567934329958, "num_lines": 55 }
"""A Flask script to manage all the routines of the application""" from flask_script import Manager from servmon import app from migrations import machine_data_seed import subprocess # Enable debugging mode for development purposes app.config['DEBUG'] = True app.config['DB'] = 'test_database' manager = Manager(app) @manager.command def makerst(): """Generate rst files (may not be properly formatted) for APIs and common utils in docs folder DO NOT RUN THIS PROCESS UNLESS ABSOLUTELY NECESSARY IT WILL OVERWRITE CHANGES MADE TO RST FILES """ subprocess.run(['make', '-C', 'docs', 'rst']) @manager.command def makedoc(): """Generate HTML documentation for APIs and common utils in docs/_build/html""" subprocess.run(['make', '-C', 'docs', 'html']) @manager.command def migrate(): """Seed the MongoDB database with test data""" machine_data_seed.up() @manager.command def reset_migrate(): """Reset the MongoDB database migrations""" machine_data_seed.down() @manager.command def test(): """Execute test cases""" subprocess.run('pytest') if __name__ == '__main__': manager.run()
{ "repo_name": "hpsuenaa/servmon", "path": "manage.py", "copies": "1", "size": "1146", "license": "mit", "hash": -7183311366772029000, "line_mean": 23.9130434783, "line_max": 98, "alpha_frac": 0.6928446771, "autogenerated": false, "ratio": 3.720779220779221, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4913623897879221, "avg_score": null, "num_lines": null }
# A flat-bottom harmonic potential on the center of mass # that keeps the system within a cylinder # with principal axis along the direction (0,0,1). from MMTK.ForceFields.ForceField import ForceField from MMTK_cylinder import CylinderTerm import numpy as N # Exactly the same as the pure Python version class CylinderForceField(ForceField): """ Flat-bottom harmonic potential for a cylinder """ def __init__(self, origin, direction, max_Z, max_R, name='cylinder'): """ @param origin: the origin of the principal axis of the cylinder @type origin: {numpy.array} @param direction: the direction of the principal axis of the cylinder @type direction: {numpy.array} @param max_Z: the maximal value of the projection along the principal axis @type max_Z: C{float} @param max_R: the maximal value orthogonal to the principal axis @type max_R: C{float} """ # Store arguments that recreate the force field from a pickled # universe or from a trajectory. self.arguments = (origin, direction, max_Z, max_R) # Initialize the ForceField class, giving a name to this one. ForceField.__init__(self, name) # Store the parameters for later use. self.origin = origin self.direction = direction self.max_Z = max_Z self.max_R = max_R self.name = name if not ((self.direction[0] == 0.0) and (self.direction[1] == 0.0) and (self.direction[2] == 1.0)): raise Exception("For efficiency, principal axis must be along (0,0,1)") # Calculate the cylinder volume self.volume = N.pi*(self.max_R*self.max_R)*(self.max_Z - self.origin[2]) # The following method is called by the energy evaluation engine # to inquire if this force field term has all the parameters it # requires. This is necessary for interdependent force field # terms. In our case, we just say "yes" immediately. def ready(self, global_data): return True # The following method is returns a dictionary of parameters for # the force field def evaluatorParameters(self, universe, subset1, subset2, global_data): return {self.name+' origin': self.center, self.name+' max Z': self.max_Z, self.name+' max R': self.max_R} # The following method is called by the energy evaluation engine # to obtain a list of the low-level evaluator objects (the C routines) # that handle the calculations. def evaluatorTerms(self, universe, subset1, subset2, global_data): # The subset evaluation mechanism does not make much sense for # this force field, so we just signal an error if someone # uses it by accident. if subset1 is not None or subset2 is not None: raise ValueError("sorry, no subsets here") # Here we pass all the parameters to the code # that handles energy calculations. return [CylinderTerm(universe, self.origin, self.direction, self.max_Z, self.max_R, self.name)] def randomPoint(self): """ Returns a random point within the cylinder """ z = N.random.uniform() (x,y) = self._randomPointInCircle() return (x*self.max_R + self.origin[0], y*self.max_R + self.origin[1], z*(self.max_Z - self.origin[2]) + self.origin[2]) def _randomPointInCircle(self): """ Returns a random point within a unit circle """ r2 = 2 while r2 > 1: (x,y) = N.random.uniform(size=2) r2 = x*x + y*y return (x,y)
{ "repo_name": "CCBatIIT/AlGDock", "path": "AlGDock/ForceFields/Cylinder/Cylinder.py", "copies": "1", "size": "3711", "license": "mit", "hash": 5017642157557358000, "line_mean": 38.9032258065, "line_max": 82, "alpha_frac": 0.6257073565, "autogenerated": false, "ratio": 3.947872340425532, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.013083350387641782, "num_lines": 93 }
# A flat-bottom harmonic potential on the center of mass # that keeps the system within a cylinder # with principal axis along the direction (1,0,0). from MMTK.ForceFields.ForceField import ForceField from MMTK_cylinder import CylinderTerm import numpy as N # Exactly the same as the pure Python version class CylinderForceField(ForceField): """ Flat-bottom harmonic potential for a cylinder """ def __init__(self, origin, direction, max_X, max_R, name='cylinder'): """ @param origin: the origin of the principal axis of the cylinder @type origin: {numpy.array} @param direction: the direction of the principal axis of the cylinder @type direction: {numpy.array} @param max_X: the maximal value of the projection along the principal axis @type max_X: C{float} @param max_R: the maximal value orthogonal to the principal axis @type max_R: C{float} """ # Store arguments that recreate the force field from a pickled # universe or from a trajectory. self.arguments = (origin, direction, max_X, max_R) # Initialize the ForceField class, giving a name to this one. ForceField.__init__(self, name) # Store the parameters for later use. self.origin = origin self.direction = direction self.max_X = max_X self.max_R = max_R self.name = name if not ((self.direction[0] == 1.0) and (self.direction[1] == 0.0) and (self.direction[2] == 0.0)): raise Exception("For efficiency, principal axis must be along (1,0,0)") # Calculate the cylinder volume self.volume = N.pi*(self.max_R*self.max_R)*self.max_X # The following method is called by the energy evaluation engine # to inquire if this force field term has all the parameters it # requires. This is necessary for interdependent force field # terms. In our case, we just say "yes" immediately. def ready(self, global_data): return True # The following method is returns a dictionary of parameters for # the force field def evaluatorParameters(self, universe, subset1, subset2, global_data): return {self.name+' origin': self.center, self.name+' max X': self.max_X, self.name+' max R': self.max_R} # The following method is called by the energy evaluation engine # to obtain a list of the low-level evaluator objects (the C routines) # that handle the calculations. def evaluatorTerms(self, universe, subset1, subset2, global_data): # The subset evaluation mechanism does not make much sense for # this force field, so we just signal an error if someone # uses it by accident. if subset1 is not None or subset2 is not None: raise ValueError("sorry, no subsets here") # Here we pass all the parameters to the code # that handles energy calculations. return [CylinderTerm(universe, self.origin, self.direction, self.max_X, self.max_R, self.name)] def randomPoint(self): """ Returns a random point within the cylinder """ x = N.random.uniform() (y,z) = self._randomPointInCircle() return (x*self.max_X + self.origin[0], y*self.max_R + self.origin[1], z*self.max_R + self.origin[2]) def _randomPointInCircle(self): """ Returns a random point within a unit circle """ r2 = 2 while r2 > 1: (x,y) = N.random.uniform(size=2) r2 = x*x + y*y return (x,y)
{ "repo_name": "luizcieslak/AlGDock", "path": "AlGDock/ForceFields/Cylinder/Cylinder.py", "copies": "2", "size": "3673", "license": "mit", "hash": 1299190452565979600, "line_mean": 38.4946236559, "line_max": 82, "alpha_frac": 0.6261911244, "autogenerated": false, "ratio": 3.966522678185745, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5592713802585745, "avg_score": null, "num_lines": null }
# A flat-bottom harmonic potential on the center of mass # that keeps the system within a sphere from MMTK.ForceFields.ForceField import ForceField from MMTK_sphere import SphereTerm import numpy as N # Exactly the same as the pure Python version class SphereForceField(ForceField): """ Flat-bottom harmonic potential for a sphere """ def __init__(self, center, max_R, name='Sphere'): """ @param center: the center of the principal axis of the sphere @type center: {numpy.array} @param max_R: the maximal value orthogonal to the principal axis @type max_R: C{float} """ # Store arguments that recreate the force field from a pickled # universe or from a trajectory. self.arguments = (center, max_R) # Initialize the ForceField class, giving a name to this one. ForceField.__init__(self, name) # Store the parameters for later use. self.center = center self.max_R = max_R self.name = name # Calculate the sphere volume self.volume = 4./3.*N.pi*(self.max_R*self.max_R*self.max_R) # The following method is called by the energy evaluation engine # to inquire if this force field term has all the parameters it # requires. This is necessary for interdependent force field # terms. In our case, we just say "yes" immediately. def ready(self, global_data): return True # The following method is returns a dictionary of parameters for # the force field def evaluatorParameters(self, universe, subset1, subset2, global_data): return {self.name+' center': self.center, self.name+' max R': self.max_R} # The following method is called by the energy evaluation engine # to obtain a list of the low-level evaluator objects (the C routines) # that handle the calculations. def evaluatorTerms(self, universe, subset1, subset2, global_data): # The subset evaluation mechanism does not make much sense for # this force field, so we just signal an error if someone # uses it by accident. if subset1 is not None or subset2 is not None: raise ValueError("sorry, no subsets here") # Here we pass all the parameters to the code # that handles energy calculations. return [SphereTerm(universe, self.center, self.max_R, self.name)] def randomPoint(self): """ Returns a random point within the sphere """ (x,y,z) = self._randomPointInSphere() return (x*self.max_R + self.center[0], y*self.max_R + self.center[1], z*self.max_R + self.center[2]) def _randomPointInSphere(self): """ Returns a random point within a unit circle """ r2 = 2 while r2 > 1: (x,y,z) = N.random.uniform(size=3) r2 = x*x + y*y + z*z return (x,y,z)
{ "repo_name": "luizcieslak/AlGDock", "path": "AlGDock/ForceFields/Sphere/Sphere.py", "copies": "2", "size": "2929", "license": "mit", "hash": 2064659207347125500, "line_mean": 36.0759493671, "line_max": 75, "alpha_frac": 0.6374189143, "autogenerated": false, "ratio": 3.958108108108108, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5595527022408108, "avg_score": null, "num_lines": null }
# A flat-bottom harmonic potential on the center of mass # that keeps the system within a sphere import AlGDock from MMTK.ForceFields.ForceField import ForceField from MMTK_sphere import SphereTerm import numpy as N # Exactly the same as the pure Python version class SphereForceField(ForceField): """ Flat-bottom harmonic potential for a sphere """ def __init__(self, center, max_R, name='Sphere'): """ @param center: the center of the principal axis of the sphere @type center: {numpy.array} @param max_R: the maximal value orthogonal to the principal axis @type max_R: C{float} """ # Store arguments that recreate the force field from a pickled # universe or from a trajectory. self.arguments = (center, max_R) # Initialize the ForceField class, giving a name to this one. ForceField.__init__(self, name) # Store the parameters for later use. self.center = center self.max_R = max_R self.name = name # Calculate the sphere volume self.volume = 4./3.*N.pi*(self.max_R*self.max_R*self.max_R) # The following method is called by the energy evaluation engine # to inquire if this force field term has all the parameters it # requires. This is necessary for interdependent force field # terms. In our case, we just say "yes" immediately. def ready(self, global_data): return True # The following method is returns a dictionary of parameters for # the force field def evaluatorParameters(self, universe, subset1, subset2, global_data): return {self.name+' center': self.center, self.name+' max R': self.max_R} # The following method is called by the energy evaluation engine # to obtain a list of the low-level evaluator objects (the C routines) # that handle the calculations. def evaluatorTerms(self, universe, subset1, subset2, global_data): # The subset evaluation mechanism does not make much sense for # this force field, so we just signal an error if someone # uses it by accident. if subset1 is not None or subset2 is not None: raise ValueError("sorry, no subsets here") # Here we pass all the parameters to the code # that handles energy calculations. return [SphereTerm(universe, self.center, self.max_R, self.name)] def randomPoint(self): """ Returns a random point within the sphere """ (x,y,z) = self._randomPointInSphere() return (x*self.max_R + self.center[0], y*self.max_R + self.center[1], z*self.max_R + self.center[2]) def _randomPointInSphere(self): """ Returns a random point within a unit circle """ r2 = 2 while r2 > 1: (x,y,z) = N.random.uniform(size=3) r2 = x*x + y*y + z*z return (x,y,z)
{ "repo_name": "CCBatIIT/AlGDock", "path": "AlGDock/ForceFields/Sphere/Sphere.py", "copies": "1", "size": "2944", "license": "mit", "hash": 7196840162492728000, "line_mean": 35.8, "line_max": 75, "alpha_frac": 0.6385869565, "autogenerated": false, "ratio": 3.9516778523489933, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9946443538065513, "avg_score": 0.028764254156696017, "num_lines": 80 }
"""A Flavor reflects a specialization of a base install, the default being BioLinux. If you want to create a new specialization (say for your own server), the recommended procedure is to choose an existing base install (Edition) and write a Flavor. When your Flavor is of interest to other users, it may be a good idea to commit it to the main project (in ./contrib/flavor). Other (main) flavors can be found in this directory and in ./contrib/flavors """ class Flavor: """Base class. Every flavor derives from this """ def __init__(self, env): self.name = "Base Flavor - no overrides" # should override this self.short_name = "" self.env = env self.check_distribution() def rewrite_config_items(self, name, items): """Generic hook to rewrite a list of configured items. Can define custom dispatches based on name: packages, custom, python, ruby, perl """ return items def check_distribution(self): """Ensure the distribution matches an expected type for this edition. Base supports multiple distributions. """ pass def check_packages_source(self): """Override for check package definition file before updating """ pass def rewrite_apt_sources_list(self, sources): """Allows editions to modify the sources list """ return sources def rewrite_apt_preferences(self, preferences): """Allows editions to modify the apt preferences policy file """ return preferences def rewrite_apt_automation(self, package_info): """Allows editions to modify the apt automation list """ return package_info def rewrite_apt_keys(self, standalone, keyserver): """Allows editions to modify key list""" return standalone, keyserver def apt_upgrade_system(self, env=None): """Upgrade system through apt - so this behaviour can be overridden """ env.safe_sudo("apt-get -y --force-yes upgrade") def post_install(self): """Add scripts for starting FreeNX and CloudMan. """ pass class Minimal(Flavor): def __init__(self, env): Flavor.__init__(self, env) self.name = "Minimal Flavor" self.short_name = "minimal" def rewrite_config_items(self, name, items): """Generic hook to rewrite a list of configured items. Can define custom dispatches based on name: packages, custom, python, ruby, perl """ return items def post_install(self, pkg_install=None): """Add scripts for starting FreeNX and CloudMan. """ pass
{ "repo_name": "heuermh/cloudbiolinux", "path": "cloudbio/flavor/__init__.py", "copies": "10", "size": "2712", "license": "mit", "hash": -7899600297668512000, "line_mean": 30.1724137931, "line_max": 84, "alpha_frac": 0.6353244838, "autogenerated": false, "ratio": 4.424143556280587, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0014559946917297654, "num_lines": 87 }
# A flock of n birds is flying across the continent. Each bird has a type, and # the different types are designated by the ID numbers 1, 2, 3, 4, and 5. # # Given an array of n integers where each integer describes the type of a bird # in the flock, find and print the type number of the most common bird. If two # or more types of birds are equally common, choose the type with the smallest # ID number. # # Input Format: # The first line contains an integer denoting n (the number of birds). # The second line contains n space-separated integers describing the respective # type numbers of each bird in the flock. # # Constraints: # 5 <= n <= 2 * 10^5 # It is guaranteed that each type is 1, 2, 3, 4, or 5. # # Output Format: # Print the type number of the most common bird; if two or more types of birds # are equally common, choose the type with the smallest ID number. # # Sample Input 0: # 6 # 1 4 4 4 5 3 # # Sample Output 0: # 4 # # Explanation 0: # The different types of birds occur in the following frequencies: # Type 1: 1 bird # Type 2: 0 birds # Type 3: 1 bird # Type 4: 3 birds # Type 5: 1 bird # # The type number that occurs at the highest frequency is type 4, so we print # 4 as our answer. _ = raw_input() # Not used types = map(int, raw_input().split()) type_count = [0] * 6 # 0 (not used), 1-5 bird types bird_type = max_birds = 0 for t in types: type_count[t] += 1 if type_count[t] > max_birds: max_birds = type_count[t] bird_type = t elif type_count[t] == max_birds: if t < bird_type: bird_type = t print bird_type
{ "repo_name": "chinhtle/python_fun", "path": "hacker_rank/algorithms/implementation/migratorybirds.py", "copies": "1", "size": "1617", "license": "mit", "hash": -4131011550918595600, "line_mean": 27.875, "line_max": 79, "alpha_frac": 0.6641929499, "autogenerated": false, "ratio": 3.039473684210526, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9203666634110526, "avg_score": 0, "num_lines": 56 }
"""A flow graph representation for Python bytecode""" from __future__ import absolute_import, print_function from pony.py23compat import imap, items_list import dis import types import sys from . import misc from .consts import CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS class FlowGraph: def __init__(self): self.current = self.entry = Block() self.exit = Block("exit") self.blocks = misc.Set() self.blocks.add(self.entry) self.blocks.add(self.exit) def startBlock(self, block): if self._debug: if self.current: print("end", repr(self.current)) print(" next", self.current.next) print(" prev", self.current.prev) print(" ", self.current.get_children()) print(repr(block)) self.current = block def nextBlock(self, block=None): # XXX think we need to specify when there is implicit transfer # from one block to the next. might be better to represent this # with explicit JUMP_ABSOLUTE instructions that are optimized # out when they are unnecessary. # # I think this strategy works: each block has a child # designated as "next" which is returned as the last of the # children. because the nodes in a graph are emitted in # reverse post order, the "next" block will always be emitted # immediately after its parent. # Worry: maintaining this invariant could be tricky if block is None: block = self.newBlock() # Note: If the current block ends with an unconditional control # transfer, then it is techically incorrect to add an implicit # transfer to the block graph. Doing so results in code generation # for unreachable blocks. That doesn't appear to be very common # with Python code and since the built-in compiler doesn't optimize # it out we don't either. self.current.addNext(block) self.startBlock(block) def newBlock(self): b = Block() self.blocks.add(b) return b def startExitBlock(self): self.startBlock(self.exit) _debug = 0 def _enable_debug(self): self._debug = 1 def _disable_debug(self): self._debug = 0 def emit(self, *inst): if self._debug: print("\t", inst) if len(inst) == 2 and isinstance(inst[1], Block): self.current.addOutEdge(inst[1]) self.current.emit(inst) def getBlocksInOrder(self): """Return the blocks in reverse postorder i.e. each node appears before all of its successors """ order = order_blocks(self.entry, self.exit) return order def getBlocks(self): return self.blocks.elements() def getRoot(self): """Return nodes appropriate for use with dominator""" return self.entry def getContainedGraphs(self): l = [] for b in self.getBlocks(): l.extend(b.getContainedGraphs()) return l def order_blocks(start_block, exit_block): """Order blocks so that they are emitted in the right order""" # Rules: # - when a block has a next block, the next block must be emitted just after # - when a block has followers (relative jumps), it must be emitted before # them # - all reachable blocks must be emitted order = [] # Find all the blocks to be emitted. remaining = set() todo = [start_block] while todo: b = todo.pop() if b in remaining: continue remaining.add(b) for c in b.get_children(): if c not in remaining: todo.append(c) # A block is dominated by another block if that block must be emitted # before it. dominators = {} for b in remaining: if __debug__ and b.next: assert b is b.next[0].prev[0], (b, b.next) # Make sure every block appears in dominators, even if no # other block must precede it. dominators.setdefault(b, set()) # preceding blocks dominate following blocks for c in b.get_followers(): while 1: dominators.setdefault(c, set()).add(b) # Any block that has a next pointer leading to c is also # dominated because the whole chain will be emitted at once. # Walk backwards and add them all. if c.prev and c.prev[0] is not b: c = c.prev[0] else: break def find_next(): # Find a block that can be emitted next. for b in remaining: for c in dominators[b]: if c in remaining: break # can't emit yet, dominated by a remaining block else: return b assert 0, 'circular dependency, cannot find next block' b = start_block while 1: order.append(b) remaining.discard(b) if b.next: b = b.next[0] continue elif b is not exit_block and not b.has_unconditional_transfer(): order.append(exit_block) if not remaining: break b = find_next() return order class Block: _count = 0 def __init__(self, label=''): self.insts = [] self.outEdges = set() self.label = label self.bid = Block._count self.next = [] self.prev = [] Block._count = Block._count + 1 def __repr__(self): if self.label: return "<block %s id=%d>" % (self.label, self.bid) else: return "<block id=%d>" % (self.bid) def __str__(self): insts = imap(str, self.insts) return "<block %s %d:\n%s>" % (self.label, self.bid, '\n'.join(insts)) def emit(self, inst): op = inst[0] self.insts.append(inst) def getInstructions(self): return self.insts def addOutEdge(self, block): self.outEdges.add(block) def addNext(self, block): self.next.append(block) assert len(self.next) == 1, list(imap(str, self.next)) block.prev.append(self) assert len(block.prev) == 1, list(imap(str, block.prev)) _uncond_transfer = ('RETURN_VALUE', 'RAISE_VARARGS', 'JUMP_ABSOLUTE', 'JUMP_FORWARD', 'CONTINUE_LOOP', ) def has_unconditional_transfer(self): """Returns True if there is an unconditional transfer to an other block at the end of this block. This means there is no risk for the bytecode executer to go past this block's bytecode.""" try: op, arg = self.insts[-1] except (IndexError, ValueError): return return op in self._uncond_transfer def get_children(self): return list(self.outEdges) + self.next def get_followers(self): """Get the whole list of followers, including the next block.""" followers = set(self.next) # Blocks that must be emitted *after* this one, because of # bytecode offsets (e.g. relative jumps) pointing to them. for inst in self.insts: if inst[0] in PyFlowGraph.hasjrel: followers.add(inst[1]) return followers def getContainedGraphs(self): """Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body. """ contained = [] for inst in self.insts: if len(inst) == 1: continue op = inst[1] if hasattr(op, 'graph'): contained.append(op.graph) return contained # flags for code objects # the FlowGraph is transformed in place; it exists in one of these states RAW = "RAW" FLAT = "FLAT" CONV = "CONV" DONE = "DONE" class PyFlowGraph(FlowGraph): super_init = FlowGraph.__init__ def __init__(self, name, filename, args=(), optimized=0, klass=None): self.super_init() self.name = name self.filename = filename self.docstring = None self.args = args # XXX self.argcount = getArgCount(args) self.klass = klass if optimized: self.flags = CO_OPTIMIZED | CO_NEWLOCALS else: self.flags = 0 self.consts = [] self.names = [] # Free variables found by the symbol table scan, including # variables used only in nested scopes, are included here. self.freevars = [] self.cellvars = [] # The closure list is used to track the order of cell # variables and free variables in the resulting code object. # The offsets used by LOAD_CLOSURE/LOAD_DEREF refer to both # kinds of variables. self.closure = [] self.varnames = list(args) or [] for i in range(len(self.varnames)): var = self.varnames[i] if isinstance(var, TupleArg): self.varnames[i] = var.getName() self.stage = RAW def setDocstring(self, doc): self.docstring = doc def setFlag(self, flag): self.flags = self.flags | flag if flag == CO_VARARGS: self.argcount = self.argcount - 1 def checkFlag(self, flag): if self.flags & flag: return 1 def setFreeVars(self, names): self.freevars = list(names) def setCellVars(self, names): self.cellvars = names def getCode(self): """Get a Python code object""" assert self.stage == RAW self.computeStackDepth() self.flattenGraph() assert self.stage == FLAT self.convertArgs() assert self.stage == CONV self.makeByteCode() assert self.stage == DONE return self.newCodeObject() def dump(self, io=None): if io: save = sys.stdout sys.stdout = io pc = 0 for t in self.insts: opname = t[0] if opname == "SET_LINENO": print() if len(t) == 1: print("\t", "%3d" % pc, opname) pc = pc + 1 else: print("\t", "%3d" % pc, opname, t[1]) pc = pc + 3 if io: sys.stdout = save def computeStackDepth(self): """Compute the max stack depth. Approach is to compute the stack effect of each basic block. Then find the path through the code with the largest total effect. """ depth = {} exit = None for b in self.getBlocks(): depth[b] = findDepth(b.getInstructions()) seen = {} def max_depth(b, d): if b in seen: return d seen[b] = 1 d = d + depth[b] children = b.get_children() if children: return max([max_depth(c, d) for c in children]) else: if not b.label == "exit": return max_depth(self.exit, d) else: return d self.stacksize = max_depth(self.entry, 0) def flattenGraph(self): """Arrange the blocks in order and resolve jumps""" assert self.stage == RAW self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": # arg takes 2 bytes pc = pc + 3 end[b] = pc pc = 0 for i in range(len(insts)): inst = insts[i] if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": pc = pc + 3 opname = inst[0] if opname in self.hasjrel: oparg = inst[1] offset = begin[oparg] - pc insts[i] = opname, offset elif opname in self.hasjabs: insts[i] = opname, begin[inst[1]] self.stage = FLAT hasjrel = set() for i in dis.hasjrel: hasjrel.add(dis.opname[i]) hasjabs = set() for i in dis.hasjabs: hasjabs.add(dis.opname[i]) def convertArgs(self): """Convert arguments from symbolic to concrete form""" assert self.stage == FLAT self.consts.insert(0, self.docstring) self.sort_cellvars() for i in range(len(self.insts)): t = self.insts[i] if len(t) == 2: opname, oparg = t conv = self._converters.get(opname, None) if conv: self.insts[i] = opname, conv(self, oparg) self.stage = CONV def sort_cellvars(self): """Sort cellvars in the order of varnames and prune from freevars. """ cells = {} for name in self.cellvars: cells[name] = 1 self.cellvars = [name for name in self.varnames if name in cells] for name in self.cellvars: del cells[name] self.cellvars = self.cellvars + cells.keys() self.closure = self.cellvars + self.freevars def _lookupName(self, name, list): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before comparing the values. """ t = type(name) for i in range(len(list)): if t == type(list[i]) and list[i] == name: return i end = len(list) list.append(name) return end _converters = {} def _convert_LOAD_CONST(self, arg): if hasattr(arg, 'getCode'): arg = arg.getCode() return self._lookupName(arg, self.consts) def _convert_LOAD_FAST(self, arg): self._lookupName(arg, self.names) return self._lookupName(arg, self.varnames) _convert_STORE_FAST = _convert_LOAD_FAST _convert_DELETE_FAST = _convert_LOAD_FAST def _convert_LOAD_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) def _convert_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) _convert_STORE_NAME = _convert_NAME _convert_DELETE_NAME = _convert_NAME _convert_IMPORT_NAME = _convert_NAME _convert_IMPORT_FROM = _convert_NAME _convert_STORE_ATTR = _convert_NAME _convert_LOAD_ATTR = _convert_NAME _convert_DELETE_ATTR = _convert_NAME _convert_LOAD_GLOBAL = _convert_NAME _convert_STORE_GLOBAL = _convert_NAME _convert_DELETE_GLOBAL = _convert_NAME def _convert_DEREF(self, arg): self._lookupName(arg, self.names) self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _convert_LOAD_DEREF = _convert_DEREF _convert_STORE_DEREF = _convert_DEREF def _convert_LOAD_CLOSURE(self, arg): self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _cmp = list(dis.cmp_op) def _convert_COMPARE_OP(self, arg): return self._cmp.index(arg) # similarly for other opcodes... for name, obj in items_list(locals()): if name[:9] == "_convert_": opname = name[9:] _converters[opname] = obj del name, obj, opname def makeByteCode(self): assert self.stage == CONV self.lnotab = lnotab = LineAddrTable() for t in self.insts: opname = t[0] if len(t) == 1: lnotab.addCode(self.opnum[opname]) else: oparg = t[1] if opname == "SET_LINENO": lnotab.nextLine(oparg) continue hi, lo = twobyte(oparg) try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: print(opname, oparg) print(self.opnum[opname], lo, hi) raise self.stage = DONE opnum = {} for num in range(len(dis.opname)): opnum[dis.opname[num]] = num del num def newCodeObject(self): assert self.stage == DONE if (self.flags & CO_NEWLOCALS) == 0: nlocals = 0 else: nlocals = len(self.varnames) argcount = self.argcount if self.flags & CO_VARKEYWORDS: argcount = argcount - 1 return types.CodeType(argcount, nlocals, self.stacksize, self.flags, self.lnotab.getCode(), self.getConsts(), tuple(self.names), tuple(self.varnames), self.filename, self.name, self.lnotab.firstline, self.lnotab.getTable(), tuple(self.freevars), tuple(self.cellvars)) def getConsts(self): """Return a tuple for the const slot of the code object Must convert references to code (MAKE_FUNCTION) to code objects recursively. """ l = [] for elt in self.consts: if isinstance(elt, PyFlowGraph): elt = elt.getCode() l.append(elt) return tuple(l) def isJump(opname): if opname[:4] == 'JUMP': return 1 class TupleArg: """Helper for marking func defs with nested tuples in arglist""" def __init__(self, count, names): self.count = count self.names = names def __repr__(self): return "TupleArg(%s, %s)" % (self.count, self.names) def getName(self): return ".%d" % self.count def getArgCount(args): argcount = len(args) if args: for arg in args: if isinstance(arg, TupleArg): numNames = len(misc.flatten(arg.names)) argcount = argcount - numNames return argcount def twobyte(val): """Convert an int argument into high and low bytes""" assert isinstance(val, int) return divmod(val, 256) class LineAddrTable: """lnotab This class builds the lnotab, which is documented in compile.c. Here's a brief recap: For each SET_LINENO instruction after the first one, two bytes are added to lnotab. (In some cases, multiple two-byte entries are added.) The first byte is the distance in bytes between the instruction for the last SET_LINENO and the current SET_LINENO. The second byte is offset in line numbers. If either offset is greater than 255, multiple two-byte entries are added -- see compile.c for the delicate details. """ def __init__(self): self.code = [] self.codeOffset = 0 self.firstline = 0 self.lastline = 0 self.lastoff = 0 self.lnotab = [] def addCode(self, *args): for arg in args: self.code.append(chr(arg)) self.codeOffset = self.codeOffset + len(args) def nextLine(self, lineno): if self.firstline == 0: self.firstline = lineno self.lastline = lineno else: # compute deltas addr = self.codeOffset - self.lastoff line = lineno - self.lastline # Python assumes that lineno always increases with # increasing bytecode address (lnotab is unsigned char). # Depending on when SET_LINENO instructions are emitted # this is not always true. Consider the code: # a = (1, # b) # In the bytecode stream, the assignment to "a" occurs # after the loading of "b". This works with the C Python # compiler because it only generates a SET_LINENO instruction # for the assignment. if line >= 0: push = self.lnotab.append while addr > 255: push(255); push(0) addr -= 255 while line > 255: push(addr); push(255) line -= 255 addr = 0 if addr > 0 or line > 0: push(addr); push(line) self.lastline = lineno self.lastoff = self.codeOffset def getCode(self): return ''.join(self.code) def getTable(self): return ''.join(imap(chr, self.lnotab)) class StackDepthTracker: # XXX 1. need to keep track of stack depth on jumps # XXX 2. at least partly as a result, this code is broken def findDepth(self, insts, debug=0): depth = 0 maxDepth = 0 for i in insts: opname = i[0] if debug: print(i, end=' ') delta = self.effect.get(opname, None) if delta is not None: depth = depth + delta else: # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta is None: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth > maxDepth: maxDepth = depth if debug: print(depth, maxDepth) return maxDepth effect = { 'POP_TOP': -1, 'DUP_TOP': 1, 'LIST_APPEND': -1, 'SET_ADD': -1, 'MAP_ADD': -2, 'SLICE+1': -1, 'SLICE+2': -1, 'SLICE+3': -2, 'STORE_SLICE+0': -1, 'STORE_SLICE+1': -2, 'STORE_SLICE+2': -2, 'STORE_SLICE+3': -3, 'DELETE_SLICE+0': -1, 'DELETE_SLICE+1': -2, 'DELETE_SLICE+2': -2, 'DELETE_SLICE+3': -3, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, # PRINT_EXPR? 'PRINT_ITEM': -1, 'RETURN_VALUE': -1, 'YIELD_VALUE': -1, 'EXEC_STMT': -3, 'BUILD_CLASS': -2, 'STORE_NAME': -1, 'STORE_ATTR': -2, 'DELETE_ATTR': -1, 'STORE_GLOBAL': -1, 'BUILD_MAP': 1, 'COMPARE_OP': -1, 'STORE_FAST': -1, 'IMPORT_STAR': -1, 'IMPORT_NAME': -1, 'IMPORT_FROM': 1, 'LOAD_ATTR': 0, # unlike other loads # close enough... 'SETUP_EXCEPT': 3, 'SETUP_FINALLY': 3, 'FOR_ITER': 1, 'WITH_CLEANUP': -1, } # use pattern match patterns = [ ('BINARY_', -1), ('LOAD_', 1), ] def UNPACK_SEQUENCE(self, count): return count-1 def BUILD_TUPLE(self, count): return -count+1 def BUILD_LIST(self, count): return -count+1 def BUILD_SET(self, count): return -count+1 def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return -(lo + hi * 2) def CALL_FUNCTION_VAR(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_KW(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_VAR_KW(self, argc): return self.CALL_FUNCTION(argc)-2 def MAKE_FUNCTION(self, argc): return -argc def MAKE_CLOSURE(self, argc): # XXX need to account for free variables too! return -argc def BUILD_SLICE(self, argc): if argc == 2: return -1 elif argc == 3: return -2 def DUP_TOPX(self, argc): return argc findDepth = StackDepthTracker().findDepth
{ "repo_name": "ponyorm/pony", "path": "pony/thirdparty/compiler/pyassem.py", "copies": "2", "size": "24342", "license": "apache-2.0", "hash": 5971832004702266000, "line_mean": 30.8612565445, "line_max": 80, "alpha_frac": 0.5396434147, "autogenerated": false, "ratio": 3.918544752092724, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5458188166792723, "avg_score": null, "num_lines": null }
"""A flow graph representation for Python bytecode""" import dis import new import string import sys import types from compiler import misc from compiler.consts import CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, \ CO_VARKEYWORDS def xxx_sort(l): l = l[:] def sorter(a, b): return cmp(a.bid, b.bid) l.sort(sorter) return l class FlowGraph: def __init__(self): self.current = self.entry = Block() self.exit = Block("exit") self.blocks = misc.Set() self.blocks.add(self.entry) self.blocks.add(self.exit) def startBlock(self, block): if self._debug: if self.current: print "end", repr(self.current) print " next", self.current.next print " ", self.current.get_children() print repr(block) self.current = block def nextBlock(self, block=None): # XXX think we need to specify when there is implicit transfer # from one block to the next. might be better to represent this # with explicit JUMP_ABSOLUTE instructions that are optimized # out when they are unnecessary. # # I think this strategy works: each block has a child # designated as "next" which is returned as the last of the # children. because the nodes in a graph are emitted in # reverse post order, the "next" block will always be emitted # immediately after its parent. # Worry: maintaining this invariant could be tricky if block is None: block = self.newBlock() # Note: If the current block ends with an unconditional # control transfer, then it is incorrect to add an implicit # transfer to the block graph. The current code requires # these edges to get the blocks emitted in the right order, # however. :-( If a client needs to remove these edges, call # pruneEdges(). self.current.addNext(block) self.startBlock(block) def newBlock(self): b = Block() self.blocks.add(b) return b def startExitBlock(self): self.startBlock(self.exit) _debug = 0 def _enable_debug(self): self._debug = 1 def _disable_debug(self): self._debug = 0 def emit(self, *inst): if self._debug: print "\t", inst if inst[0] == 'RETURN_VALUE': self.current.addOutEdge(self.exit) if len(inst) == 2 and isinstance(inst[1], Block): self.current.addOutEdge(inst[1]) self.current.emit(inst) def getBlocksInOrder(self): """Return the blocks in reverse postorder i.e. each node appears before all of its successors """ # XXX make sure every node that doesn't have an explicit next # is set so that next points to exit for b in self.blocks.elements(): if b is self.exit: continue if not b.next: b.addNext(self.exit) order = dfs_postorder(self.entry, {}) order.reverse() self.fixupOrder(order, self.exit) # hack alert if not self.exit in order: order.append(self.exit) return order def fixupOrder(self, blocks, default_next): """Fixup bad order introduced by DFS.""" # XXX This is a total mess. There must be a better way to get # the code blocks in the right order. self.fixupOrderHonorNext(blocks, default_next) self.fixupOrderForward(blocks, default_next) def fixupOrderHonorNext(self, blocks, default_next): """Fix one problem with DFS. The DFS uses child block, but doesn't know about the special "next" block. As a result, the DFS can order blocks so that a block isn't next to the right block for implicit control transfers. """ index = {} for i in range(len(blocks)): index[blocks[i]] = i for i in range(0, len(blocks) - 1): b = blocks[i] n = blocks[i + 1] if not b.next or b.next[0] == default_next or b.next[0] == n: continue # The blocks are in the wrong order. Find the chain of # blocks to insert where they belong. cur = b chain = [] elt = cur while elt.next and elt.next[0] != default_next: chain.append(elt.next[0]) elt = elt.next[0] # Now remove the blocks in the chain from the current # block list, so that they can be re-inserted. l = [] for b in chain: assert index[b] > i l.append((index[b], b)) l.sort() l.reverse() for j, b in l: del blocks[index[b]] # Insert the chain in the proper location blocks[i:i + 1] = [cur] + chain # Finally, re-compute the block indexes for i in range(len(blocks)): index[blocks[i]] = i def fixupOrderForward(self, blocks, default_next): """Make sure all JUMP_FORWARDs jump forward""" index = {} chains = [] cur = [] for b in blocks: index[b] = len(chains) cur.append(b) if b.next and b.next[0] == default_next: chains.append(cur) cur = [] chains.append(cur) while 1: constraints = [] for i in range(len(chains)): l = chains[i] for b in l: for c in b.get_children(): if index[c] < i: forward_p = 0 for inst in b.insts: if inst[0] == 'JUMP_FORWARD': if inst[1] == c: forward_p = 1 if not forward_p: continue constraints.append((index[c], i)) if not constraints: break # XXX just do one for now # do swaps to get things in the right order goes_before, a_chain = constraints[0] assert a_chain > goes_before c = chains[a_chain] chains.remove(c) chains.insert(goes_before, c) del blocks[:] for c in chains: for b in c: blocks.append(b) def getBlocks(self): return self.blocks.elements() def getRoot(self): """Return nodes appropriate for use with dominator""" return self.entry def getContainedGraphs(self): l = [] for b in self.getBlocks(): l.extend(b.getContainedGraphs()) return l def dfs_postorder(b, seen): """Depth-first search of tree rooted at b, return in postorder""" order = [] seen[b] = b for c in b.get_children(): if seen.has_key(c): continue order = order + dfs_postorder(c, seen) order.append(b) return order class Block: _count = 0 def __init__(self, label=''): self.insts = [] self.inEdges = misc.Set() self.outEdges = misc.Set() self.label = label self.bid = Block._count self.next = [] Block._count = Block._count + 1 def __repr__(self): if self.label: return "<block %s id=%d>" % (self.label, self.bid) else: return "<block id=%d>" % (self.bid) def __str__(self): insts = map(str, self.insts) return "<block %s %d:\n%s>" % (self.label, self.bid, string.join(insts, '\n')) def emit(self, inst): op = inst[0] if op[:4] == 'JUMP': self.outEdges.add(inst[1]) self.insts.append(inst) def getInstructions(self): return self.insts def addInEdge(self, block): self.inEdges.add(block) def addOutEdge(self, block): self.outEdges.add(block) def addNext(self, block): self.next.append(block) assert len(self.next) == 1, map(str, self.next) _uncond_transfer = ('RETURN_VALUE', 'RAISE_VARARGS', 'JUMP_ABSOLUTE', 'JUMP_FORWARD', 'CONTINUE_LOOP') def pruneNext(self): """Remove bogus edge for unconditional transfers Each block has a next edge that accounts for implicit control transfers, e.g. from a JUMP_IF_FALSE to the block that will be executed if the test is true. These edges must remain for the current assembler code to work. If they are removed, the dfs_postorder gets things in weird orders. However, they shouldn't be there for other purposes, e.g. conversion to SSA form. This method will remove the next edge when it follows an unconditional control transfer. """ try: op, arg = self.insts[-1] except (IndexError, ValueError): return if op in self._uncond_transfer: self.next = [] def get_children(self): if self.next and self.next[0] in self.outEdges: self.outEdges.remove(self.next[0]) return self.outEdges.elements() + self.next def getContainedGraphs(self): """Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body. """ contained = [] for inst in self.insts: if len(inst) == 1: continue op = inst[1] if hasattr(op, 'graph'): contained.append(op.graph) return contained # flags for code objects # the FlowGraph is transformed in place; it exists in one of these states RAW = "RAW" FLAT = "FLAT" CONV = "CONV" DONE = "DONE" class PyFlowGraph(FlowGraph): super_init = FlowGraph.__init__ def __init__(self, name, filename, args=(), optimized=0, klass=None): self.super_init() self.name = name self.filename = filename self.docstring = None self.args = args # XXX self.argcount = getArgCount(args) self.klass = klass if optimized: self.flags = CO_OPTIMIZED | CO_NEWLOCALS else: self.flags = 0 self.consts = [] self.names = [] # Free variables found by the symbol table scan, including # variables used only in nested scopes, are included here. self.freevars = [] self.cellvars = [] # The closure list is used to track the order of cell # variables and free variables in the resulting code object. # The offsets used by LOAD_CLOSURE/LOAD_DEREF refer to both # kinds of variables. self.closure = [] self.varnames = list(args) or [] for i in range(len(self.varnames)): var = self.varnames[i] if isinstance(var, TupleArg): self.varnames[i] = var.getName() self.stage = RAW def setDocstring(self, doc): self.docstring = doc def setFlag(self, flag): self.flags = self.flags | flag if flag == CO_VARARGS: self.argcount = self.argcount - 1 def checkFlag(self, flag): if self.flags & flag: return 1 def setFreeVars(self, names): self.freevars = list(names) def setCellVars(self, names): self.cellvars = names def getCode(self): """Get a Python code object""" if self.stage == RAW: self.computeStackDepth() self.flattenGraph() if self.stage == FLAT: self.convertArgs() if self.stage == CONV: self.makeByteCode() if self.stage == DONE: return self.newCodeObject() raise RuntimeError, "inconsistent PyFlowGraph state" def dump(self, io=None): if io: save = sys.stdout sys.stdout = io pc = 0 for t in self.insts: opname = t[0] if opname == "SET_LINENO": print if len(t) == 1: print "\t", "%3d" % pc, opname pc = pc + 1 else: print "\t", "%3d" % pc, opname, t[1] pc = pc + 3 if io: sys.stdout = save def computeStackDepth(self): """Compute the max stack depth. Approach is to compute the stack effect of each basic block. Then find the path through the code with the largest total effect. """ depth = {} exit = None for b in self.getBlocks(): depth[b] = findDepth(b.getInstructions()) seen = {} def max_depth(b, d): if seen.has_key(b): return d seen[b] = 1 d = d + depth[b] children = b.get_children() if children: return max([max_depth(c, d) for c in children]) else: if not b.label == "exit": return max_depth(self.exit, d) else: return d self.stacksize = max_depth(self.entry, 0) def flattenGraph(self): """Arrange the blocks in order and resolve jumps""" assert self.stage == RAW self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if len(inst) == 1: pc = pc + 1 else: # arg takes 2 bytes pc = pc + 3 end[b] = pc pc = 0 for i in range(len(insts)): inst = insts[i] if len(inst) == 1: pc = pc + 1 else: pc = pc + 3 opname = inst[0] if self.hasjrel.has_elt(opname): oparg = inst[1] offset = begin[oparg] - pc insts[i] = opname, offset elif self.hasjabs.has_elt(opname): insts[i] = opname, begin[inst[1]] self.stage = FLAT hasjrel = misc.Set() for i in dis.hasjrel: hasjrel.add(dis.opname[i]) hasjabs = misc.Set() for i in dis.hasjabs: hasjabs.add(dis.opname[i]) def convertArgs(self): """Convert arguments from symbolic to concrete form""" assert self.stage == FLAT self.consts.insert(0, self.docstring) self.sort_cellvars() for i in range(len(self.insts)): t = self.insts[i] if len(t) == 2: opname, oparg = t conv = self._converters.get(opname, None) if conv: self.insts[i] = opname, conv(self, oparg) self.stage = CONV def sort_cellvars(self): """Sort cellvars in the order of varnames and prune from freevars. """ cells = {} for name in self.cellvars: cells[name] = 1 self.cellvars = [name for name in self.varnames if cells.has_key(name)] for name in self.cellvars: del cells[name] self.cellvars = self.cellvars + cells.keys() self.closure = self.cellvars + self.freevars def _lookupName(self, name, list): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before comparing the values. """ t = type(name) for i in range(len(list)): if t == type(list[i]) and list[i] == name: return i end = len(list) list.append(name) return end _converters = {} def _convert_LOAD_CONST(self, arg): if hasattr(arg, 'getCode'): arg = arg.getCode() return self._lookupName(arg, self.consts) def _convert_LOAD_FAST(self, arg): self._lookupName(arg, self.names) return self._lookupName(arg, self.varnames) _convert_STORE_FAST = _convert_LOAD_FAST _convert_DELETE_FAST = _convert_LOAD_FAST def _convert_LOAD_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) def _convert_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) _convert_STORE_NAME = _convert_NAME _convert_DELETE_NAME = _convert_NAME _convert_IMPORT_NAME = _convert_NAME _convert_IMPORT_FROM = _convert_NAME _convert_STORE_ATTR = _convert_NAME _convert_LOAD_ATTR = _convert_NAME _convert_DELETE_ATTR = _convert_NAME _convert_LOAD_GLOBAL = _convert_NAME _convert_STORE_GLOBAL = _convert_NAME _convert_DELETE_GLOBAL = _convert_NAME def _convert_DEREF(self, arg): self._lookupName(arg, self.names) self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _convert_LOAD_DEREF = _convert_DEREF _convert_STORE_DEREF = _convert_DEREF def _convert_LOAD_CLOSURE(self, arg): self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _cmp = list(dis.cmp_op) def _convert_COMPARE_OP(self, arg): return self._cmp.index(arg) # similarly for other opcodes... for name, obj in locals().items(): if name[:9] == "_convert_": opname = name[9:] _converters[opname] = obj del name, obj, opname def makeByteCode(self): assert self.stage == CONV self.lnotab = lnotab = LineAddrTable() for t in self.insts: opname = t[0] if len(t) == 1: lnotab.addCode(self.opnum[opname]) else: oparg = t[1] if opname == "SET_LINENO": lnotab.nextLine(oparg) hi, lo = twobyte(oparg) try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: print opname, oparg print self.opnum[opname], lo, hi raise self.stage = DONE opnum = {} for num in range(len(dis.opname)): opnum[dis.opname[num]] = num del num def newCodeObject(self): assert self.stage == DONE if (self.flags & CO_NEWLOCALS) == 0: nlocals = 0 else: nlocals = len(self.varnames) argcount = self.argcount if self.flags & CO_VARKEYWORDS: argcount = argcount - 1 return new.code(argcount, nlocals, self.stacksize, self.flags, self.lnotab.getCode(), self.getConsts(), tuple(self.names), tuple(self.varnames), self.filename, self.name, self.lnotab.firstline, self.lnotab.getTable(), tuple(self.freevars), tuple(self.cellvars)) def getConsts(self): """Return a tuple for the const slot of the code object Must convert references to code (MAKE_FUNCTION) to code objects recursively. """ l = [] for elt in self.consts: if isinstance(elt, PyFlowGraph): elt = elt.getCode() l.append(elt) return tuple(l) def isJump(opname): if opname[:4] == 'JUMP': return 1 class TupleArg: """Helper for marking func defs with nested tuples in arglist""" def __init__(self, count, names): self.count = count self.names = names def __repr__(self): return "TupleArg(%s, %s)" % (self.count, self.names) def getName(self): return ".%d" % self.count def getArgCount(args): argcount = len(args) if args: for arg in args: if isinstance(arg, TupleArg): numNames = len(misc.flatten(arg.names)) argcount = argcount - numNames return argcount def twobyte(val): """Convert an int argument into high and low bytes""" assert type(val) == types.IntType return divmod(val, 256) class LineAddrTable: """lnotab This class builds the lnotab, which is documented in compile.c. Here's a brief recap: For each SET_LINENO instruction after the first one, two bytes are added to lnotab. (In some cases, multiple two-byte entries are added.) The first byte is the distance in bytes between the instruction for the last SET_LINENO and the current SET_LINENO. The second byte is offset in line numbers. If either offset is greater than 255, multiple two-byte entries are added -- see compile.c for the delicate details. """ def __init__(self): self.code = [] self.codeOffset = 0 self.firstline = 0 self.lastline = 0 self.lastoff = 0 self.lnotab = [] def addCode(self, *args): for arg in args: self.code.append(chr(arg)) self.codeOffset = self.codeOffset + len(args) def nextLine(self, lineno): if self.firstline == 0: self.firstline = lineno self.lastline = lineno else: # compute deltas addr = self.codeOffset - self.lastoff line = lineno - self.lastline # Python assumes that lineno always increases with # increasing bytecode address (lnotab is unsigned char). # Depending on when SET_LINENO instructions are emitted # this is not always true. Consider the code: # a = (1, # b) # In the bytecode stream, the assignment to "a" occurs # after the loading of "b". This works with the C Python # compiler because it only generates a SET_LINENO instruction # for the assignment. if line > 0: push = self.lnotab.append while addr > 255: push(255); push(0) addr -= 255 while line > 255: push(addr); push(255) line -= 255 addr = 0 if addr > 0 or line > 0: push(addr); push(line) self.lastline = lineno self.lastoff = self.codeOffset def getCode(self): return string.join(self.code, '') def getTable(self): return string.join(map(chr, self.lnotab), '') class StackDepthTracker: # XXX 1. need to keep track of stack depth on jumps # XXX 2. at least partly as a result, this code is broken def findDepth(self, insts, debug=0): depth = 0 maxDepth = 0 for i in insts: opname = i[0] if debug: print i, delta = self.effect.get(opname, None) if delta is not None: depth = depth + delta else: # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta is None: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth > maxDepth: maxDepth = depth if debug: print depth, maxDepth return maxDepth effect = { 'POP_TOP': -1, 'DUP_TOP': 1, 'SLICE+1': -1, 'SLICE+2': -1, 'SLICE+3': -2, 'STORE_SLICE+0': -1, 'STORE_SLICE+1': -2, 'STORE_SLICE+2': -2, 'STORE_SLICE+3': -3, 'DELETE_SLICE+0': -1, 'DELETE_SLICE+1': -2, 'DELETE_SLICE+2': -2, 'DELETE_SLICE+3': -3, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, # PRINT_EXPR? 'PRINT_ITEM': -1, 'RETURN_VALUE': -1, 'EXEC_STMT': -3, 'BUILD_CLASS': -2, 'STORE_NAME': -1, 'STORE_ATTR': -2, 'DELETE_ATTR': -1, 'STORE_GLOBAL': -1, 'BUILD_MAP': 1, 'COMPARE_OP': -1, 'STORE_FAST': -1, 'IMPORT_STAR': -1, 'IMPORT_NAME': 0, 'IMPORT_FROM': 1, 'LOAD_ATTR': 0, # unlike other loads # close enough... 'SETUP_EXCEPT': 3, 'SETUP_FINALLY': 3, 'FOR_ITER': 1, } # use pattern match patterns = [ ('BINARY_', -1), ('LOAD_', 1), ] def UNPACK_SEQUENCE(self, count): return count-1 def BUILD_TUPLE(self, count): return -count+1 def BUILD_LIST(self, count): return -count+1 def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return -(lo + hi * 2) def CALL_FUNCTION_VAR(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_KW(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_VAR_KW(self, argc): return self.CALL_FUNCTION(argc)-2 def MAKE_FUNCTION(self, argc): return -argc def MAKE_CLOSURE(self, argc): # XXX need to account for free variables too! return -argc def BUILD_SLICE(self, argc): if argc == 2: return -1 elif argc == 3: return -2 def DUP_TOPX(self, argc): return argc findDepth = StackDepthTracker().findDepth
{ "repo_name": "MalloyPower/parsing-python", "path": "front-end/testsuite-python-lib/Python-2.2/Lib/compiler/pyassem.py", "copies": "1", "size": "26214", "license": "mit", "hash": -5889136586565532000, "line_mean": 30.8131067961, "line_max": 74, "alpha_frac": 0.5295262074, "autogenerated": false, "ratio": 3.9455147501505117, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49750409575505117, "avg_score": null, "num_lines": null }
"""A flow graph representation for Python bytecode""" import dis import new import sys import types from compiler import misc from compiler.consts \ import CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS class FlowGraph: def __init__(self): self.current = self.entry = Block() self.exit = Block("exit") self.blocks = misc.Set() self.blocks.add(self.entry) self.blocks.add(self.exit) def startBlock(self, block): if self._debug: if self.current: print "end", repr(self.current) print " next", self.current.next print " ", self.current.get_children() print repr(block) self.current = block def nextBlock(self, block=None): # XXX think we need to specify when there is implicit transfer # from one block to the next. might be better to represent this # with explicit JUMP_ABSOLUTE instructions that are optimized # out when they are unnecessary. # # I think this strategy works: each block has a child # designated as "next" which is returned as the last of the # children. because the nodes in a graph are emitted in # reverse post order, the "next" block will always be emitted # immediately after its parent. # Worry: maintaining this invariant could be tricky if block is None: block = self.newBlock() # Note: If the current block ends with an unconditional # control transfer, then it is incorrect to add an implicit # transfer to the block graph. The current code requires # these edges to get the blocks emitted in the right order, # however. :-( If a client needs to remove these edges, call # pruneEdges(). self.current.addNext(block) self.startBlock(block) def newBlock(self): b = Block() self.blocks.add(b) return b def startExitBlock(self): self.startBlock(self.exit) _debug = 0 def _enable_debug(self): self._debug = 1 def _disable_debug(self): self._debug = 0 def emit(self, *inst): if self._debug: print "\t", inst if inst[0] in ['RETURN_VALUE', 'YIELD_VALUE']: self.current.addOutEdge(self.exit) if len(inst) == 2 and isinstance(inst[1], Block): self.current.addOutEdge(inst[1]) self.current.emit(inst) def getBlocksInOrder(self): """Return the blocks in reverse postorder i.e. each node appears before all of its successors """ # XXX make sure every node that doesn't have an explicit next # is set so that next points to exit for b in self.blocks.elements(): if b is self.exit: continue if not b.next: b.addNext(self.exit) order = dfs_postorder(self.entry, {}) order.reverse() self.fixupOrder(order, self.exit) # hack alert if not self.exit in order: order.append(self.exit) return order def fixupOrder(self, blocks, default_next): """Fixup bad order introduced by DFS.""" # XXX This is a total mess. There must be a better way to get # the code blocks in the right order. self.fixupOrderHonorNext(blocks, default_next) self.fixupOrderForward(blocks, default_next) def fixupOrderHonorNext(self, blocks, default_next): """Fix one problem with DFS. The DFS uses child block, but doesn't know about the special "next" block. As a result, the DFS can order blocks so that a block isn't next to the right block for implicit control transfers. """ index = {} for i in range(len(blocks)): index[blocks[i]] = i for i in range(0, len(blocks) - 1): b = blocks[i] n = blocks[i + 1] if not b.next or b.next[0] == default_next or b.next[0] == n: continue # The blocks are in the wrong order. Find the chain of # blocks to insert where they belong. cur = b chain = [] elt = cur while elt.next and elt.next[0] != default_next: chain.append(elt.next[0]) elt = elt.next[0] # Now remove the blocks in the chain from the current # block list, so that they can be re-inserted. l = [] for b in chain: assert index[b] > i l.append((index[b], b)) l.sort() l.reverse() for j, b in l: del blocks[index[b]] # Insert the chain in the proper location blocks[i:i + 1] = [cur] + chain # Finally, re-compute the block indexes for i in range(len(blocks)): index[blocks[i]] = i def fixupOrderForward(self, blocks, default_next): """Make sure all JUMP_FORWARDs jump forward""" index = {} chains = [] cur = [] for b in blocks: index[b] = len(chains) cur.append(b) if b.next and b.next[0] == default_next: chains.append(cur) cur = [] chains.append(cur) while 1: constraints = [] for i in range(len(chains)): l = chains[i] for b in l: for c in b.get_children(): if index[c] < i: forward_p = 0 for inst in b.insts: if inst[0] == 'JUMP_FORWARD': if inst[1] == c: forward_p = 1 if not forward_p: continue constraints.append((index[c], i)) if not constraints: break # XXX just do one for now # do swaps to get things in the right order goes_before, a_chain = constraints[0] assert a_chain > goes_before c = chains[a_chain] chains.remove(c) chains.insert(goes_before, c) del blocks[:] for c in chains: for b in c: blocks.append(b) def getBlocks(self): return self.blocks.elements() def getRoot(self): """Return nodes appropriate for use with dominator""" return self.entry def getContainedGraphs(self): l = [] for b in self.getBlocks(): l.extend(b.getContainedGraphs()) return l def dfs_postorder(b, seen): """Depth-first search of tree rooted at b, return in postorder""" order = [] seen[b] = b for c in b.get_children(): if seen.has_key(c): continue order = order + dfs_postorder(c, seen) order.append(b) return order class Block: _count = 0 def __init__(self, label=''): self.insts = [] self.inEdges = misc.Set() self.outEdges = misc.Set() self.label = label self.bid = Block._count self.next = [] Block._count = Block._count + 1 def __repr__(self): if self.label: return "<block %s id=%d>" % (self.label, self.bid) else: return "<block id=%d>" % (self.bid) def __str__(self): insts = map(str, self.insts) return "<block %s %d:\n%s>" % (self.label, self.bid, '\n'.join(insts)) def emit(self, inst): op = inst[0] if op[:4] == 'JUMP': self.outEdges.add(inst[1]) self.insts.append(inst) def getInstructions(self): return self.insts def addInEdge(self, block): self.inEdges.add(block) def addOutEdge(self, block): self.outEdges.add(block) def addNext(self, block): self.next.append(block) assert len(self.next) == 1, map(str, self.next) _uncond_transfer = ('RETURN_VALUE', 'RAISE_VARARGS', 'YIELD_VALUE', 'JUMP_ABSOLUTE', 'JUMP_FORWARD', 'CONTINUE_LOOP') def pruneNext(self): """Remove bogus edge for unconditional transfers Each block has a next edge that accounts for implicit control transfers, e.g. from a JUMP_IF_FALSE to the block that will be executed if the test is true. These edges must remain for the current assembler code to work. If they are removed, the dfs_postorder gets things in weird orders. However, they shouldn't be there for other purposes, e.g. conversion to SSA form. This method will remove the next edge when it follows an unconditional control transfer. """ try: op, arg = self.insts[-1] except (IndexError, ValueError): return if op in self._uncond_transfer: self.next = [] def get_children(self): if self.next and self.next[0] in self.outEdges: self.outEdges.remove(self.next[0]) return self.outEdges.elements() + self.next def getContainedGraphs(self): """Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body. """ contained = [] for inst in self.insts: if len(inst) == 1: continue op = inst[1] if hasattr(op, 'graph'): contained.append(op.graph) return contained # flags for code objects # the FlowGraph is transformed in place; it exists in one of these states RAW = "RAW" FLAT = "FLAT" CONV = "CONV" DONE = "DONE" class PyFlowGraph(FlowGraph): super_init = FlowGraph.__init__ def __init__(self, name, filename, args=(), optimized=0, klass=None): self.super_init() self.name = name self.filename = filename self.docstring = None self.args = args # XXX self.argcount = getArgCount(args) self.klass = klass if optimized: self.flags = CO_OPTIMIZED | CO_NEWLOCALS else: self.flags = 0 self.consts = [] self.names = [] # Free variables found by the symbol table scan, including # variables used only in nested scopes, are included here. self.freevars = [] self.cellvars = [] # The closure list is used to track the order of cell # variables and free variables in the resulting code object. # The offsets used by LOAD_CLOSURE/LOAD_DEREF refer to both # kinds of variables. self.closure = [] self.varnames = list(args) or [] for i in range(len(self.varnames)): var = self.varnames[i] if isinstance(var, TupleArg): self.varnames[i] = var.getName() self.stage = RAW def setDocstring(self, doc): self.docstring = doc def setFlag(self, flag): self.flags = self.flags | flag if flag == CO_VARARGS: self.argcount = self.argcount - 1 def checkFlag(self, flag): if self.flags & flag: return 1 def setFreeVars(self, names): self.freevars = list(names) def setCellVars(self, names): self.cellvars = names def getCode(self): """Get a Python code object""" if self.stage == RAW: self.computeStackDepth() self.flattenGraph() if self.stage == FLAT: self.convertArgs() if self.stage == CONV: self.makeByteCode() if self.stage == DONE: return self.newCodeObject() raise RuntimeError, "inconsistent PyFlowGraph state" def dump(self, io=None): if io: save = sys.stdout sys.stdout = io pc = 0 for t in self.insts: opname = t[0] if opname == "SET_LINENO": print if len(t) == 1: print "\t", "%3d" % pc, opname pc = pc + 1 else: print "\t", "%3d" % pc, opname, t[1] pc = pc + 3 if io: sys.stdout = save def computeStackDepth(self): """Compute the max stack depth. Approach is to compute the stack effect of each basic block. Then find the path through the code with the largest total effect. """ depth = {} exit = None for b in self.getBlocks(): depth[b] = findDepth(b.getInstructions()) seen = {} def max_depth(b, d): if seen.has_key(b): return d seen[b] = 1 d = d + depth[b] children = b.get_children() if children: return max([max_depth(c, d) for c in children]) else: if not b.label == "exit": return max_depth(self.exit, d) else: return d self.stacksize = max_depth(self.entry, 0) def flattenGraph(self): """Arrange the blocks in order and resolve jumps""" assert self.stage == RAW self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": # arg takes 2 bytes pc = pc + 3 end[b] = pc pc = 0 for i in range(len(insts)): inst = insts[i] if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": pc = pc + 3 opname = inst[0] if self.hasjrel.has_elt(opname): oparg = inst[1] offset = begin[oparg] - pc insts[i] = opname, offset elif self.hasjabs.has_elt(opname): insts[i] = opname, begin[inst[1]] self.stage = FLAT hasjrel = misc.Set() for i in dis.hasjrel: hasjrel.add(dis.opname[i]) hasjabs = misc.Set() for i in dis.hasjabs: hasjabs.add(dis.opname[i]) def convertArgs(self): """Convert arguments from symbolic to concrete form""" assert self.stage == FLAT self.consts.insert(0, self.docstring) self.sort_cellvars() for i in range(len(self.insts)): t = self.insts[i] if len(t) == 2: opname, oparg = t conv = self._converters.get(opname, None) if conv: self.insts[i] = opname, conv(self, oparg) self.stage = CONV def sort_cellvars(self): """Sort cellvars in the order of varnames and prune from freevars. """ cells = {} for name in self.cellvars: cells[name] = 1 self.cellvars = [name for name in self.varnames if cells.has_key(name)] for name in self.cellvars: del cells[name] self.cellvars = self.cellvars + cells.keys() self.closure = self.cellvars + self.freevars def _lookupName(self, name, list): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before comparing the values. """ t = type(name) for i in range(len(list)): if t == type(list[i]) and list[i] == name: return i end = len(list) list.append(name) return end _converters = {} def _convert_LOAD_CONST(self, arg): if hasattr(arg, 'getCode'): arg = arg.getCode() return self._lookupName(arg, self.consts) def _convert_LOAD_FAST(self, arg): self._lookupName(arg, self.names) return self._lookupName(arg, self.varnames) _convert_STORE_FAST = _convert_LOAD_FAST _convert_DELETE_FAST = _convert_LOAD_FAST def _convert_LOAD_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) def _convert_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) _convert_STORE_NAME = _convert_NAME _convert_DELETE_NAME = _convert_NAME _convert_IMPORT_NAME = _convert_NAME _convert_IMPORT_FROM = _convert_NAME _convert_STORE_ATTR = _convert_NAME _convert_LOAD_ATTR = _convert_NAME _convert_DELETE_ATTR = _convert_NAME _convert_LOAD_GLOBAL = _convert_NAME _convert_STORE_GLOBAL = _convert_NAME _convert_DELETE_GLOBAL = _convert_NAME def _convert_DEREF(self, arg): self._lookupName(arg, self.names) self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _convert_LOAD_DEREF = _convert_DEREF _convert_STORE_DEREF = _convert_DEREF def _convert_LOAD_CLOSURE(self, arg): self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _cmp = list(dis.cmp_op) def _convert_COMPARE_OP(self, arg): return self._cmp.index(arg) # similarly for other opcodes... for name, obj in locals().items(): if name[:9] == "_convert_": opname = name[9:] _converters[opname] = obj del name, obj, opname def makeByteCode(self): assert self.stage == CONV self.lnotab = lnotab = LineAddrTable() for t in self.insts: opname = t[0] if len(t) == 1: lnotab.addCode(self.opnum[opname]) else: oparg = t[1] if opname == "SET_LINENO": lnotab.nextLine(oparg) continue hi, lo = twobyte(oparg) try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: print opname, oparg print self.opnum[opname], lo, hi raise self.stage = DONE opnum = {} for num in range(len(dis.opname)): opnum[dis.opname[num]] = num del num def newCodeObject(self): assert self.stage == DONE if (self.flags & CO_NEWLOCALS) == 0: nlocals = 0 else: nlocals = len(self.varnames) argcount = self.argcount if self.flags & CO_VARKEYWORDS: argcount = argcount - 1 return new.code(argcount, nlocals, self.stacksize, self.flags, self.lnotab.getCode(), self.getConsts(), tuple(self.names), tuple(self.varnames), self.filename, self.name, self.lnotab.firstline, self.lnotab.getTable(), tuple(self.freevars), tuple(self.cellvars)) def getConsts(self): """Return a tuple for the const slot of the code object Must convert references to code (MAKE_FUNCTION) to code objects recursively. """ l = [] for elt in self.consts: if isinstance(elt, PyFlowGraph): elt = elt.getCode() l.append(elt) return tuple(l) def isJump(opname): if opname[:4] == 'JUMP': return 1 class TupleArg: """Helper for marking func defs with nested tuples in arglist""" def __init__(self, count, names): self.count = count self.names = names def __repr__(self): return "TupleArg(%s, %s)" % (self.count, self.names) def getName(self): return ".%d" % self.count def getArgCount(args): argcount = len(args) if args: for arg in args: if isinstance(arg, TupleArg): numNames = len(misc.flatten(arg.names)) argcount = argcount - numNames return argcount def twobyte(val): """Convert an int argument into high and low bytes""" assert type(val) == types.IntType return divmod(val, 256) class LineAddrTable: """lnotab This class builds the lnotab, which is documented in compile.c. Here's a brief recap: For each SET_LINENO instruction after the first one, two bytes are added to lnotab. (In some cases, multiple two-byte entries are added.) The first byte is the distance in bytes between the instruction for the last SET_LINENO and the current SET_LINENO. The second byte is offset in line numbers. If either offset is greater than 255, multiple two-byte entries are added -- see compile.c for the delicate details. """ def __init__(self): self.code = [] self.codeOffset = 0 self.firstline = 0 self.lastline = 0 self.lastoff = 0 self.lnotab = [] def addCode(self, *args): for arg in args: self.code.append(chr(arg)) self.codeOffset = self.codeOffset + len(args) def nextLine(self, lineno): if self.firstline == 0: self.firstline = lineno self.lastline = lineno else: # compute deltas addr = self.codeOffset - self.lastoff line = lineno - self.lastline # Python assumes that lineno always increases with # increasing bytecode address (lnotab is unsigned char). # Depending on when SET_LINENO instructions are emitted # this is not always true. Consider the code: # a = (1, # b) # In the bytecode stream, the assignment to "a" occurs # after the loading of "b". This works with the C Python # compiler because it only generates a SET_LINENO instruction # for the assignment. if line >= 0: push = self.lnotab.append while addr > 255: push(255); push(0) addr -= 255 while line > 255: push(addr); push(255) line -= 255 addr = 0 if addr > 0 or line > 0: push(addr); push(line) self.lastline = lineno self.lastoff = self.codeOffset def getCode(self): return ''.join(self.code) def getTable(self): return ''.join(map(chr, self.lnotab)) class StackDepthTracker: # XXX 1. need to keep track of stack depth on jumps # XXX 2. at least partly as a result, this code is broken def findDepth(self, insts, debug=0): depth = 0 maxDepth = 0 for i in insts: opname = i[0] if debug: print i, delta = self.effect.get(opname, None) if delta is not None: depth = depth + delta else: # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta is None: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth > maxDepth: maxDepth = depth if debug: print depth, maxDepth return maxDepth effect = { 'POP_TOP': -1, 'DUP_TOP': 1, 'SLICE+1': -1, 'SLICE+2': -1, 'SLICE+3': -2, 'STORE_SLICE+0': -1, 'STORE_SLICE+1': -2, 'STORE_SLICE+2': -2, 'STORE_SLICE+3': -3, 'DELETE_SLICE+0': -1, 'DELETE_SLICE+1': -2, 'DELETE_SLICE+2': -2, 'DELETE_SLICE+3': -3, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, # PRINT_EXPR? 'PRINT_ITEM': -1, 'RETURN_VALUE': -1, 'YIELD_VALUE': -1, 'EXEC_STMT': -3, 'BUILD_CLASS': -2, 'STORE_NAME': -1, 'STORE_ATTR': -2, 'DELETE_ATTR': -1, 'STORE_GLOBAL': -1, 'BUILD_MAP': 1, 'COMPARE_OP': -1, 'STORE_FAST': -1, 'IMPORT_STAR': -1, 'IMPORT_NAME': 0, 'IMPORT_FROM': 1, 'LOAD_ATTR': 0, # unlike other loads # close enough... 'SETUP_EXCEPT': 3, 'SETUP_FINALLY': 3, 'FOR_ITER': 1, } # use pattern match patterns = [ ('BINARY_', -1), ('LOAD_', 1), ] def UNPACK_SEQUENCE(self, count): return count-1 def BUILD_TUPLE(self, count): return -count+1 def BUILD_LIST(self, count): return -count+1 def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return -(lo + hi * 2) def CALL_FUNCTION_VAR(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_KW(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_VAR_KW(self, argc): return self.CALL_FUNCTION(argc)-2 def MAKE_FUNCTION(self, argc): return -argc def MAKE_CLOSURE(self, argc): # XXX need to account for free variables too! return -argc def BUILD_SLICE(self, argc): if argc == 2: return -1 elif argc == 3: return -2 def DUP_TOPX(self, argc): return argc findDepth = StackDepthTracker().findDepth
{ "repo_name": "MalloyPower/parsing-python", "path": "front-end/testsuite-python-lib/Python-2.4/Lib/compiler/pyassem.py", "copies": "14", "size": "26195", "license": "mit", "hash": -8285213154111827000, "line_mean": 31.0232273839, "line_max": 74, "alpha_frac": 0.5291467837, "autogenerated": false, "ratio": 3.9474080771549125, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0019012552776404219, "num_lines": 818 }
"""A flow graph representation for Python bytecode""" import dis import new import sys from compiler import misc from compiler.consts \ import CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS class FlowGraph: def __init__(self): self.current = self.entry = Block() self.exit = Block("exit") self.blocks = misc.Set() self.blocks.add(self.entry) self.blocks.add(self.exit) def startBlock(self, block): if self._debug: if self.current: print "end", repr(self.current) print " next", self.current.next print " ", self.current.get_children() print repr(block) self.current = block def nextBlock(self, block=None): # XXX think we need to specify when there is implicit transfer # from one block to the next. might be better to represent this # with explicit JUMP_ABSOLUTE instructions that are optimized # out when they are unnecessary. # # I think this strategy works: each block has a child # designated as "next" which is returned as the last of the # children. because the nodes in a graph are emitted in # reverse post order, the "next" block will always be emitted # immediately after its parent. # Worry: maintaining this invariant could be tricky if block is None: block = self.newBlock() # Note: If the current block ends with an unconditional # control transfer, then it is incorrect to add an implicit # transfer to the block graph. The current code requires # these edges to get the blocks emitted in the right order, # however. :-( If a client needs to remove these edges, call # pruneEdges(). self.current.addNext(block) self.startBlock(block) def newBlock(self): b = Block() self.blocks.add(b) return b def startExitBlock(self): self.startBlock(self.exit) _debug = 0 def _enable_debug(self): self._debug = 1 def _disable_debug(self): self._debug = 0 def emit(self, *inst): if self._debug: print "\t", inst if inst[0] in ['RETURN_VALUE', 'YIELD_VALUE']: self.current.addOutEdge(self.exit) if len(inst) == 2 and isinstance(inst[1], Block): self.current.addOutEdge(inst[1]) self.current.emit(inst) def getBlocksInOrder(self): """Return the blocks in reverse postorder i.e. each node appears before all of its successors """ # XXX make sure every node that doesn't have an explicit next # is set so that next points to exit for b in self.blocks.elements(): if b is self.exit: continue if not b.next: b.addNext(self.exit) order = dfs_postorder(self.entry, {}) order.reverse() self.fixupOrder(order, self.exit) # hack alert if not self.exit in order: order.append(self.exit) return order def fixupOrder(self, blocks, default_next): """Fixup bad order introduced by DFS.""" # XXX This is a total mess. There must be a better way to get # the code blocks in the right order. self.fixupOrderHonorNext(blocks, default_next) self.fixupOrderForward(blocks, default_next) def fixupOrderHonorNext(self, blocks, default_next): """Fix one problem with DFS. The DFS uses child block, but doesn't know about the special "next" block. As a result, the DFS can order blocks so that a block isn't next to the right block for implicit control transfers. """ index = {} for i in range(len(blocks)): index[blocks[i]] = i for i in range(0, len(blocks) - 1): b = blocks[i] n = blocks[i + 1] if not b.next or b.next[0] == default_next or b.next[0] == n: continue # The blocks are in the wrong order. Find the chain of # blocks to insert where they belong. cur = b chain = [] elt = cur while elt.next and elt.next[0] != default_next: chain.append(elt.next[0]) elt = elt.next[0] # Now remove the blocks in the chain from the current # block list, so that they can be re-inserted. l = [] for b in chain: assert index[b] > i l.append((index[b], b)) l.sort() l.reverse() for j, b in l: del blocks[index[b]] # Insert the chain in the proper location blocks[i:i + 1] = [cur] + chain # Finally, re-compute the block indexes for i in range(len(blocks)): index[blocks[i]] = i def fixupOrderForward(self, blocks, default_next): """Make sure all JUMP_FORWARDs jump forward""" index = {} chains = [] cur = [] for b in blocks: index[b] = len(chains) cur.append(b) if b.next and b.next[0] == default_next: chains.append(cur) cur = [] chains.append(cur) while 1: constraints = [] for i in range(len(chains)): l = chains[i] for b in l: for c in b.get_children(): if index[c] < i: forward_p = 0 for inst in b.insts: if inst[0] == 'JUMP_FORWARD': if inst[1] == c: forward_p = 1 if not forward_p: continue constraints.append((index[c], i)) if not constraints: break # XXX just do one for now # do swaps to get things in the right order goes_before, a_chain = constraints[0] assert a_chain > goes_before c = chains[a_chain] chains.remove(c) chains.insert(goes_before, c) del blocks[:] for c in chains: for b in c: blocks.append(b) def getBlocks(self): return self.blocks.elements() def getRoot(self): """Return nodes appropriate for use with dominator""" return self.entry def getContainedGraphs(self): l = [] for b in self.getBlocks(): l.extend(b.getContainedGraphs()) return l def dfs_postorder(b, seen): """Depth-first search of tree rooted at b, return in postorder""" order = [] seen[b] = b for c in b.get_children(): if seen.has_key(c): continue order = order + dfs_postorder(c, seen) order.append(b) return order class Block: _count = 0 def __init__(self, label=''): self.insts = [] self.inEdges = misc.Set() self.outEdges = misc.Set() self.label = label self.bid = Block._count self.next = [] Block._count = Block._count + 1 def __repr__(self): if self.label: return "<block %s id=%d>" % (self.label, self.bid) else: return "<block id=%d>" % (self.bid) def __str__(self): insts = map(str, self.insts) return "<block %s %d:\n%s>" % (self.label, self.bid, '\n'.join(insts)) def emit(self, inst): op = inst[0] if op[:4] == 'JUMP': self.outEdges.add(inst[1]) self.insts.append(inst) def getInstructions(self): return self.insts def addInEdge(self, block): self.inEdges.add(block) def addOutEdge(self, block): self.outEdges.add(block) def addNext(self, block): self.next.append(block) assert len(self.next) == 1, map(str, self.next) _uncond_transfer = ('RETURN_VALUE', 'RAISE_VARARGS', 'YIELD_VALUE', 'JUMP_ABSOLUTE', 'JUMP_FORWARD', 'CONTINUE_LOOP') def pruneNext(self): """Remove bogus edge for unconditional transfers Each block has a next edge that accounts for implicit control transfers, e.g. from a JUMP_IF_FALSE to the block that will be executed if the test is true. These edges must remain for the current assembler code to work. If they are removed, the dfs_postorder gets things in weird orders. However, they shouldn't be there for other purposes, e.g. conversion to SSA form. This method will remove the next edge when it follows an unconditional control transfer. """ try: op, arg = self.insts[-1] except (IndexError, ValueError): return if op in self._uncond_transfer: self.next = [] def get_children(self): if self.next and self.next[0] in self.outEdges: self.outEdges.remove(self.next[0]) return self.outEdges.elements() + self.next def getContainedGraphs(self): """Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body. """ contained = [] for inst in self.insts: if len(inst) == 1: continue op = inst[1] if hasattr(op, 'graph'): contained.append(op.graph) return contained # flags for code objects # the FlowGraph is transformed in place; it exists in one of these states RAW = "RAW" FLAT = "FLAT" CONV = "CONV" DONE = "DONE" class PyFlowGraph(FlowGraph): super_init = FlowGraph.__init__ def __init__(self, name, filename, args=(), optimized=0, klass=None): self.super_init() self.name = name self.filename = filename self.docstring = None self.args = args # XXX self.argcount = getArgCount(args) self.klass = klass if optimized: self.flags = CO_OPTIMIZED | CO_NEWLOCALS else: self.flags = 0 self.consts = [] self.names = [] # Free variables found by the symbol table scan, including # variables used only in nested scopes, are included here. self.freevars = [] self.cellvars = [] # The closure list is used to track the order of cell # variables and free variables in the resulting code object. # The offsets used by LOAD_CLOSURE/LOAD_DEREF refer to both # kinds of variables. self.closure = [] self.varnames = list(args) or [] for i in range(len(self.varnames)): var = self.varnames[i] if isinstance(var, TupleArg): self.varnames[i] = var.getName() self.stage = RAW def setDocstring(self, doc): self.docstring = doc def setFlag(self, flag): self.flags = self.flags | flag if flag == CO_VARARGS: self.argcount = self.argcount - 1 def checkFlag(self, flag): if self.flags & flag: return 1 def setFreeVars(self, names): self.freevars = list(names) def setCellVars(self, names): self.cellvars = names def getCode(self): """Get a Python code object""" assert self.stage == RAW self.computeStackDepth() self.flattenGraph() assert self.stage == FLAT self.convertArgs() assert self.stage == CONV self.makeByteCode() assert self.stage == DONE return self.newCodeObject() def dump(self, io=None): if io: save = sys.stdout sys.stdout = io pc = 0 for t in self.insts: opname = t[0] if opname == "SET_LINENO": print if len(t) == 1: print "\t", "%3d" % pc, opname pc = pc + 1 else: print "\t", "%3d" % pc, opname, t[1] pc = pc + 3 if io: sys.stdout = save def computeStackDepth(self): """Compute the max stack depth. Approach is to compute the stack effect of each basic block. Then find the path through the code with the largest total effect. """ depth = {} exit = None for b in self.getBlocks(): depth[b] = findDepth(b.getInstructions()) seen = {} def max_depth(b, d): if seen.has_key(b): return d seen[b] = 1 d = d + depth[b] children = b.get_children() if children: return max([max_depth(c, d) for c in children]) else: if not b.label == "exit": return max_depth(self.exit, d) else: return d self.stacksize = max_depth(self.entry, 0) def flattenGraph(self): """Arrange the blocks in order and resolve jumps""" assert self.stage == RAW self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": # arg takes 2 bytes pc = pc + 3 end[b] = pc pc = 0 for i in range(len(insts)): inst = insts[i] if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": pc = pc + 3 opname = inst[0] if self.hasjrel.has_elt(opname): oparg = inst[1] offset = begin[oparg] - pc insts[i] = opname, offset elif self.hasjabs.has_elt(opname): insts[i] = opname, begin[inst[1]] self.stage = FLAT hasjrel = misc.Set() for i in dis.hasjrel: hasjrel.add(dis.opname[i]) hasjabs = misc.Set() for i in dis.hasjabs: hasjabs.add(dis.opname[i]) def convertArgs(self): """Convert arguments from symbolic to concrete form""" assert self.stage == FLAT self.consts.insert(0, self.docstring) self.sort_cellvars() for i in range(len(self.insts)): t = self.insts[i] if len(t) == 2: opname, oparg = t conv = self._converters.get(opname, None) if conv: self.insts[i] = opname, conv(self, oparg) self.stage = CONV def sort_cellvars(self): """Sort cellvars in the order of varnames and prune from freevars. """ cells = {} for name in self.cellvars: cells[name] = 1 self.cellvars = [name for name in self.varnames if cells.has_key(name)] for name in self.cellvars: del cells[name] self.cellvars = self.cellvars + cells.keys() self.closure = self.cellvars + self.freevars def _lookupName(self, name, list): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before comparing the values. """ t = type(name) for i in range(len(list)): if t == type(list[i]) and list[i] == name: return i end = len(list) list.append(name) return end _converters = {} def _convert_LOAD_CONST(self, arg): if hasattr(arg, 'getCode'): arg = arg.getCode() return self._lookupName(arg, self.consts) def _convert_LOAD_FAST(self, arg): self._lookupName(arg, self.names) return self._lookupName(arg, self.varnames) _convert_STORE_FAST = _convert_LOAD_FAST _convert_DELETE_FAST = _convert_LOAD_FAST def _convert_LOAD_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) def _convert_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) _convert_STORE_NAME = _convert_NAME _convert_DELETE_NAME = _convert_NAME _convert_IMPORT_NAME = _convert_NAME _convert_IMPORT_FROM = _convert_NAME _convert_STORE_ATTR = _convert_NAME _convert_LOAD_ATTR = _convert_NAME _convert_DELETE_ATTR = _convert_NAME _convert_LOAD_GLOBAL = _convert_NAME _convert_STORE_GLOBAL = _convert_NAME _convert_DELETE_GLOBAL = _convert_NAME def _convert_DEREF(self, arg): self._lookupName(arg, self.names) self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _convert_LOAD_DEREF = _convert_DEREF _convert_STORE_DEREF = _convert_DEREF def _convert_LOAD_CLOSURE(self, arg): self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _cmp = list(dis.cmp_op) def _convert_COMPARE_OP(self, arg): return self._cmp.index(arg) # similarly for other opcodes... for name, obj in locals().items(): if name[:9] == "_convert_": opname = name[9:] _converters[opname] = obj del name, obj, opname def makeByteCode(self): assert self.stage == CONV self.lnotab = lnotab = LineAddrTable() for t in self.insts: opname = t[0] if len(t) == 1: lnotab.addCode(self.opnum[opname]) else: oparg = t[1] if opname == "SET_LINENO": lnotab.nextLine(oparg) continue hi, lo = twobyte(oparg) try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: print opname, oparg print self.opnum[opname], lo, hi raise self.stage = DONE opnum = {} for num in range(len(dis.opname)): opnum[dis.opname[num]] = num del num def newCodeObject(self): assert self.stage == DONE if (self.flags & CO_NEWLOCALS) == 0: nlocals = 0 else: nlocals = len(self.varnames) argcount = self.argcount if self.flags & CO_VARKEYWORDS: argcount = argcount - 1 return new.code(argcount, nlocals, self.stacksize, self.flags, self.lnotab.getCode(), self.getConsts(), tuple(self.names), tuple(self.varnames), self.filename, self.name, self.lnotab.firstline, self.lnotab.getTable(), tuple(self.freevars), tuple(self.cellvars)) def getConsts(self): """Return a tuple for the const slot of the code object Must convert references to code (MAKE_FUNCTION) to code objects recursively. """ l = [] for elt in self.consts: if isinstance(elt, PyFlowGraph): elt = elt.getCode() l.append(elt) return tuple(l) def isJump(opname): if opname[:4] == 'JUMP': return 1 class TupleArg: """Helper for marking func defs with nested tuples in arglist""" def __init__(self, count, names): self.count = count self.names = names def __repr__(self): return "TupleArg(%s, %s)" % (self.count, self.names) def getName(self): return ".%d" % self.count def getArgCount(args): argcount = len(args) if args: for arg in args: if isinstance(arg, TupleArg): numNames = len(misc.flatten(arg.names)) argcount = argcount - numNames return argcount def twobyte(val): """Convert an int argument into high and low bytes""" assert isinstance(val, int) return divmod(val, 256) class LineAddrTable: """lnotab This class builds the lnotab, which is documented in compile.c. Here's a brief recap: For each SET_LINENO instruction after the first one, two bytes are added to lnotab. (In some cases, multiple two-byte entries are added.) The first byte is the distance in bytes between the instruction for the last SET_LINENO and the current SET_LINENO. The second byte is offset in line numbers. If either offset is greater than 255, multiple two-byte entries are added -- see compile.c for the delicate details. """ def __init__(self): self.code = [] self.codeOffset = 0 self.firstline = 0 self.lastline = 0 self.lastoff = 0 self.lnotab = [] def addCode(self, *args): for arg in args: self.code.append(chr(arg)) self.codeOffset = self.codeOffset + len(args) def nextLine(self, lineno): if self.firstline == 0: self.firstline = lineno self.lastline = lineno else: # compute deltas addr = self.codeOffset - self.lastoff line = lineno - self.lastline # Python assumes that lineno always increases with # increasing bytecode address (lnotab is unsigned char). # Depending on when SET_LINENO instructions are emitted # this is not always true. Consider the code: # a = (1, # b) # In the bytecode stream, the assignment to "a" occurs # after the loading of "b". This works with the C Python # compiler because it only generates a SET_LINENO instruction # for the assignment. if line >= 0: push = self.lnotab.append while addr > 255: push(255); push(0) addr -= 255 while line > 255: push(addr); push(255) line -= 255 addr = 0 if addr > 0 or line > 0: push(addr); push(line) self.lastline = lineno self.lastoff = self.codeOffset def getCode(self): return ''.join(self.code) def getTable(self): return ''.join(map(chr, self.lnotab)) class StackDepthTracker: # XXX 1. need to keep track of stack depth on jumps # XXX 2. at least partly as a result, this code is broken def findDepth(self, insts, debug=0): depth = 0 maxDepth = 0 for i in insts: opname = i[0] if debug: print i, delta = self.effect.get(opname, None) if delta is not None: depth = depth + delta else: # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta is None: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth > maxDepth: maxDepth = depth if debug: print depth, maxDepth return maxDepth effect = { 'POP_TOP': -1, 'DUP_TOP': 1, 'LIST_APPEND': -2, 'SLICE+1': -1, 'SLICE+2': -1, 'SLICE+3': -2, 'STORE_SLICE+0': -1, 'STORE_SLICE+1': -2, 'STORE_SLICE+2': -2, 'STORE_SLICE+3': -3, 'DELETE_SLICE+0': -1, 'DELETE_SLICE+1': -2, 'DELETE_SLICE+2': -2, 'DELETE_SLICE+3': -3, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, # PRINT_EXPR? 'PRINT_ITEM': -1, 'RETURN_VALUE': -1, 'YIELD_VALUE': -1, 'EXEC_STMT': -3, 'BUILD_CLASS': -2, 'STORE_NAME': -1, 'STORE_ATTR': -2, 'DELETE_ATTR': -1, 'STORE_GLOBAL': -1, 'BUILD_MAP': 1, 'COMPARE_OP': -1, 'STORE_FAST': -1, 'IMPORT_STAR': -1, 'IMPORT_NAME': -1, 'IMPORT_FROM': 1, 'LOAD_ATTR': 0, # unlike other loads # close enough... 'SETUP_EXCEPT': 3, 'SETUP_FINALLY': 3, 'FOR_ITER': 1, 'WITH_CLEANUP': -1, } # use pattern match patterns = [ ('BINARY_', -1), ('LOAD_', 1), ] def UNPACK_SEQUENCE(self, count): return count-1 def BUILD_TUPLE(self, count): return -count+1 def BUILD_LIST(self, count): return -count+1 def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return -(lo + hi * 2) def CALL_FUNCTION_VAR(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_KW(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_VAR_KW(self, argc): return self.CALL_FUNCTION(argc)-2 def MAKE_FUNCTION(self, argc): return -argc def MAKE_CLOSURE(self, argc): # XXX need to account for free variables too! return -argc def BUILD_SLICE(self, argc): if argc == 2: return -1 elif argc == 3: return -2 def DUP_TOPX(self, argc): return argc findDepth = StackDepthTracker().findDepth
{ "repo_name": "fitermay/intellij-community", "path": "python/lib/Lib/compiler/pyassem.py", "copies": "93", "size": "26163", "license": "apache-2.0", "hash": 7222800565738363000, "line_mean": 30.9841075795, "line_max": 74, "alpha_frac": 0.5290295455, "autogenerated": false, "ratio": 3.9431801055011304, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
"""A flow graph representation for Python bytecode""" import dis import types import sys from compiler import misc from compiler.consts \ import CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS class FlowGraph: def __init__(self): self.current = self.entry = Block() self.exit = Block("exit") self.blocks = misc.Set() self.blocks.add(self.entry) self.blocks.add(self.exit) def startBlock(self, block): if self._debug: if self.current: print "end", repr(self.current) print " next", self.current.next print " ", self.current.get_children() print repr(block) self.current = block def nextBlock(self, block=None): # XXX think we need to specify when there is implicit transfer # from one block to the next. might be better to represent this # with explicit JUMP_ABSOLUTE instructions that are optimized # out when they are unnecessary. # # I think this strategy works: each block has a child # designated as "next" which is returned as the last of the # children. because the nodes in a graph are emitted in # reverse post order, the "next" block will always be emitted # immediately after its parent. # Worry: maintaining this invariant could be tricky if block is None: block = self.newBlock() # Note: If the current block ends with an unconditional # control transfer, then it is incorrect to add an implicit # transfer to the block graph. The current code requires # these edges to get the blocks emitted in the right order, # however. :-( If a client needs to remove these edges, call # pruneEdges(). self.current.addNext(block) self.startBlock(block) def newBlock(self): b = Block() self.blocks.add(b) return b def startExitBlock(self): self.startBlock(self.exit) _debug = 0 def _enable_debug(self): self._debug = 1 def _disable_debug(self): self._debug = 0 def emit(self, *inst): if self._debug: print "\t", inst if inst[0] in ['RETURN_VALUE', 'YIELD_VALUE']: self.current.addOutEdge(self.exit) if len(inst) == 2 and isinstance(inst[1], Block): self.current.addOutEdge(inst[1]) self.current.emit(inst) def getBlocksInOrder(self): """Return the blocks in reverse postorder i.e. each node appears before all of its successors """ # XXX make sure every node that doesn't have an explicit next # is set so that next points to exit for b in self.blocks.elements(): if b is self.exit: continue if not b.next: b.addNext(self.exit) order = dfs_postorder(self.entry, {}) order.reverse() self.fixupOrder(order, self.exit) # hack alert if not self.exit in order: order.append(self.exit) return order def fixupOrder(self, blocks, default_next): """Fixup bad order introduced by DFS.""" # XXX This is a total mess. There must be a better way to get # the code blocks in the right order. self.fixupOrderHonorNext(blocks, default_next) self.fixupOrderForward(blocks, default_next) def fixupOrderHonorNext(self, blocks, default_next): """Fix one problem with DFS. The DFS uses child block, but doesn't know about the special "next" block. As a result, the DFS can order blocks so that a block isn't next to the right block for implicit control transfers. """ index = {} for i in range(len(blocks)): index[blocks[i]] = i for i in range(0, len(blocks) - 1): b = blocks[i] n = blocks[i + 1] if not b.next or b.next[0] == default_next or b.next[0] == n: continue # The blocks are in the wrong order. Find the chain of # blocks to insert where they belong. cur = b chain = [] elt = cur while elt.next and elt.next[0] != default_next: chain.append(elt.next[0]) elt = elt.next[0] # Now remove the blocks in the chain from the current # block list, so that they can be re-inserted. l = [] for b in chain: assert index[b] > i l.append((index[b], b)) l.sort() l.reverse() for j, b in l: del blocks[index[b]] # Insert the chain in the proper location blocks = blocks[:i] + [cur] + [chain] + blocks[i + 1:] # Finally, re-compute the block indexes for i in range(len(blocks)): index[blocks[i]] = i def fixupOrderForward(self, blocks, default_next): """Make sure all JUMP_FORWARDs jump forward""" index = {} chains = [] cur = [] for b in blocks: index[b] = len(chains) cur.append(b) if b.next and b.next[0] == default_next: chains.append(cur) cur = [] chains.append(cur) while 1: constraints = [] for i in range(len(chains)): l = chains[i] for b in l: for c in b.get_children(): if index[c] < i: forward_p = 0 for inst in b.insts: if inst[0] == 'JUMP_FORWARD': if inst[1] == c: forward_p = 1 if not forward_p: continue constraints.append((index[c], i)) if not constraints: break # XXX just do one for now # do swaps to get things in the right order goes_before, a_chain = constraints[0] assert a_chain > goes_before c = chains[a_chain] chains.remove(c) chains.insert(goes_before, c) while len(blocks) > 0: del blocks[0] for c in chains: for b in c: blocks.append(b) def getBlocks(self): return self.blocks.elements() def getRoot(self): """Return nodes appropriate for use with dominator""" return self.entry def getContainedGraphs(self): l = [] for b in self.getBlocks(): l.extend(b.getContainedGraphs()) return l def dfs_postorder(b, seen): """Depth-first search of tree rooted at b, return in postorder""" order = [] seen[b] = b for c in b.get_children(): if c in seen: continue order = order + dfs_postorder(c, seen) order.append(b) return order class Block: _count = 0 def __init__(self, label=''): self.insts = [] self.inEdges = misc.Set() self.outEdges = misc.Set() self.label = label self.bid = Block._count self.next = [] Block._count = Block._count + 1 def __repr__(self): if self.label: return "<block %s id=%d>" % (self.label, self.bid) else: return "<block id=%d>" % (self.bid) def __str__(self): insts = map(str, self.insts) return "<block %s %d:\n%s>" % (self.label, self.bid, '\n'.join(insts)) def emit(self, inst): op = inst[0] if op[:4] == 'JUMP': self.outEdges.add(inst[1]) self.insts.append(inst) def getInstructions(self): return self.insts def addInEdge(self, block): self.inEdges.add(block) def addOutEdge(self, block): self.outEdges.add(block) def addNext(self, block): self.next.append(block) assert len(self.next) == 1, map(str, self.next) _uncond_transfer = ('RETURN_VALUE', 'RAISE_VARARGS', 'YIELD_VALUE', 'JUMP_ABSOLUTE', 'JUMP_FORWARD', 'CONTINUE_LOOP') def pruneNext(self): """Remove bogus edge for unconditional transfers Each block has a next edge that accounts for implicit control transfers, e.g. from a JUMP_IF_FALSE to the block that will be executed if the test is true. These edges must remain for the current assembler code to work. If they are removed, the dfs_postorder gets things in weird orders. However, they shouldn't be there for other purposes, e.g. conversion to SSA form. This method will remove the next edge when it follows an unconditional control transfer. """ try: op, arg = self.insts[-1] except (IndexError, ValueError): return if op in self._uncond_transfer: self.next = [] def get_children(self): if self.next and self.next[0] in self.outEdges: self.outEdges.remove(self.next[0]) return self.outEdges.elements() + self.next def getContainedGraphs(self): """Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body. """ contained = [] for inst in self.insts: if len(inst) == 1: continue op = inst[1] if hasattr(op, 'graph'): contained.append(op.graph) return contained # flags for code objects # the FlowGraph is transformed in place; it exists in one of these states RAW = "RAW" FLAT = "FLAT" CONV = "CONV" DONE = "DONE" class PyFlowGraph(FlowGraph): super_init = FlowGraph.__init__ def __init__(self, name, filename, args=(), optimized=0, klass=None): self.super_init() self.hasjrel = misc.Set() self.hasjabs = misc.Set() for i in dis.hasjrel: self.hasjrel.add(dis.opname[i]) for i in dis.hasjabs: self.hasjabs.add(dis.opname[i]) self.name = name self.filename = filename self.docstring = None self.args = args # XXX self.argcount = getArgCount(args) self.klass = klass if optimized: self.flags = CO_OPTIMIZED | CO_NEWLOCALS else: self.flags = 0 self.consts = [] self.names = [] # Free variables found by the symbol table scan, including # variables used only in nested scopes, are included here. self.freevars = [] self.cellvars = [] # The closure list is used to track the order of cell # variables and free variables in the resulting code object. # The offsets used by LOAD_CLOSURE/LOAD_DEREF refer to both # kinds of variables. self.closure = [] self.varnames = list(args) or [] for i in range(len(self.varnames)): var = self.varnames[i] if isinstance(var, TupleArg): self.varnames[i] = var.getName() self.stage = RAW for name, obj in dir(self): if name[:9] == "_convert_": opname = name[9:] self._converters[opname] = obj for num in range(len(dis.opname)): opnum[dis.opname[num]] = num def setDocstring(self, doc): self.docstring = doc def setFlag(self, flag): self.flags = self.flags | flag if flag == CO_VARARGS: self.argcount = self.argcount - 1 def checkFlag(self, flag): if self.flags & flag: return 1 def setFreeVars(self, names): self.freevars = list(names) def setCellVars(self, names): self.cellvars = names def getCode(self): """Get a Python code object""" assert self.stage == RAW self.computeStackDepth() self.flattenGraph() assert self.stage == FLAT self.convertArgs() assert self.stage == CONV self.makeByteCode() assert self.stage == DONE return self.newCodeObject() def dump(self, io=None): if io: save = sys.stdout sys.stdout = io pc = 0 for t in self.insts: opname = t[0] if opname == "SET_LINENO": print if len(t) == 1: print "\t", "%3d" % pc, opname pc = pc + 1 else: print "\t", "%3d" % pc, opname, t[1] pc = pc + 3 if io: sys.stdout = save def computeStackDepth(self): """Compute the max stack depth. Approach is to compute the stack effect of each basic block. Then find the path through the code with the largest total effect. """ depth = {} exit = None for b in self.getBlocks(): depth[b] = findDepth(b.getInstructions()) seen = {} def max_depth(b, d): if b in seen: return d seen[b] = 1 d = d + depth[b] children = b.get_children() if children: return max([max_depth(c, d) for c in children]) else: if not b.label == "exit": return max_depth(self.exit, d) else: return d self.stacksize = max_depth(self.entry, 0) def flattenGraph(self): """Arrange the blocks in order and resolve jumps""" assert self.stage == RAW self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": # arg takes 2 bytes pc = pc + 3 end[b] = pc pc = 0 for i in range(len(insts)): inst = insts[i] if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": pc = pc + 3 opname = inst[0] if self.hasjrel.has_elt(opname): oparg = inst[1] offset = begin[oparg] - pc insts[i] = opname, offset elif self.hasjabs.has_elt(opname): insts[i] = opname, begin[inst[1]] self.stage = FLAT # MOVED to constructor #hasjrel = misc.Set() #for i in dis.hasjrel: # hasjrel.add(dis.opname[i]) #hasjabs = misc.Set() #for i in dis.hasjabs: # hasjabs.add(dis.opname[i]) def convertArgs(self): """Convert arguments from symbolic to concrete form""" assert self.stage == FLAT self.consts.insert(0, self.docstring) self.sort_cellvars() for i in range(len(self.insts)): t = self.insts[i] if len(t) == 2: opname, oparg = t conv = self._converters.get(opname, None) if conv: self.insts[i] = opname, conv(self, oparg) self.stage = CONV def sort_cellvars(self): """Sort cellvars in the order of varnames and prune from freevars. """ cells = {} for name in self.cellvars: cells[name] = 1 self.cellvars = [name for name in self.varnames if name in cells] for name in self.cellvars: del cells[name] self.cellvars = self.cellvars + cells.keys() self.closure = self.cellvars + self.freevars def _lookupName(self, name, list): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before comparing the values. """ t = type(name) for i in range(len(list)): if t == type(list[i]) and list[i] == name: return i end = len(list) list.append(name) return end _converters = {} def _convert_LOAD_CONST(self, arg): if hasattr(arg, 'getCode'): arg = arg.getCode() return self._lookupName(arg, self.consts) def _convert_LOAD_FAST(self, arg): self._lookupName(arg, self.names) return self._lookupName(arg, self.varnames) _convert_STORE_FAST = _convert_LOAD_FAST _convert_DELETE_FAST = _convert_LOAD_FAST def _convert_LOAD_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) def _convert_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) _convert_STORE_NAME = _convert_NAME _convert_DELETE_NAME = _convert_NAME _convert_IMPORT_NAME = _convert_NAME _convert_IMPORT_FROM = _convert_NAME _convert_STORE_ATTR = _convert_NAME _convert_LOAD_ATTR = _convert_NAME _convert_DELETE_ATTR = _convert_NAME _convert_LOAD_GLOBAL = _convert_NAME _convert_STORE_GLOBAL = _convert_NAME _convert_DELETE_GLOBAL = _convert_NAME def _convert_DEREF(self, arg): self._lookupName(arg, self.names) self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _convert_LOAD_DEREF = _convert_DEREF _convert_STORE_DEREF = _convert_DEREF def _convert_LOAD_CLOSURE(self, arg): self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _cmp = list(dis.cmp_op) def _convert_COMPARE_OP(self, arg): return self._cmp.index(arg) # similarly for other opcodes... # MOVED to constructor #for name, obj in locals().items(): # if name[:9] == "_convert_": # opname = name[9:] # _converters[opname] = obj #del name, obj, opname def makeByteCode(self): assert self.stage == CONV self.lnotab = lnotab = LineAddrTable() for t in self.insts: opname = t[0] if len(t) == 1: lnotab.addCode(self.opnum[opname]) else: oparg = t[1] if opname == "SET_LINENO": lnotab.nextLine(oparg) continue hi, lo = twobyte(oparg) try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: print opname, oparg print self.opnum[opname], lo, hi raise self.stage = DONE opnum = {} # MOVED to constructor #for num in range(len(dis.opname)): # opnum[dis.opname[num]] = num #del num def newCodeObject(self): assert self.stage == DONE if (self.flags & CO_NEWLOCALS) == 0: nlocals = 0 else: nlocals = len(self.varnames) argcount = self.argcount if self.flags & CO_VARKEYWORDS: argcount = argcount - 1 return types.CodeType(argcount, nlocals, self.stacksize, self.flags, self.lnotab.getCode(), self.getConsts(), tuple(self.names), tuple(self.varnames), self.filename, self.name, self.lnotab.firstline, self.lnotab.getTable(), tuple(self.freevars), tuple(self.cellvars)) def getConsts(self): """Return a tuple for the const slot of the code object Must convert references to code (MAKE_FUNCTION) to code objects recursively. """ l = [] for elt in self.consts: if isinstance(elt, PyFlowGraph): elt = elt.getCode() l.append(elt) return tuple(l) def isJump(opname): if opname[:4] == 'JUMP': return 1 class TupleArg: """Helper for marking func defs with nested tuples in arglist""" def __init__(self, count, names): self.count = count self.names = names def __repr__(self): return "TupleArg(%s, %s)" % (self.count, self.names) def getName(self): return ".%d" % self.count def getArgCount(args): argcount = len(args) if args: for arg in args: if isinstance(arg, TupleArg): numNames = len(misc.flatten(arg.names)) argcount = argcount - numNames return argcount def twobyte(val): """Convert an int argument into high and low bytes""" assert isinstance(val, int) return divmod(val, 256) class LineAddrTable: """lnotab This class builds the lnotab, which is documented in compile.c. Here's a brief recap: For each SET_LINENO instruction after the first one, two bytes are added to lnotab. (In some cases, multiple two-byte entries are added.) The first byte is the distance in bytes between the instruction for the last SET_LINENO and the current SET_LINENO. The second byte is offset in line numbers. If either offset is greater than 255, multiple two-byte entries are added -- see compile.c for the delicate details. """ def __init__(self): self.code = [] self.codeOffset = 0 self.firstline = 0 self.lastline = 0 self.lastoff = 0 self.lnotab = [] def addCode(self, *args): for arg in args: self.code.append(chr(arg)) self.codeOffset = self.codeOffset + len(args) def nextLine(self, lineno): if self.firstline == 0: self.firstline = lineno self.lastline = lineno else: # compute deltas addr = self.codeOffset - self.lastoff line = lineno - self.lastline # Python assumes that lineno always increases with # increasing bytecode address (lnotab is unsigned char). # Depending on when SET_LINENO instructions are emitted # this is not always true. Consider the code: # a = (1, # b) # In the bytecode stream, the assignment to "a" occurs # after the loading of "b". This works with the C Python # compiler because it only generates a SET_LINENO instruction # for the assignment. if line >= 0: push = self.lnotab.append while addr > 255: push(255); push(0) addr -= 255 while line > 255: push(addr); push(255) line -= 255 addr = 0 if addr > 0 or line > 0: push(addr); push(line) self.lastline = lineno self.lastoff = self.codeOffset def getCode(self): return ''.join(self.code) def getTable(self): return ''.join(map(chr, self.lnotab)) class StackDepthTracker: # XXX 1. need to keep track of stack depth on jumps # XXX 2. at least partly as a result, this code is broken def findDepth(self, insts, debug=0): depth = 0 maxDepth = 0 for i in insts: opname = i[0] if debug: print i, delta = self.effect.get(opname, None) if delta is not None: depth = depth + delta else: # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta is None: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth > maxDepth: maxDepth = depth if debug: print depth, maxDepth return maxDepth effect = { 'POP_TOP': -1, 'DUP_TOP': 1, 'LIST_APPEND': -2, 'SLICE+1': -1, 'SLICE+2': -1, 'SLICE+3': -2, 'STORE_SLICE+0': -1, 'STORE_SLICE+1': -2, 'STORE_SLICE+2': -2, 'STORE_SLICE+3': -3, 'DELETE_SLICE+0': -1, 'DELETE_SLICE+1': -2, 'DELETE_SLICE+2': -2, 'DELETE_SLICE+3': -3, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, # PRINT_EXPR? 'PRINT_ITEM': -1, 'RETURN_VALUE': -1, 'YIELD_VALUE': -1, 'EXEC_STMT': -3, 'BUILD_CLASS': -2, 'STORE_NAME': -1, 'STORE_ATTR': -2, 'DELETE_ATTR': -1, 'STORE_GLOBAL': -1, 'BUILD_MAP': 1, 'COMPARE_OP': -1, 'STORE_FAST': -1, 'IMPORT_STAR': -1, 'IMPORT_NAME': -1, 'IMPORT_FROM': 1, 'LOAD_ATTR': 0, # unlike other loads # close enough... 'SETUP_EXCEPT': 3, 'SETUP_FINALLY': 3, 'FOR_ITER': 1, 'WITH_CLEANUP': -1, } # use pattern match patterns = [ ('BINARY_', -1), ('LOAD_', 1), ] def UNPACK_SEQUENCE(self, count): return count-1 def BUILD_TUPLE(self, count): return -count+1 def BUILD_LIST(self, count): return -count+1 def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return -(lo + hi * 2) def CALL_FUNCTION_VAR(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_KW(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_VAR_KW(self, argc): return self.CALL_FUNCTION(argc)-2 def MAKE_FUNCTION(self, argc): return -argc def MAKE_CLOSURE(self, argc): # XXX need to account for free variables too! return -argc def BUILD_SLICE(self, argc): if argc == 2: return -1 elif argc == 3: return -2 def DUP_TOPX(self, argc): return argc findDepth = StackDepthTracker().findDepth
{ "repo_name": "pyjs/pyjs", "path": "pgen/lib2to3/compiler/pyassem.py", "copies": "6", "size": "26766", "license": "apache-2.0", "hash": -7717533171647056000, "line_mean": 30.9784946237, "line_max": 76, "alpha_frac": 0.5285436748, "autogenerated": false, "ratio": 3.925208974923009, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002175143496556293, "num_lines": 837 }
"""A flow graph representation for Python bytecode""" import dis import types import sys from pycompiler import misc from pycompiler.consts \ import CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS class FlowGraph: def __init__(self): self.current = self.entry = Block() self.exit = Block("exit") self.blocks = misc.Set() self.blocks.add(self.entry) self.blocks.add(self.exit) def startBlock(self, block): if self._debug: if self.current: print("end", repr(self.current)) print(" next", self.current.next) print(" ", self.current.get_children()) print(repr(block)) self.current = block def nextBlock(self, block=None): # XXX think we need to specify when there is implicit transfer # from one block to the next. might be better to represent this # with explicit JUMP_ABSOLUTE instructions that are optimized # out when they are unnecessary. # # I think this strategy works: each block has a child # designated as "next" which is returned as the last of the # children. because the nodes in a graph are emitted in # reverse post order, the "next" block will always be emitted # immediately after its parent. # Worry: maintaining this invariant could be tricky if block is None: block = self.newBlock() # Note: If the current block ends with an unconditional # control transfer, then it is incorrect to add an implicit # transfer to the block graph. The current code requires # these edges to get the blocks emitted in the right order, # however. :-( If a client needs to remove these edges, call # pruneEdges(). self.current.addNext(block) self.startBlock(block) def newBlock(self): b = Block() self.blocks.add(b) return b def startExitBlock(self): self.startBlock(self.exit) _debug = 0 def _enable_debug(self): self._debug = 1 def _disable_debug(self): self._debug = 0 def emit(self, *inst): if self._debug: print("\t", inst) if inst[0] in ['RETURN_VALUE', 'YIELD_VALUE']: self.current.addOutEdge(self.exit) if len(inst) == 2 and isinstance(inst[1], Block): self.current.addOutEdge(inst[1]) self.current.emit(inst) def getBlocksInOrder(self): """Return the blocks in reverse postorder i.e. each node appears before all of its successors """ # XXX make sure every node that doesn't have an explicit next # is set so that next points to exit for b in self.blocks.elements(): if b is self.exit: continue if not b.next: b.addNext(self.exit) order = dfs_postorder(self.entry, {}) order.reverse() self.fixupOrder(order, self.exit) # hack alert if not self.exit in order: order.append(self.exit) return order def fixupOrder(self, blocks, default_next): """Fixup bad order introduced by DFS.""" # XXX This is a total mess. There must be a better way to get # the code blocks in the right order. self.fixupOrderHonorNext(blocks, default_next) self.fixupOrderForward(blocks, default_next) def fixupOrderHonorNext(self, blocks, default_next): """Fix one problem with DFS. The DFS uses child block, but doesn't know about the special "next" block. As a result, the DFS can order blocks so that a block isn't next to the right block for implicit control transfers. """ index = {} for i in range(len(blocks)): index[blocks[i]] = i for i in range(0, len(blocks) - 1): b = blocks[i] n = blocks[i + 1] if not b.next or b.next[0] == default_next or b.next[0] == n: continue # The blocks are in the wrong order. Find the chain of # blocks to insert where they belong. cur = b chain = [] elt = cur while elt.next and elt.next[0] != default_next: chain.append(elt.next[0]) elt = elt.next[0] # Now remove the blocks in the chain from the current # block list, so that they can be re-inserted. l = [] for b in chain: assert index[b] > i l.append((index[b], b)) l.sort() l.reverse() for j, b in l: del blocks[index[b]] # Insert the chain in the proper location blocks = blocks[:i] + [cur] + [chain] + blocks[i + 1:] # Finally, re-compute the block indexes for i in range(len(blocks)): index[blocks[i]] = i def fixupOrderForward(self, blocks, default_next): """Make sure all JUMP_FORWARDs jump forward""" index = {} chains = [] cur = [] for b in blocks: index[b] = len(chains) cur.append(b) if b.next and b.next[0] == default_next: chains.append(cur) cur = [] chains.append(cur) while 1: constraints = [] for i in range(len(chains)): l = chains[i] for b in l: for c in b.get_children(): if index[c] < i: forward_p = 0 for inst in b.insts: if inst[0] == 'JUMP_FORWARD': if inst[1] == c: forward_p = 1 if not forward_p: continue constraints.append((index[c], i)) if not constraints: break # XXX just do one for now # do swaps to get things in the right order goes_before, a_chain = constraints[0] assert a_chain > goes_before c = chains[a_chain] chains.remove(c) chains.insert(goes_before, c) while len(blocks) > 0: del blocks[0] for c in chains: for b in c: blocks.append(b) def getBlocks(self): return self.blocks.elements() def getRoot(self): """Return nodes appropriate for use with dominator""" return self.entry def getContainedGraphs(self): l = [] for b in self.getBlocks(): l.extend(b.getContainedGraphs()) return l def dfs_postorder(b, seen): """Depth-first search of tree rooted at b, return in postorder""" order = [] seen[b] = b for c in b.get_children(): if c in seen: continue order = order + dfs_postorder(c, seen) order.append(b) return order class Block: _count = 0 def __init__(self, label=''): self.insts = [] self.inEdges = misc.Set() self.outEdges = misc.Set() self.label = label self.bid = Block._count self.next = [] Block._count = Block._count + 1 def __repr__(self): if self.label: return "<block %s id=%d>" % (self.label, self.bid) else: return "<block id=%d>" % (self.bid) def __str__(self): insts = map(str, self.insts) return "<block %s %d:\n%s>" % (self.label, self.bid, '\n'.join(insts)) def emit(self, inst): op = inst[0] if op[:4] == 'JUMP': self.outEdges.add(inst[1]) self.insts.append(inst) def getInstructions(self): return self.insts def addInEdge(self, block): self.inEdges.add(block) def addOutEdge(self, block): self.outEdges.add(block) def addNext(self, block): self.next.append(block) assert len(self.next) == 1, map(str, self.next) _uncond_transfer = ('RETURN_VALUE', 'RAISE_VARARGS', 'YIELD_VALUE', 'JUMP_ABSOLUTE', 'JUMP_FORWARD', 'CONTINUE_LOOP') def pruneNext(self): """Remove bogus edge for unconditional transfers Each block has a next edge that accounts for implicit control transfers, e.g. from a JUMP_IF_FALSE to the block that will be executed if the test is true. These edges must remain for the current assembler code to work. If they are removed, the dfs_postorder gets things in weird orders. However, they shouldn't be there for other purposes, e.g. conversion to SSA form. This method will remove the next edge when it follows an unconditional control transfer. """ try: op, arg = self.insts[-1] except (IndexError, ValueError): return if op in self._uncond_transfer: self.next = [] def get_children(self): if self.next and self.next[0] in self.outEdges: self.outEdges.remove(self.next[0]) return self.outEdges.elements() + self.next def getContainedGraphs(self): """Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body. """ contained = [] for inst in self.insts: if len(inst) == 1: continue op = inst[1] if hasattr(op, 'graph'): contained.append(op.graph) return contained # flags for code objects # the FlowGraph is transformed in place; it exists in one of these states RAW = "RAW" FLAT = "FLAT" CONV = "CONV" DONE = "DONE" class PyFlowGraph(FlowGraph): super_init = FlowGraph.__init__ def __init__(self, name, filename, args=(), optimized=0, klass=None): self.super_init() self.hasjrel = misc.Set() self.hasjabs = misc.Set() for i in dis.hasjrel: self.hasjrel.add(dis.opname[i]) for i in dis.hasjabs: self.hasjabs.add(dis.opname[i]) self.name = name self.filename = filename self.docstring = None self.args = args # XXX self.argcount = getArgCount(args) self.klass = klass if optimized: self.flags = CO_OPTIMIZED | CO_NEWLOCALS else: self.flags = 0 self.consts = [] self.names = [] # Free variables found by the symbol table scan, including # variables used only in nested scopes, are included here. self.freevars = [] self.cellvars = [] # The closure list is used to track the order of cell # variables and free variables in the resulting code object. # The offsets used by LOAD_CLOSURE/LOAD_DEREF refer to both # kinds of variables. self.closure = [] self.varnames = list(args) or [] for i in range(len(self.varnames)): var = self.varnames[i] if isinstance(var, TupleArg): self.varnames[i] = var.getName() self.stage = RAW for name, obj in dir(self): if name[:9] == "_convert_": opname = name[9:] self._converters[opname] = obj for num in range(len(dis.opname)): opnum[dis.opname[num]] = num def setDocstring(self, doc): self.docstring = doc def setFlag(self, flag): self.flags = self.flags | flag if flag == CO_VARARGS: self.argcount = self.argcount - 1 def checkFlag(self, flag): if self.flags & flag: return 1 def setFreeVars(self, names): self.freevars = list(names) def setCellVars(self, names): self.cellvars = names def getCode(self): """Get a Python code object""" assert self.stage == RAW self.computeStackDepth() self.flattenGraph() assert self.stage == FLAT self.convertArgs() assert self.stage == CONV self.makeByteCode() assert self.stage == DONE return self.newCodeObject() def dump(self, io=None): if io: save = sys.stdout sys.stdout = io pc = 0 for t in self.insts: opname = t[0] if opname == "SET_LINENO": print() if len(t) == 1: print("\t", "%3d" % pc, opname) pc = pc + 1 else: print("\t", "%3d" % pc, opname, t[1]) pc = pc + 3 if io: sys.stdout = save def computeStackDepth(self): """Compute the max stack depth. Approach is to compute the stack effect of each basic block. Then find the path through the code with the largest total effect. """ depth = {} exit = None for b in self.getBlocks(): depth[b] = findDepth(b.getInstructions()) seen = {} def max_depth(b, d): if b in seen: return d seen[b] = 1 d = d + depth[b] children = b.get_children() if children: return max([max_depth(c, d) for c in children]) else: if not b.label == "exit": return max_depth(self.exit, d) else: return d self.stacksize = max_depth(self.entry, 0) def flattenGraph(self): """Arrange the blocks in order and resolve jumps""" assert self.stage == RAW self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": # arg takes 2 bytes pc = pc + 3 end[b] = pc pc = 0 for i in range(len(insts)): inst = insts[i] if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": pc = pc + 3 opname = inst[0] if self.hasjrel.has_elt(opname): oparg = inst[1] offset = begin[oparg] - pc insts[i] = opname, offset elif self.hasjabs.has_elt(opname): insts[i] = opname, begin[inst[1]] self.stage = FLAT # MOVED to constructor #hasjrel = misc.Set() #for i in dis.hasjrel: # hasjrel.add(dis.opname[i]) #hasjabs = misc.Set() #for i in dis.hasjabs: # hasjabs.add(dis.opname[i]) def convertArgs(self): """Convert arguments from symbolic to concrete form""" assert self.stage == FLAT self.consts.insert(0, self.docstring) self.sort_cellvars() for i in range(len(self.insts)): t = self.insts[i] if len(t) == 2: opname, oparg = t conv = self._converters.get(opname, None) if conv: self.insts[i] = opname, conv(self, oparg) self.stage = CONV def sort_cellvars(self): """Sort cellvars in the order of varnames and prune from freevars. """ cells = {} for name in self.cellvars: cells[name] = 1 self.cellvars = [name for name in self.varnames if name in cells] for name in self.cellvars: del cells[name] self.cellvars = self.cellvars + cells.keys() self.closure = self.cellvars + self.freevars def _lookupName(self, name, list): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before comparing the values. """ t = type(name) for i in range(len(list)): if t == type(list[i]) and list[i] == name: return i end = len(list) list.append(name) return end _converters = {} def _convert_LOAD_CONST(self, arg): if hasattr(arg, 'getCode'): arg = arg.getCode() return self._lookupName(arg, self.consts) def _convert_LOAD_FAST(self, arg): self._lookupName(arg, self.names) return self._lookupName(arg, self.varnames) _convert_STORE_FAST = _convert_LOAD_FAST _convert_DELETE_FAST = _convert_LOAD_FAST def _convert_LOAD_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) def _convert_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) _convert_STORE_NAME = _convert_NAME _convert_DELETE_NAME = _convert_NAME _convert_IMPORT_NAME = _convert_NAME _convert_IMPORT_FROM = _convert_NAME _convert_STORE_ATTR = _convert_NAME _convert_LOAD_ATTR = _convert_NAME _convert_DELETE_ATTR = _convert_NAME _convert_LOAD_GLOBAL = _convert_NAME _convert_STORE_GLOBAL = _convert_NAME _convert_DELETE_GLOBAL = _convert_NAME def _convert_DEREF(self, arg): self._lookupName(arg, self.names) self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _convert_LOAD_DEREF = _convert_DEREF _convert_STORE_DEREF = _convert_DEREF def _convert_LOAD_CLOSURE(self, arg): self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _cmp = list(dis.cmp_op) def _convert_COMPARE_OP(self, arg): return self._cmp.index(arg) # similarly for other opcodes... # MOVED to constructor #for name, obj in locals().items(): # if name[:9] == "_convert_": # opname = name[9:] # _converters[opname] = obj #del name, obj, opname def makeByteCode(self): assert self.stage == CONV self.lnotab = lnotab = LineAddrTable() for t in self.insts: opname = t[0] if len(t) == 1: lnotab.addCode(self.opnum[opname]) else: oparg = t[1] if opname == "SET_LINENO": lnotab.nextLine(oparg) continue hi, lo = twobyte(oparg) try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: print(opname, oparg) print(self.opnum[opname], lo, hi) raise self.stage = DONE opnum = {} # MOVED to constructor #for num in range(len(dis.opname)): # opnum[dis.opname[num]] = num #del num def newCodeObject(self): assert self.stage == DONE if (self.flags & CO_NEWLOCALS) == 0: nlocals = 0 else: nlocals = len(self.varnames) argcount = self.argcount if self.flags & CO_VARKEYWORDS: argcount = argcount - 1 return types.CodeType(argcount, nlocals, self.stacksize, self.flags, self.lnotab.getCode(), self.getConsts(), tuple(self.names), tuple(self.varnames), self.filename, self.name, self.lnotab.firstline, self.lnotab.getTable(), tuple(self.freevars), tuple(self.cellvars)) def getConsts(self): """Return a tuple for the const slot of the code object Must convert references to code (MAKE_FUNCTION) to code objects recursively. """ l = [] for elt in self.consts: if isinstance(elt, PyFlowGraph): elt = elt.getCode() l.append(elt) return tuple(l) def isJump(opname): if opname[:4] == 'JUMP': return 1 class TupleArg: """Helper for marking func defs with nested tuples in arglist""" def __init__(self, count, names): self.count = count self.names = names def __repr__(self): return "TupleArg(%s, %s)" % (self.count, self.names) def getName(self): return ".%d" % self.count def getArgCount(args): argcount = len(args) if args: for arg in args: if isinstance(arg, TupleArg): numNames = len(misc.flatten(arg.names)) argcount = argcount - numNames return argcount def twobyte(val): """Convert an int argument into high and low bytes""" assert isinstance(val, int) return divmod(val, 256) class LineAddrTable: """lnotab This class builds the lnotab, which is documented in compile.c. Here's a brief recap: For each SET_LINENO instruction after the first one, two bytes are added to lnotab. (In some cases, multiple two-byte entries are added.) The first byte is the distance in bytes between the instruction for the last SET_LINENO and the current SET_LINENO. The second byte is offset in line numbers. If either offset is greater than 255, multiple two-byte entries are added -- see compile.c for the delicate details. """ def __init__(self): self.code = [] self.codeOffset = 0 self.firstline = 0 self.lastline = 0 self.lastoff = 0 self.lnotab = [] def addCode(self, *args): for arg in args: self.code.append(chr(arg)) self.codeOffset = self.codeOffset + len(args) def nextLine(self, lineno): if self.firstline == 0: self.firstline = lineno self.lastline = lineno else: # compute deltas addr = self.codeOffset - self.lastoff line = lineno - self.lastline # Python assumes that lineno always increases with # increasing bytecode address (lnotab is unsigned char). # Depending on when SET_LINENO instructions are emitted # this is not always true. Consider the code: # a = (1, # b) # In the bytecode stream, the assignment to "a" occurs # after the loading of "b". This works with the C Python # compiler because it only generates a SET_LINENO instruction # for the assignment. if line >= 0: push = self.lnotab.append while addr > 255: push(255); push(0) addr -= 255 while line > 255: push(addr); push(255) line -= 255 addr = 0 if addr > 0 or line > 0: push(addr); push(line) self.lastline = lineno self.lastoff = self.codeOffset def getCode(self): return ''.join(self.code) def getTable(self): return ''.join(map(chr, self.lnotab)) class StackDepthTracker: # XXX 1. need to keep track of stack depth on jumps # XXX 2. at least partly as a result, this code is broken def findDepth(self, insts, debug=0): depth = 0 maxDepth = 0 for i in insts: opname = i[0] if debug: print(i), delta = self.effect.get(opname, None) if delta is not None: depth = depth + delta else: # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta is None: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth > maxDepth: maxDepth = depth if debug: print(depth, maxDepth) return maxDepth effect = { 'POP_TOP': -1, 'DUP_TOP': 1, 'LIST_APPEND': -2, 'SLICE+1': -1, 'SLICE+2': -1, 'SLICE+3': -2, 'STORE_SLICE+0': -1, 'STORE_SLICE+1': -2, 'STORE_SLICE+2': -2, 'STORE_SLICE+3': -3, 'DELETE_SLICE+0': -1, 'DELETE_SLICE+1': -2, 'DELETE_SLICE+2': -2, 'DELETE_SLICE+3': -3, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, # PRINT_EXPR? 'PRINT_ITEM': -1, 'RETURN_VALUE': -1, 'YIELD_VALUE': -1, 'EXEC_STMT': -3, 'BUILD_CLASS': -2, 'STORE_NAME': -1, 'STORE_ATTR': -2, 'DELETE_ATTR': -1, 'STORE_GLOBAL': -1, 'BUILD_MAP': 1, 'COMPARE_OP': -1, 'STORE_FAST': -1, 'IMPORT_STAR': -1, 'IMPORT_NAME': -1, 'IMPORT_FROM': 1, 'LOAD_ATTR': 0, # unlike other loads # close enough... 'SETUP_EXCEPT': 3, 'SETUP_FINALLY': 3, 'FOR_ITER': 1, 'WITH_CLEANUP': -1, } # use pattern match patterns = [ ('BINARY_', -1), ('LOAD_', 1), ] def UNPACK_SEQUENCE(self, count): return count-1 def BUILD_TUPLE(self, count): return -count+1 def BUILD_LIST(self, count): return -count+1 def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return -(lo + hi * 2) def CALL_FUNCTION_VAR(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_KW(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_VAR_KW(self, argc): return self.CALL_FUNCTION(argc)-2 def MAKE_FUNCTION(self, argc): return -argc def MAKE_CLOSURE(self, argc): # XXX need to account for free variables too! return -argc def BUILD_SLICE(self, argc): if argc == 2: return -1 elif argc == 3: return -2 def DUP_TOPX(self, argc): return argc findDepth = StackDepthTracker().findDepth
{ "repo_name": "pombredanne/pyjs", "path": "pyjs/lib_trans/pycompiler/pyassem.py", "copies": "6", "size": "26783", "license": "apache-2.0", "hash": -4466380800798878000, "line_mean": 30.9988052569, "line_max": 76, "alpha_frac": 0.5283575402, "autogenerated": false, "ratio": 3.919654617298405, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002175143496556293, "num_lines": 837 }
"""A flow graph representation for Python bytecode""" from __future__ import absolute_import, print_function from pony.py23compat import imap, items_list import dis import types import sys from . import misc from .consts import CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS class FlowGraph: def __init__(self): self.current = self.entry = Block() self.exit = Block("exit") self.blocks = misc.Set() self.blocks.add(self.entry) self.blocks.add(self.exit) def startBlock(self, block): if self._debug: if self.current: print("end", repr(self.current)) print(" next", self.current.next) print(" prev", self.current.prev) print(" ", self.current.get_children()) print(repr(block)) self.current = block def nextBlock(self, block=None): # XXX think we need to specify when there is implicit transfer # from one block to the next. might be better to represent this # with explicit JUMP_ABSOLUTE instructions that are optimized # out when they are unnecessary. # # I think this strategy works: each block has a child # designated as "next" which is returned as the last of the # children. because the nodes in a graph are emitted in # reverse post order, the "next" block will always be emitted # immediately after its parent. # Worry: maintaining this invariant could be tricky if block is None: block = self.newBlock() # Note: If the current block ends with an unconditional control # transfer, then it is techically incorrect to add an implicit # transfer to the block graph. Doing so results in code generation # for unreachable blocks. That doesn't appear to be very common # with Python code and since the built-in compiler doesn't optimize # it out we don't either. self.current.addNext(block) self.startBlock(block) def newBlock(self): b = Block() self.blocks.add(b) return b def startExitBlock(self): self.startBlock(self.exit) _debug = 0 def _enable_debug(self): self._debug = 1 def _disable_debug(self): self._debug = 0 def emit(self, *inst): if self._debug: print("\t", inst) if len(inst) == 2 and isinstance(inst[1], Block): self.current.addOutEdge(inst[1]) self.current.emit(inst) def getBlocksInOrder(self): """Return the blocks in reverse postorder i.e. each node appears before all of its successors """ order = order_blocks(self.entry, self.exit) return order def getBlocks(self): return self.blocks.elements() def getRoot(self): """Return nodes appropriate for use with dominator""" return self.entry def getContainedGraphs(self): l = [] for b in self.getBlocks(): l.extend(b.getContainedGraphs()) return l def order_blocks(start_block, exit_block): """Order blocks so that they are emitted in the right order""" # Rules: # - when a block has a next block, the next block must be emitted just after # - when a block has followers (relative jumps), it must be emitted before # them # - all reachable blocks must be emitted order = [] # Find all the blocks to be emitted. remaining = set() todo = [start_block] while todo: b = todo.pop() if b in remaining: continue remaining.add(b) for c in b.get_children(): if c not in remaining: todo.append(c) # A block is dominated by another block if that block must be emitted # before it. dominators = {} for b in remaining: if __debug__ and b.next: assert b is b.next[0].prev[0], (b, b.next) # Make sure every block appears in dominators, even if no # other block must precede it. dominators.setdefault(b, set()) # preceding blocks dominate following blocks for c in b.get_followers(): while 1: dominators.setdefault(c, set()).add(b) # Any block that has a next pointer leading to c is also # dominated because the whole chain will be emitted at once. # Walk backwards and add them all. if c.prev and c.prev[0] is not b: c = c.prev[0] else: break def find_next(): # Find a block that can be emitted next. for b in remaining: for c in dominators[b]: if c in remaining: break # can't emit yet, dominated by a remaining block else: return b assert 0, 'circular dependency, cannot find next block' b = start_block while 1: order.append(b) remaining.discard(b) if b.next: b = b.next[0] continue elif b is not exit_block and not b.has_unconditional_transfer(): order.append(exit_block) if not remaining: break b = find_next() return order class Block: _count = 0 def __init__(self, label=''): self.insts = [] self.outEdges = set() self.label = label self.bid = Block._count self.next = [] self.prev = [] Block._count = Block._count + 1 def __repr__(self): if self.label: return "<block %s id=%d>" % (self.label, self.bid) else: return "<block id=%d>" % (self.bid) def __str__(self): insts = imap(str, self.insts) return "<block %s %d:\n%s>" % (self.label, self.bid, '\n'.join(insts)) def emit(self, inst): op = inst[0] self.insts.append(inst) def getInstructions(self): return self.insts def addOutEdge(self, block): self.outEdges.add(block) def addNext(self, block): self.next.append(block) assert len(self.next) == 1, list(imap(str, self.next)) block.prev.append(self) assert len(block.prev) == 1, list(imap(str, block.prev)) _uncond_transfer = ('RETURN_VALUE', 'RAISE_VARARGS', 'JUMP_ABSOLUTE', 'JUMP_FORWARD', 'CONTINUE_LOOP', ) def has_unconditional_transfer(self): """Returns True if there is an unconditional transfer to an other block at the end of this block. This means there is no risk for the bytecode executer to go past this block's bytecode.""" try: op, arg = self.insts[-1] except (IndexError, ValueError): return return op in self._uncond_transfer def get_children(self): return list(self.outEdges) + self.next def get_followers(self): """Get the whole list of followers, including the next block.""" followers = set(self.next) # Blocks that must be emitted *after* this one, because of # bytecode offsets (e.g. relative jumps) pointing to them. for inst in self.insts: if inst[0] in PyFlowGraph.hasjrel: followers.add(inst[1]) return followers def getContainedGraphs(self): """Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body. """ contained = [] for inst in self.insts: if len(inst) == 1: continue op = inst[1] if hasattr(op, 'graph'): contained.append(op.graph) return contained # flags for code objects # the FlowGraph is transformed in place; it exists in one of these states RAW = "RAW" FLAT = "FLAT" CONV = "CONV" DONE = "DONE" class PyFlowGraph(FlowGraph): super_init = FlowGraph.__init__ def __init__(self, name, filename, args=(), optimized=0, klass=None): self.super_init() self.name = name self.filename = filename self.docstring = None self.args = args # XXX self.argcount = getArgCount(args) self.klass = klass if optimized: self.flags = CO_OPTIMIZED | CO_NEWLOCALS else: self.flags = 0 self.consts = [] self.names = [] # Free variables found by the symbol table scan, including # variables used only in nested scopes, are included here. self.freevars = [] self.cellvars = [] # The closure list is used to track the order of cell # variables and free variables in the resulting code object. # The offsets used by LOAD_CLOSURE/LOAD_DEREF refer to both # kinds of variables. self.closure = [] self.varnames = list(args) or [] for i in range(len(self.varnames)): var = self.varnames[i] if isinstance(var, TupleArg): self.varnames[i] = var.getName() self.stage = RAW def setDocstring(self, doc): self.docstring = doc def setFlag(self, flag): self.flags = self.flags | flag if flag == CO_VARARGS: self.argcount = self.argcount - 1 def checkFlag(self, flag): if self.flags & flag: return 1 def setFreeVars(self, names): self.freevars = list(names) def setCellVars(self, names): self.cellvars = names def getCode(self): """Get a Python code object""" assert self.stage == RAW self.computeStackDepth() self.flattenGraph() assert self.stage == FLAT self.convertArgs() assert self.stage == CONV self.makeByteCode() assert self.stage == DONE return self.newCodeObject() def dump(self, io=None): if io: save = sys.stdout sys.stdout = io pc = 0 for t in self.insts: opname = t[0] if opname == "SET_LINENO": print() if len(t) == 1: print("\t", "%3d" % pc, opname) pc = pc + 1 else: print("\t", "%3d" % pc, opname, t[1]) pc = pc + 3 if io: sys.stdout = save def computeStackDepth(self): """Compute the max stack depth. Approach is to compute the stack effect of each basic block. Then find the path through the code with the largest total effect. """ depth = {} exit = None for b in self.getBlocks(): depth[b] = findDepth(b.getInstructions()) seen = {} def max_depth(b, d): if b in seen: return d seen[b] = 1 d = d + depth[b] children = b.get_children() if children: return max([max_depth(c, d) for c in children]) else: if not b.label == "exit": return max_depth(self.exit, d) else: return d self.stacksize = max_depth(self.entry, 0) def flattenGraph(self): """Arrange the blocks in order and resolve jumps""" assert self.stage == RAW self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": # arg takes 2 bytes pc = pc + 3 end[b] = pc pc = 0 for i in range(len(insts)): inst = insts[i] if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": pc = pc + 3 opname = inst[0] if opname in self.hasjrel: oparg = inst[1] offset = begin[oparg] - pc insts[i] = opname, offset elif opname in self.hasjabs: insts[i] = opname, begin[inst[1]] self.stage = FLAT hasjrel = set() for i in dis.hasjrel: hasjrel.add(dis.opname[i]) hasjabs = set() for i in dis.hasjabs: hasjabs.add(dis.opname[i]) def convertArgs(self): """Convert arguments from symbolic to concrete form""" assert self.stage == FLAT self.consts.insert(0, self.docstring) self.sort_cellvars() for i in range(len(self.insts)): t = self.insts[i] if len(t) == 2: opname, oparg = t conv = self._converters.get(opname, None) if conv: self.insts[i] = opname, conv(self, oparg) self.stage = CONV def sort_cellvars(self): """Sort cellvars in the order of varnames and prune from freevars. """ cells = {} for name in self.cellvars: cells[name] = 1 self.cellvars = [name for name in self.varnames if name in cells] for name in self.cellvars: del cells[name] self.cellvars = self.cellvars + cells.keys() self.closure = self.cellvars + self.freevars def _lookupName(self, name, list): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before comparing the values. """ t = type(name) for i in range(len(list)): if t == type(list[i]) and list[i] == name: return i end = len(list) list.append(name) return end _converters = {} def _convert_LOAD_CONST(self, arg): if hasattr(arg, 'getCode'): arg = arg.getCode() return self._lookupName(arg, self.consts) def _convert_LOAD_FAST(self, arg): self._lookupName(arg, self.names) return self._lookupName(arg, self.varnames) _convert_STORE_FAST = _convert_LOAD_FAST _convert_DELETE_FAST = _convert_LOAD_FAST def _convert_LOAD_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) def _convert_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) _convert_STORE_NAME = _convert_NAME _convert_DELETE_NAME = _convert_NAME _convert_IMPORT_NAME = _convert_NAME _convert_IMPORT_FROM = _convert_NAME _convert_STORE_ATTR = _convert_NAME _convert_LOAD_ATTR = _convert_NAME _convert_DELETE_ATTR = _convert_NAME _convert_LOAD_GLOBAL = _convert_NAME _convert_STORE_GLOBAL = _convert_NAME _convert_DELETE_GLOBAL = _convert_NAME def _convert_DEREF(self, arg): self._lookupName(arg, self.names) self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _convert_LOAD_DEREF = _convert_DEREF _convert_STORE_DEREF = _convert_DEREF def _convert_LOAD_CLOSURE(self, arg): self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _cmp = list(dis.cmp_op) def _convert_COMPARE_OP(self, arg): return self._cmp.index(arg) # similarly for other opcodes... for name, obj in items_list(locals()): if name[:9] == "_convert_": opname = name[9:] _converters[opname] = obj del name, obj, opname def makeByteCode(self): assert self.stage == CONV self.lnotab = lnotab = LineAddrTable() for t in self.insts: opname = t[0] if len(t) == 1: lnotab.addCode(self.opnum[opname]) else: oparg = t[1] if opname == "SET_LINENO": lnotab.nextLine(oparg) continue hi, lo = twobyte(oparg) try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: print(opname, oparg) print(self.opnum[opname], lo, hi) raise self.stage = DONE opnum = {} for num in range(len(dis.opname)): opnum[dis.opname[num]] = num del num def newCodeObject(self): assert self.stage == DONE if (self.flags & CO_NEWLOCALS) == 0: nlocals = 0 else: nlocals = len(self.varnames) argcount = self.argcount if self.flags & CO_VARKEYWORDS: argcount = argcount - 1 return types.CodeType(argcount, nlocals, self.stacksize, self.flags, self.lnotab.getCode(), self.getConsts(), tuple(self.names), tuple(self.varnames), self.filename, self.name, self.lnotab.firstline, self.lnotab.getTable(), tuple(self.freevars), tuple(self.cellvars)) def getConsts(self): """Return a tuple for the const slot of the code object Must convert references to code (MAKE_FUNCTION) to code objects recursively. """ l = [] for elt in self.consts: if isinstance(elt, PyFlowGraph): elt = elt.getCode() l.append(elt) return tuple(l) def isJump(opname): if opname[:4] == 'JUMP': return 1 class TupleArg: """Helper for marking func defs with nested tuples in arglist""" def __init__(self, count, names): self.count = count self.names = names def __repr__(self): return "TupleArg(%s, %s)" % (self.count, self.names) def getName(self): return ".%d" % self.count def getArgCount(args): argcount = len(args) if args: for arg in args: if isinstance(arg, TupleArg): numNames = len(misc.flatten(arg.names)) argcount = argcount - numNames return argcount def twobyte(val): """Convert an int argument into high and low bytes""" assert isinstance(val, int) return divmod(val, 256) class LineAddrTable: """lnotab This class builds the lnotab, which is documented in compile.c. Here's a brief recap: For each SET_LINENO instruction after the first one, two bytes are added to lnotab. (In some cases, multiple two-byte entries are added.) The first byte is the distance in bytes between the instruction for the last SET_LINENO and the current SET_LINENO. The second byte is offset in line numbers. If either offset is greater than 255, multiple two-byte entries are added -- see compile.c for the delicate details. """ def __init__(self): self.code = [] self.codeOffset = 0 self.firstline = 0 self.lastline = 0 self.lastoff = 0 self.lnotab = [] def addCode(self, *args): for arg in args: self.code.append(chr(arg)) self.codeOffset = self.codeOffset + len(args) def nextLine(self, lineno): if self.firstline == 0: self.firstline = lineno self.lastline = lineno else: # compute deltas addr = self.codeOffset - self.lastoff line = lineno - self.lastline # Python assumes that lineno always increases with # increasing bytecode address (lnotab is unsigned char). # Depending on when SET_LINENO instructions are emitted # this is not always true. Consider the code: # a = (1, # b) # In the bytecode stream, the assignment to "a" occurs # after the loading of "b". This works with the C Python # compiler because it only generates a SET_LINENO instruction # for the assignment. if line >= 0: push = self.lnotab.append while addr > 255: push(255); push(0) addr -= 255 while line > 255: push(addr); push(255) line -= 255 addr = 0 if addr > 0 or line > 0: push(addr); push(line) self.lastline = lineno self.lastoff = self.codeOffset def getCode(self): return ''.join(self.code) def getTable(self): return ''.join(imap(chr, self.lnotab)) class StackDepthTracker: # XXX 1. need to keep track of stack depth on jumps # XXX 2. at least partly as a result, this code is broken def findDepth(self, insts, debug=0): depth = 0 maxDepth = 0 for i in insts: opname = i[0] if debug: print(i, end=' ') delta = self.effect.get(opname, None) if delta is not None: depth = depth + delta else: # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta is None: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth > maxDepth: maxDepth = depth if debug: print(depth, maxDepth) return maxDepth effect = { 'POP_TOP': -1, 'DUP_TOP': 1, 'LIST_APPEND': -1, 'SET_ADD': -1, 'MAP_ADD': -2, 'SLICE+1': -1, 'SLICE+2': -1, 'SLICE+3': -2, 'STORE_SLICE+0': -1, 'STORE_SLICE+1': -2, 'STORE_SLICE+2': -2, 'STORE_SLICE+3': -3, 'DELETE_SLICE+0': -1, 'DELETE_SLICE+1': -2, 'DELETE_SLICE+2': -2, 'DELETE_SLICE+3': -3, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, # PRINT_EXPR? 'PRINT_ITEM': -1, 'RETURN_VALUE': -1, 'YIELD_VALUE': -1, 'EXEC_STMT': -3, 'BUILD_CLASS': -2, 'STORE_NAME': -1, 'STORE_ATTR': -2, 'DELETE_ATTR': -1, 'STORE_GLOBAL': -1, 'BUILD_MAP': 1, 'COMPARE_OP': -1, 'STORE_FAST': -1, 'IMPORT_STAR': -1, 'IMPORT_NAME': -1, 'IMPORT_FROM': 1, 'LOAD_ATTR': 0, # unlike other loads # close enough... 'SETUP_EXCEPT': 3, 'SETUP_FINALLY': 3, 'FOR_ITER': 1, 'WITH_CLEANUP': -1, } # use pattern match patterns = [ ('BINARY_', -1), ('LOAD_', 1), ] def UNPACK_SEQUENCE(self, count): return count-1 def BUILD_TUPLE(self, count): return -count+1 def BUILD_LIST(self, count): return -count+1 def BUILD_SET(self, count): return -count+1 def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return -(lo + hi * 2) def CALL_FUNCTION_VAR(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_KW(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_VAR_KW(self, argc): return self.CALL_FUNCTION(argc)-2 def MAKE_FUNCTION(self, argc): return -argc def MAKE_CLOSURE(self, argc): # XXX need to account for free variables too! return -argc def BUILD_SLICE(self, argc): if argc == 2: return -1 elif argc == 3: return -2 def DUP_TOPX(self, argc): return argc findDepth = StackDepthTracker().findDepth
{ "repo_name": "compiteing/flask-ponypermission", "path": "venv/lib/python2.7/site-packages/pony/thirdparty/compiler/pyassem.py", "copies": "2", "size": "25106", "license": "mit", "hash": -5587362155962567000, "line_mean": 30.8612565445, "line_max": 80, "alpha_frac": 0.5232215407, "autogenerated": false, "ratio": 4.035685581096287, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0016785817693308936, "num_lines": 764 }
"""A flow graph representation for Python bytecode""" import dis import new import sys from compiler import misc from compiler.consts \ import CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS class FlowGraph: def __init__(self): self.current = self.entry = Block() self.exit = Block("exit") self.blocks = misc.Set() self.blocks.add(self.entry) self.blocks.add(self.exit) def startBlock(self, block): if self._debug: if self.current: print "end", repr(self.current) print " next", self.current.next print " ", self.current.get_children() print repr(block) self.current = block def nextBlock(self, block=None): # XXX think we need to specify when there is implicit transfer # from one block to the next. might be better to represent this # with explicit JUMP_ABSOLUTE instructions that are optimized # out when they are unnecessary. # # I think this strategy works: each block has a child # designated as "next" which is returned as the last of the # children. because the nodes in a graph are emitted in # reverse post order, the "next" block will always be emitted # immediately after its parent. # Worry: maintaining this invariant could be tricky if block is None: block = self.newBlock() # Note: If the current block ends with an unconditional # control transfer, then it is incorrect to add an implicit # transfer to the block graph. The current code requires # these edges to get the blocks emitted in the right order, # however. :-( If a client needs to remove these edges, call # pruneEdges(). self.current.addNext(block) self.startBlock(block) def newBlock(self): b = Block() self.blocks.add(b) return b def startExitBlock(self): self.startBlock(self.exit) _debug = 0 def _enable_debug(self): self._debug = 1 def _disable_debug(self): self._debug = 0 def emit(self, *inst): if self._debug: print "\t", inst if inst[0] in ['RETURN_VALUE', 'YIELD_VALUE']: self.current.addOutEdge(self.exit) if len(inst) == 2 and isinstance(inst[1], Block): self.current.addOutEdge(inst[1]) self.current.emit(inst) def getBlocksInOrder(self): """Return the blocks in reverse postorder i.e. each node appears before all of its successors """ # XXX make sure every node that doesn't have an explicit next # is set so that next points to exit for b in self.blocks.elements(): if b is self.exit: continue if not b.next: b.addNext(self.exit) order = dfs_postorder(self.entry, {}) order.reverse() self.fixupOrder(order, self.exit) # hack alert if not self.exit in order: order.append(self.exit) return order def fixupOrder(self, blocks, default_next): """Fixup bad order introduced by DFS.""" # XXX This is a total mess. There must be a better way to get # the code blocks in the right order. self.fixupOrderHonorNext(blocks, default_next) self.fixupOrderForward(blocks, default_next) def fixupOrderHonorNext(self, blocks, default_next): """Fix one problem with DFS. The DFS uses child block, but doesn't know about the special "next" block. As a result, the DFS can order blocks so that a block isn't next to the right block for implicit control transfers. """ index = {} for i in range(len(blocks)): index[blocks[i]] = i for i in range(0, len(blocks) - 1): b = blocks[i] n = blocks[i + 1] if not b.next or b.next[0] == default_next or b.next[0] == n: continue # The blocks are in the wrong order. Find the chain of # blocks to insert where they belong. cur = b chain = [] elt = cur while elt.next and elt.next[0] != default_next: chain.append(elt.next[0]) elt = elt.next[0] # Now remove the blocks in the chain from the current # block list, so that they can be re-inserted. l = [] for b in chain: assert index[b] > i l.append((index[b], b)) l.sort() l.reverse() for j, b in l: del blocks[index[b]] # Insert the chain in the proper location blocks[i:i + 1] = [cur] + chain # Finally, re-compute the block indexes for i in range(len(blocks)): index[blocks[i]] = i def fixupOrderForward(self, blocks, default_next): """Make sure all JUMP_FORWARDs jump forward""" index = {} chains = [] cur = [] for b in blocks: index[b] = len(chains) cur.append(b) if b.next and b.next[0] == default_next: chains.append(cur) cur = [] chains.append(cur) while 1: constraints = [] for i in range(len(chains)): l = chains[i] for b in l: for c in b.get_children(): if index[c] < i: forward_p = 0 for inst in b.insts: if inst[0] == 'JUMP_FORWARD': if inst[1] == c: forward_p = 1 if not forward_p: continue constraints.append((index[c], i)) if not constraints: break # XXX just do one for now # do swaps to get things in the right order goes_before, a_chain = constraints[0] assert a_chain > goes_before c = chains[a_chain] chains.remove(c) chains.insert(goes_before, c) del blocks[:] for c in chains: for b in c: blocks.append(b) def getBlocks(self): return self.blocks.elements() def getRoot(self): """Return nodes appropriate for use with dominator""" return self.entry def getContainedGraphs(self): l = [] for b in self.getBlocks(): l.extend(b.getContainedGraphs()) return l def dfs_postorder(b, seen): """Depth-first search of tree rooted at b, return in postorder""" order = [] seen[b] = b for c in b.get_children(): if seen.has_key(c): continue order = order + dfs_postorder(c, seen) order.append(b) return order class Block: _count = 0 def __init__(self, label=''): self.insts = [] self.inEdges = misc.Set() self.outEdges = misc.Set() self.label = label self.bid = Block._count self.next = [] Block._count = Block._count + 1 def __repr__(self): if self.label: return "<block %s id=%d>" % (self.label, self.bid) else: return "<block id=%d>" % (self.bid) def __str__(self): insts = map(str, self.insts) return "<block %s %d:\n%s>" % (self.label, self.bid, '\n'.join(insts)) def emit(self, inst): op = inst[0] if op[:4] == 'JUMP': self.outEdges.add(inst[1]) self.insts.append(inst) def getInstructions(self): return self.insts def addInEdge(self, block): self.inEdges.add(block) def addOutEdge(self, block): self.outEdges.add(block) def addNext(self, block): self.next.append(block) assert len(self.next) == 1, map(str, self.next) _uncond_transfer = ('RETURN_VALUE', 'RAISE_VARARGS', 'YIELD_VALUE', 'JUMP_ABSOLUTE', 'JUMP_FORWARD', 'CONTINUE_LOOP') def pruneNext(self): """Remove bogus edge for unconditional transfers Each block has a next edge that accounts for implicit control transfers, e.g. from a JUMP_IF_FALSE to the block that will be executed if the test is true. These edges must remain for the current assembler code to work. If they are removed, the dfs_postorder gets things in weird orders. However, they shouldn't be there for other purposes, e.g. conversion to SSA form. This method will remove the next edge when it follows an unconditional control transfer. """ try: op, arg = self.insts[-1] except (IndexError, ValueError): return if op in self._uncond_transfer: self.next = [] def get_children(self): if self.next and self.next[0] in self.outEdges: self.outEdges.remove(self.next[0]) return self.outEdges.elements() + self.next def getContainedGraphs(self): """Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body. """ contained = [] for inst in self.insts: if len(inst) == 1: continue op = inst[1] if hasattr(op, 'graph'): contained.append(op.graph) return contained # flags for code objects # the FlowGraph is transformed in place; it exists in one of these states RAW = "RAW" FLAT = "FLAT" CONV = "CONV" DONE = "DONE" class PyFlowGraph(FlowGraph): super_init = FlowGraph.__init__ def __init__(self, name, filename, args=(), optimized=0, klass=None): self.super_init() self.name = name self.filename = filename self.docstring = None self.args = args # XXX self.argcount = getArgCount(args) self.klass = klass if optimized: self.flags = CO_OPTIMIZED | CO_NEWLOCALS else: self.flags = 0 self.consts = [] self.names = [] # Free variables found by the symbol table scan, including # variables used only in nested scopes, are included here. self.freevars = [] self.cellvars = [] # The closure list is used to track the order of cell # variables and free variables in the resulting code object. # The offsets used by LOAD_CLOSURE/LOAD_DEREF refer to both # kinds of variables. self.closure = [] self.varnames = list(args) or [] for i in range(len(self.varnames)): var = self.varnames[i] if isinstance(var, TupleArg): self.varnames[i] = var.getName() self.stage = RAW def setDocstring(self, doc): self.docstring = doc def setFlag(self, flag): self.flags = self.flags | flag if flag == CO_VARARGS: self.argcount = self.argcount - 1 def checkFlag(self, flag): if self.flags & flag: return 1 def setFreeVars(self, names): self.freevars = list(names) def setCellVars(self, names): self.cellvars = names def getCode(self): """Get a Python code object""" assert self.stage == RAW self.computeStackDepth() self.flattenGraph() assert self.stage == FLAT self.convertArgs() assert self.stage == CONV self.makeByteCode() assert self.stage == DONE return self.newCodeObject() def dump(self, io=None): if io: save = sys.stdout sys.stdout = io pc = 0 for t in self.insts: opname = t[0] if opname == "SET_LINENO": print if len(t) == 1: print "\t", "%3d" % pc, opname pc = pc + 1 else: print "\t", "%3d" % pc, opname, t[1] pc = pc + 3 if io: sys.stdout = save def computeStackDepth(self): """Compute the max stack depth. Approach is to compute the stack effect of each basic block. Then find the path through the code with the largest total effect. """ depth = {} exit = None for b in self.getBlocks(): depth[b] = findDepth(b.getInstructions()) seen = {} def max_depth(b, d): if seen.has_key(b): return d seen[b] = 1 d = d + depth[b] children = b.get_children() if children: return max([max_depth(c, d) for c in children]) else: if not b.label == "exit": return max_depth(self.exit, d) else: return d self.stacksize = max_depth(self.entry, 0) def flattenGraph(self): """Arrange the blocks in order and resolve jumps""" assert self.stage == RAW self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": # arg takes 2 bytes pc = pc + 3 end[b] = pc pc = 0 for i in range(len(insts)): inst = insts[i] if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": pc = pc + 3 opname = inst[0] if self.hasjrel.has_elt(opname): oparg = inst[1] offset = begin[oparg] - pc insts[i] = opname, offset elif self.hasjabs.has_elt(opname): insts[i] = opname, begin[inst[1]] self.stage = FLAT hasjrel = misc.Set() for i in dis.hasjrel: hasjrel.add(dis.opname[i]) hasjabs = misc.Set() for i in dis.hasjabs: hasjabs.add(dis.opname[i]) def convertArgs(self): """Convert arguments from symbolic to concrete form""" assert self.stage == FLAT self.consts.insert(0, self.docstring) self.sort_cellvars() for i in range(len(self.insts)): t = self.insts[i] if len(t) == 2: opname, oparg = t conv = self._converters.get(opname, None) if conv: self.insts[i] = opname, conv(self, oparg) self.stage = CONV def sort_cellvars(self): """Sort cellvars in the order of varnames and prune from freevars. """ cells = {} for name in self.cellvars: cells[name] = 1 self.cellvars = [name for name in self.varnames if cells.has_key(name)] for name in self.cellvars: del cells[name] self.cellvars = self.cellvars + cells.keys() self.closure = self.cellvars + self.freevars def _lookupName(self, name, list): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before comparing the values. """ t = type(name) for i in range(len(list)): if t == type(list[i]) and list[i] == name: return i end = len(list) list.append(name) return end _converters = {} def _convert_LOAD_CONST(self, arg): if hasattr(arg, 'getCode'): arg = arg.getCode() return self._lookupName(arg, self.consts) def _convert_LOAD_FAST(self, arg): self._lookupName(arg, self.names) return self._lookupName(arg, self.varnames) _convert_STORE_FAST = _convert_LOAD_FAST _convert_DELETE_FAST = _convert_LOAD_FAST def _convert_LOAD_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) def _convert_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) _convert_STORE_NAME = _convert_NAME _convert_DELETE_NAME = _convert_NAME _convert_IMPORT_NAME = _convert_NAME _convert_IMPORT_FROM = _convert_NAME _convert_STORE_ATTR = _convert_NAME _convert_LOAD_ATTR = _convert_NAME _convert_DELETE_ATTR = _convert_NAME _convert_LOAD_GLOBAL = _convert_NAME _convert_STORE_GLOBAL = _convert_NAME _convert_DELETE_GLOBAL = _convert_NAME def _convert_DEREF(self, arg): self._lookupName(arg, self.names) self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _convert_LOAD_DEREF = _convert_DEREF _convert_STORE_DEREF = _convert_DEREF def _convert_LOAD_CLOSURE(self, arg): self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _cmp = list(dis.cmp_op) def _convert_COMPARE_OP(self, arg): return self._cmp.index(arg) # similarly for other opcodes... for name, obj in locals().items(): if name[:9] == "_convert_": opname = name[9:] _converters[opname] = obj del name, obj, opname def makeByteCode(self): assert self.stage == CONV self.lnotab = lnotab = LineAddrTable() for t in self.insts: opname = t[0] if len(t) == 1: lnotab.addCode(self.opnum[opname]) else: oparg = t[1] if opname == "SET_LINENO": lnotab.nextLine(oparg) continue hi, lo = twobyte(oparg) try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: print opname, oparg print self.opnum[opname], lo, hi raise self.stage = DONE opnum = {} for num in range(len(dis.opname)): opnum[dis.opname[num]] = num del num def newCodeObject(self): assert self.stage == DONE if (self.flags & CO_NEWLOCALS) == 0: nlocals = 0 else: nlocals = len(self.varnames) argcount = self.argcount if self.flags & CO_VARKEYWORDS: argcount = argcount - 1 return new.code(argcount, nlocals, self.stacksize, self.flags, self.lnotab.getCode(), self.getConsts(), tuple(self.names), tuple(self.varnames), self.filename, self.name, self.lnotab.firstline, self.lnotab.getTable(), tuple(self.freevars), tuple(self.cellvars)) def getConsts(self): """Return a tuple for the const slot of the code object Must convert references to code (MAKE_FUNCTION) to code objects recursively. """ l = [] for elt in self.consts: if isinstance(elt, PyFlowGraph): elt = elt.getCode() l.append(elt) return tuple(l) def isJump(opname): if opname[:4] == 'JUMP': return 1 class TupleArg: """Helper for marking func defs with nested tuples in arglist""" def __init__(self, count, names): self.count = count self.names = names def __repr__(self): return "TupleArg(%s, %s)" % (self.count, self.names) def getName(self): return ".%d" % self.count def getArgCount(args): argcount = len(args) if args: for arg in args: if isinstance(arg, TupleArg): numNames = len(misc.flatten(arg.names)) argcount = argcount - numNames return argcount def twobyte(val): """Convert an int argument into high and low bytes""" assert isinstance(val, int) return divmod(val, 256) class LineAddrTable: """lnotab This class builds the lnotab, which is documented in compile.c. Here's a brief recap: For each SET_LINENO instruction after the first one, two bytes are added to lnotab. (In some cases, multiple two-byte entries are added.) The first byte is the distance in bytes between the instruction for the last SET_LINENO and the current SET_LINENO. The second byte is offset in line numbers. If either offset is greater than 255, multiple two-byte entries are added -- see compile.c for the delicate details. """ def __init__(self): self.code = [] self.codeOffset = 0 self.firstline = 0 self.lastline = 0 self.lastoff = 0 self.lnotab = [] def addCode(self, *args): for arg in args: self.code.append(chr(arg)) self.codeOffset = self.codeOffset + len(args) def nextLine(self, lineno): if self.firstline == 0: self.firstline = lineno self.lastline = lineno else: # compute deltas addr = self.codeOffset - self.lastoff line = lineno - self.lastline # Python assumes that lineno always increases with # increasing bytecode address (lnotab is unsigned char). # Depending on when SET_LINENO instructions are emitted # this is not always true. Consider the code: # a = (1, # b) # In the bytecode stream, the assignment to "a" occurs # after the loading of "b". This works with the C Python # compiler because it only generates a SET_LINENO instruction # for the assignment. if line >= 0: push = self.lnotab.append while addr > 255: push(255); push(0) addr -= 255 while line > 255: push(addr); push(255) line -= 255 addr = 0 if addr > 0 or line > 0: push(addr); push(line) self.lastline = lineno self.lastoff = self.codeOffset def getCode(self): return ''.join(self.code) def getTable(self): return ''.join(map(chr, self.lnotab)) class StackDepthTracker: # XXX 1. need to keep track of stack depth on jumps # XXX 2. at least partly as a result, this code is broken def findDepth(self, insts, debug=0): depth = 0 maxDepth = 0 for i in insts: opname = i[0] if debug: print i, delta = self.effect.get(opname, None) if delta is not None: depth = depth + delta else: # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta is None: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth > maxDepth: maxDepth = depth if debug: print depth, maxDepth return maxDepth effect = { 'POP_TOP': -1, 'DUP_TOP': 1, 'LIST_APPEND': -2, 'SLICE+1': -1, 'SLICE+2': -1, 'SLICE+3': -2, 'STORE_SLICE+0': -1, 'STORE_SLICE+1': -2, 'STORE_SLICE+2': -2, 'STORE_SLICE+3': -3, 'DELETE_SLICE+0': -1, 'DELETE_SLICE+1': -2, 'DELETE_SLICE+2': -2, 'DELETE_SLICE+3': -3, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, # PRINT_EXPR? 'PRINT_ITEM': -1, 'RETURN_VALUE': -1, 'YIELD_VALUE': -1, 'EXEC_STMT': -3, 'BUILD_CLASS': -2, 'STORE_NAME': -1, 'STORE_ATTR': -2, 'DELETE_ATTR': -1, 'STORE_GLOBAL': -1, 'BUILD_MAP': 1, 'COMPARE_OP': -1, 'STORE_FAST': -1, 'IMPORT_STAR': -1, 'IMPORT_NAME': -1, 'IMPORT_FROM': 1, 'LOAD_ATTR': 0, # unlike other loads # close enough... 'SETUP_EXCEPT': 3, 'SETUP_FINALLY': 3, 'FOR_ITER': 1, 'WITH_CLEANUP': -1, } # use pattern match patterns = [ ('BINARY_', -1), ('LOAD_', 1), ] def UNPACK_SEQUENCE(self, count): return count-1 def BUILD_TUPLE(self, count): return -count+1 def BUILD_LIST(self, count): return -count+1 def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return -(lo + hi * 2) def CALL_FUNCTION_VAR(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_KW(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_VAR_KW(self, argc): return self.CALL_FUNCTION(argc)-2 def MAKE_FUNCTION(self, argc): return -argc def MAKE_CLOSURE(self, argc): # XXX need to account for free variables too! return -argc def BUILD_SLICE(self, argc): if argc == 2: return -1 elif argc == 3: return -2 def DUP_TOPX(self, argc): return argc findDepth = StackDepthTracker().findDepth
{ "repo_name": "ericlink/adms-server", "path": "playframework-dist/1.1-src/python/Lib/compiler/pyassem.py", "copies": "2", "size": "26981", "license": "mit", "hash": 1035117605734464000, "line_mean": 30.9841075795, "line_max": 74, "alpha_frac": 0.512990623, "autogenerated": false, "ratio": 4.059735179055071, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5572725802055072, "avg_score": null, "num_lines": null }
"""A flow graph representation for Python bytecode""" import dis import types import sys from compiler import misc from compiler.consts \ import CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS class FlowGraph: def __init__(self): self.current = self.entry = Block() self.exit = Block("exit") self.blocks = misc.Set() self.blocks.add(self.entry) self.blocks.add(self.exit) def startBlock(self, block): if self._debug: if self.current: print "end", repr(self.current) print " next", self.current.next print " prev", self.current.prev print " ", self.current.get_children() print repr(block) self.current = block def nextBlock(self, block=None): # XXX think we need to specify when there is implicit transfer # from one block to the next. might be better to represent this # with explicit JUMP_ABSOLUTE instructions that are optimized # out when they are unnecessary. # # I think this strategy works: each block has a child # designated as "next" which is returned as the last of the # children. because the nodes in a graph are emitted in # reverse post order, the "next" block will always be emitted # immediately after its parent. # Worry: maintaining this invariant could be tricky if block is None: block = self.newBlock() # Note: If the current block ends with an unconditional control # transfer, then it is techically incorrect to add an implicit # transfer to the block graph. Doing so results in code generation # for unreachable blocks. That doesn't appear to be very common # with Python code and since the built-in compiler doesn't optimize # it out we don't either. self.current.addNext(block) self.startBlock(block) def newBlock(self): b = Block() self.blocks.add(b) return b def startExitBlock(self): self.startBlock(self.exit) _debug = 0 def _enable_debug(self): self._debug = 1 def _disable_debug(self): self._debug = 0 def emit(self, *inst): if self._debug: print "\t", inst if len(inst) == 2 and isinstance(inst[1], Block): self.current.addOutEdge(inst[1]) self.current.emit(inst) def getBlocksInOrder(self): """Return the blocks in reverse postorder i.e. each node appears before all of its successors """ order = order_blocks(self.entry, self.exit) return order def getBlocks(self): return self.blocks.elements() def getRoot(self): """Return nodes appropriate for use with dominator""" return self.entry def getContainedGraphs(self): l = [] for b in self.getBlocks(): l.extend(b.getContainedGraphs()) return l def order_blocks(start_block, exit_block): """Order blocks so that they are emitted in the right order""" # Rules: # - when a block has a next block, the next block must be emitted just after # - when a block has followers (relative jumps), it must be emitted before # them # - all reachable blocks must be emitted order = [] # Find all the blocks to be emitted. remaining = set() todo = [start_block] while todo: b = todo.pop() if b in remaining: continue remaining.add(b) for c in b.get_children(): if c not in remaining: todo.append(c) # A block is dominated by another block if that block must be emitted # before it. dominators = {} for b in remaining: if __debug__ and b.next: assert b is b.next[0].prev[0], (b, b.next) # Make sure every block appears in dominators, even if no # other block must precede it. dominators.setdefault(b, set()) # preceding blocks dominate following blocks for c in b.get_followers(): while 1: dominators.setdefault(c, set()).add(b) # Any block that has a next pointer leading to c is also # dominated because the whole chain will be emitted at once. # Walk backwards and add them all. if c.prev and c.prev[0] is not b: c = c.prev[0] else: break def find_next(): # Find a block that can be emitted next. for b in remaining: for c in dominators[b]: if c in remaining: break # can't emit yet, dominated by a remaining block else: return b assert 0, 'circular dependency, cannot find next block' b = start_block while 1: order.append(b) remaining.discard(b) if b.next: b = b.next[0] continue elif b is not exit_block and not b.has_unconditional_transfer(): order.append(exit_block) if not remaining: break b = find_next() return order class Block: _count = 0 def __init__(self, label=''): self.insts = [] self.outEdges = set() self.label = label self.bid = Block._count self.next = [] self.prev = [] Block._count = Block._count + 1 def __repr__(self): if self.label: return "<block %s id=%d>" % (self.label, self.bid) else: return "<block id=%d>" % (self.bid) def __str__(self): insts = map(str, self.insts) return "<block %s %d:\n%s>" % (self.label, self.bid, '\n'.join(insts)) def emit(self, inst): op = inst[0] self.insts.append(inst) def getInstructions(self): return self.insts def addOutEdge(self, block): self.outEdges.add(block) def addNext(self, block): self.next.append(block) assert len(self.next) == 1, map(str, self.next) block.prev.append(self) assert len(block.prev) == 1, map(str, block.prev) _uncond_transfer = ('RETURN_VALUE', 'RAISE_VARARGS', 'JUMP_ABSOLUTE', 'JUMP_FORWARD', 'CONTINUE_LOOP', ) def has_unconditional_transfer(self): """Returns True if there is an unconditional transfer to an other block at the end of this block. This means there is no risk for the bytecode executer to go past this block's bytecode.""" try: op, arg = self.insts[-1] except (IndexError, ValueError): return return op in self._uncond_transfer def get_children(self): return list(self.outEdges) + self.next def get_followers(self): """Get the whole list of followers, including the next block.""" followers = set(self.next) # Blocks that must be emitted *after* this one, because of # bytecode offsets (e.g. relative jumps) pointing to them. for inst in self.insts: if inst[0] in PyFlowGraph.hasjrel: followers.add(inst[1]) return followers def getContainedGraphs(self): """Return all graphs contained within this block. For example, a MAKE_FUNCTION block will contain a reference to the graph for the function body. """ contained = [] for inst in self.insts: if len(inst) == 1: continue op = inst[1] if hasattr(op, 'graph'): contained.append(op.graph) return contained # flags for code objects # the FlowGraph is transformed in place; it exists in one of these states RAW = "RAW" FLAT = "FLAT" CONV = "CONV" DONE = "DONE" class PyFlowGraph(FlowGraph): super_init = FlowGraph.__init__ def __init__(self, name, filename, args=(), optimized=0, klass=None): self.super_init() self.name = name self.filename = filename self.docstring = None self.args = args # XXX self.argcount = getArgCount(args) self.klass = klass if optimized: self.flags = CO_OPTIMIZED | CO_NEWLOCALS else: self.flags = 0 self.consts = [] self.names = [] # Free variables found by the symbol table scan, including # variables used only in nested scopes, are included here. self.freevars = [] self.cellvars = [] # The closure list is used to track the order of cell # variables and free variables in the resulting code object. # The offsets used by LOAD_CLOSURE/LOAD_DEREF refer to both # kinds of variables. self.closure = [] self.varnames = list(args) or [] for i in range(len(self.varnames)): var = self.varnames[i] if isinstance(var, TupleArg): self.varnames[i] = var.getName() self.stage = RAW def setDocstring(self, doc): self.docstring = doc def setFlag(self, flag): self.flags = self.flags | flag if flag == CO_VARARGS: self.argcount = self.argcount - 1 def checkFlag(self, flag): if self.flags & flag: return 1 def setFreeVars(self, names): self.freevars = list(names) def setCellVars(self, names): self.cellvars = names def getCode(self): """Get a Python code object""" assert self.stage == RAW self.computeStackDepth() self.flattenGraph() assert self.stage == FLAT self.convertArgs() assert self.stage == CONV self.makeByteCode() assert self.stage == DONE return self.newCodeObject() def dump(self, io=None): if io: save = sys.stdout sys.stdout = io pc = 0 for t in self.insts: opname = t[0] if opname == "SET_LINENO": print if len(t) == 1: print "\t", "%3d" % pc, opname pc = pc + 1 else: print "\t", "%3d" % pc, opname, t[1] pc = pc + 3 if io: sys.stdout = save def computeStackDepth(self): """Compute the max stack depth. Approach is to compute the stack effect of each basic block. Then find the path through the code with the largest total effect. """ depth = {} exit = None for b in self.getBlocks(): depth[b] = findDepth(b.getInstructions()) seen = {} def max_depth(b, d): if b in seen: return d seen[b] = 1 d = d + depth[b] children = b.get_children() if children: return max([max_depth(c, d) for c in children]) else: if not b.label == "exit": return max_depth(self.exit, d) else: return d self.stacksize = max_depth(self.entry, 0) def flattenGraph(self): """Arrange the blocks in order and resolve jumps""" assert self.stage == RAW self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": # arg takes 2 bytes pc = pc + 3 end[b] = pc pc = 0 for i in range(len(insts)): inst = insts[i] if len(inst) == 1: pc = pc + 1 elif inst[0] != "SET_LINENO": pc = pc + 3 opname = inst[0] if opname in self.hasjrel: oparg = inst[1] offset = begin[oparg] - pc insts[i] = opname, offset elif opname in self.hasjabs: insts[i] = opname, begin[inst[1]] self.stage = FLAT hasjrel = set() for i in dis.hasjrel: hasjrel.add(dis.opname[i]) hasjabs = set() for i in dis.hasjabs: hasjabs.add(dis.opname[i]) def convertArgs(self): """Convert arguments from symbolic to concrete form""" assert self.stage == FLAT self.consts.insert(0, self.docstring) self.sort_cellvars() for i in range(len(self.insts)): t = self.insts[i] if len(t) == 2: opname, oparg = t conv = self._converters.get(opname, None) if conv: self.insts[i] = opname, conv(self, oparg) self.stage = CONV def sort_cellvars(self): """Sort cellvars in the order of varnames and prune from freevars. """ cells = {} for name in self.cellvars: cells[name] = 1 self.cellvars = [name for name in self.varnames if name in cells] for name in self.cellvars: del cells[name] self.cellvars = self.cellvars + cells.keys() self.closure = self.cellvars + self.freevars def _lookupName(self, name, list): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before comparing the values. """ t = type(name) for i in range(len(list)): if t == type(list[i]) and list[i] == name: return i end = len(list) list.append(name) return end _converters = {} def _convert_LOAD_CONST(self, arg): if hasattr(arg, 'getCode'): arg = arg.getCode() return self._lookupName(arg, self.consts) def _convert_LOAD_FAST(self, arg): self._lookupName(arg, self.names) return self._lookupName(arg, self.varnames) _convert_STORE_FAST = _convert_LOAD_FAST _convert_DELETE_FAST = _convert_LOAD_FAST def _convert_LOAD_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) def _convert_NAME(self, arg): if self.klass is None: self._lookupName(arg, self.varnames) return self._lookupName(arg, self.names) _convert_STORE_NAME = _convert_NAME _convert_DELETE_NAME = _convert_NAME _convert_IMPORT_NAME = _convert_NAME _convert_IMPORT_FROM = _convert_NAME _convert_STORE_ATTR = _convert_NAME _convert_LOAD_ATTR = _convert_NAME _convert_DELETE_ATTR = _convert_NAME _convert_LOAD_GLOBAL = _convert_NAME _convert_STORE_GLOBAL = _convert_NAME _convert_DELETE_GLOBAL = _convert_NAME def _convert_DEREF(self, arg): self._lookupName(arg, self.names) self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _convert_LOAD_DEREF = _convert_DEREF _convert_STORE_DEREF = _convert_DEREF def _convert_LOAD_CLOSURE(self, arg): self._lookupName(arg, self.varnames) return self._lookupName(arg, self.closure) _cmp = list(dis.cmp_op) def _convert_COMPARE_OP(self, arg): return self._cmp.index(arg) # similarly for other opcodes... for name, obj in locals().items(): if name[:9] == "_convert_": opname = name[9:] _converters[opname] = obj del name, obj, opname def makeByteCode(self): assert self.stage == CONV self.lnotab = lnotab = LineAddrTable() for t in self.insts: opname = t[0] if len(t) == 1: lnotab.addCode(self.opnum[opname]) else: oparg = t[1] if opname == "SET_LINENO": lnotab.nextLine(oparg) continue hi, lo = twobyte(oparg) try: lnotab.addCode(self.opnum[opname], lo, hi) except ValueError: print opname, oparg print self.opnum[opname], lo, hi raise self.stage = DONE opnum = {} for num in range(len(dis.opname)): opnum[dis.opname[num]] = num del num def newCodeObject(self): assert self.stage == DONE if (self.flags & CO_NEWLOCALS) == 0: nlocals = 0 else: nlocals = len(self.varnames) argcount = self.argcount if self.flags & CO_VARKEYWORDS: argcount = argcount - 1 return types.CodeType(argcount, nlocals, self.stacksize, self.flags, self.lnotab.getCode(), self.getConsts(), tuple(self.names), tuple(self.varnames), self.filename, self.name, self.lnotab.firstline, self.lnotab.getTable(), tuple(self.freevars), tuple(self.cellvars)) def getConsts(self): """Return a tuple for the const slot of the code object Must convert references to code (MAKE_FUNCTION) to code objects recursively. """ l = [] for elt in self.consts: if isinstance(elt, PyFlowGraph): elt = elt.getCode() l.append(elt) return tuple(l) def isJump(opname): if opname[:4] == 'JUMP': return 1 class TupleArg: """Helper for marking func defs with nested tuples in arglist""" def __init__(self, count, names): self.count = count self.names = names def __repr__(self): return "TupleArg(%s, %s)" % (self.count, self.names) def getName(self): return ".%d" % self.count def getArgCount(args): argcount = len(args) if args: for arg in args: if isinstance(arg, TupleArg): numNames = len(misc.flatten(arg.names)) argcount = argcount - numNames return argcount def twobyte(val): """Convert an int argument into high and low bytes""" assert isinstance(val, int) return divmod(val, 256) class LineAddrTable: """lnotab This class builds the lnotab, which is documented in compile.c. Here's a brief recap: For each SET_LINENO instruction after the first one, two bytes are added to lnotab. (In some cases, multiple two-byte entries are added.) The first byte is the distance in bytes between the instruction for the last SET_LINENO and the current SET_LINENO. The second byte is offset in line numbers. If either offset is greater than 255, multiple two-byte entries are added -- see compile.c for the delicate details. """ def __init__(self): self.code = [] self.codeOffset = 0 self.firstline = 0 self.lastline = 0 self.lastoff = 0 self.lnotab = [] def addCode(self, *args): for arg in args: self.code.append(chr(arg)) self.codeOffset = self.codeOffset + len(args) def nextLine(self, lineno): if self.firstline == 0: self.firstline = lineno self.lastline = lineno else: # compute deltas addr = self.codeOffset - self.lastoff line = lineno - self.lastline # Python assumes that lineno always increases with # increasing bytecode address (lnotab is unsigned char). # Depending on when SET_LINENO instructions are emitted # this is not always true. Consider the code: # a = (1, # b) # In the bytecode stream, the assignment to "a" occurs # after the loading of "b". This works with the C Python # compiler because it only generates a SET_LINENO instruction # for the assignment. if line >= 0: push = self.lnotab.append while addr > 255: push(255); push(0) addr -= 255 while line > 255: push(addr); push(255) line -= 255 addr = 0 if addr > 0 or line > 0: push(addr); push(line) self.lastline = lineno self.lastoff = self.codeOffset def getCode(self): return ''.join(self.code) def getTable(self): return ''.join(map(chr, self.lnotab)) class StackDepthTracker: # XXX 1. need to keep track of stack depth on jumps # XXX 2. at least partly as a result, this code is broken def findDepth(self, insts, debug=0): depth = 0 maxDepth = 0 for i in insts: opname = i[0] if debug: print i, delta = self.effect.get(opname, None) if delta is not None: depth = depth + delta else: # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta is None: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth > maxDepth: maxDepth = depth if debug: print depth, maxDepth return maxDepth effect = { 'POP_TOP': -1, 'DUP_TOP': 1, 'LIST_APPEND': -1, 'SET_ADD': -1, 'MAP_ADD': -2, 'SLICE+1': -1, 'SLICE+2': -1, 'SLICE+3': -2, 'STORE_SLICE+0': -1, 'STORE_SLICE+1': -2, 'STORE_SLICE+2': -2, 'STORE_SLICE+3': -3, 'DELETE_SLICE+0': -1, 'DELETE_SLICE+1': -2, 'DELETE_SLICE+2': -2, 'DELETE_SLICE+3': -3, 'STORE_SUBSCR': -3, 'DELETE_SUBSCR': -2, # PRINT_EXPR? 'PRINT_ITEM': -1, 'RETURN_VALUE': -1, 'YIELD_VALUE': -1, 'EXEC_STMT': -3, 'BUILD_CLASS': -2, 'STORE_NAME': -1, 'STORE_ATTR': -2, 'DELETE_ATTR': -1, 'STORE_GLOBAL': -1, 'BUILD_MAP': 1, 'COMPARE_OP': -1, 'STORE_FAST': -1, 'IMPORT_STAR': -1, 'IMPORT_NAME': -1, 'IMPORT_FROM': 1, 'LOAD_ATTR': 0, # unlike other loads # close enough... 'SETUP_EXCEPT': 3, 'SETUP_FINALLY': 3, 'FOR_ITER': 1, 'WITH_CLEANUP': -1, } # use pattern match patterns = [ ('BINARY_', -1), ('LOAD_', 1), ] def UNPACK_SEQUENCE(self, count): return count-1 def BUILD_TUPLE(self, count): return -count+1 def BUILD_LIST(self, count): return -count+1 def BUILD_SET(self, count): return -count+1 def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return -(lo + hi * 2) def CALL_FUNCTION_VAR(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_KW(self, argc): return self.CALL_FUNCTION(argc)-1 def CALL_FUNCTION_VAR_KW(self, argc): return self.CALL_FUNCTION(argc)-2 def MAKE_FUNCTION(self, argc): return -argc def MAKE_CLOSURE(self, argc): # XXX need to account for free variables too! return -argc def BUILD_SLICE(self, argc): if argc == 2: return -1 elif argc == 3: return -2 def DUP_TOPX(self, argc): return argc findDepth = StackDepthTracker().findDepth
{ "repo_name": "nmercier/linux-cross-gcc", "path": "win32/bin/Lib/compiler/pyassem.py", "copies": "3", "size": "25023", "license": "bsd-3-clause", "hash": 8832250615295317000, "line_mean": 30.7955439056, "line_max": 80, "alpha_frac": 0.5216400911, "autogenerated": false, "ratio": 4.052307692307692, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0016807817454374872, "num_lines": 763 }
''' AFLR3 wrapper ''' import os # --- OpenMDAO imports from openmdao.api import Problem, Group, ExternalCode, IndepVarComp class AFLR3(ExternalCode): ''' OpenMDAO component for executing AFLR3 ''' aflr3_exec = 'aflr3.script' # --------------------------------------- # --- File Wrapper/Template for AFLR3 --- # --------------------------------------- def __init__(self, *args, **kwargs): # ------------------------------------------------- # --- Constructor for Surface Meshing Component --- # ------------------------------------------------- super(AFLR3, self).__init__() self.options['external_input_files'] = [ os.path.join('..', 'Meshing', 'AFLR3', 'Hyperloop_PW.b8.ugrid'), os.path.join('..', 'Meshing', 'AFLR3', 'Hyperloop.tags') ] self.options['external_output_files'] = [os.path.join( '..', 'Aero', 'Fun3D', 'Hyperloop.b8.ugrid')] self.options['command'] = ['sh', self.aflr3_exec] def execute(self): # ------------------------------- # --- Execute AFLR3 Component --- # ------------------------------- super(AFLR3, self).solve_nonlinear(params, unknowns, resids) if __name__ == "__main__": # ------------------------- # --- Default Test Case --- # ------------------------- p = Problem(root=Group()) p.root.add('aflr3', AFLR3()) p.setup() p.run()
{ "repo_name": "andipeng/MagnePlane", "path": "src/hyperloop/Python/OldMagnePlaneCode/aflr3.py", "copies": "4", "size": "1457", "license": "apache-2.0", "hash": 1991653149782509800, "line_mean": 29.3541666667, "line_max": 76, "alpha_frac": 0.4296499657, "autogenerated": false, "ratio": 3.8241469816272966, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6253796947327296, "avg_score": null, "num_lines": null }
''' a-flux-one-direction.py ========================= AIM: Perform basic statistics on the data and gets the maximal stray light flux for one orbit INPUT: files: - <height>_flux/flux_*.dat : data files variables: see section PARAMETERS (below) OUTPUT: <height>_figures/ : evolution of stray light CMD: python a-flux-one-direction.py ISSUES: <none known> REQUIRES:- standard python libraries, specific libraries in resources/ - Structure of the root folder: * <height>_flux/ --> flux files * <height>_figures/ --> figures * <height>_misc/ --> storages of data * all_figures/ --> comparison figures REMARKS: <none> ''' ################################################################################ import numpy as np import pylab as plt from resources.routines import * from resources.TimeStepping import * import parameters as param import resources.constants as const import resources.figures as figures from matplotlib import rc rc('font',**{'family':'serif','serif':['Palatino'],'size':14}) rc('text', usetex=True) # Orbit in which to search o = 41 orbitID = 1 t_ini, t_end, a_ini, a_end = orbit2times(o,orbitID) sl = np.zeros(t_end-t_ini) for minute in range(a_ini,a_end): ra, dec, S_sl = load_flux_file(minute, 'flux_', folder='%d_flux/' % orbitID) idr = np.where(np.abs(ra-1.806) < 0.1)[0] idd = np.where(np.abs(dec+0.55) < 0.1)[0] id_ = np.intersect1d(idr, idd) sl[minute-a_ini] = S_sl[id_] print S_sl[id_] fig=plt.figure() ax = plt.subplot(111) fig.text(0.12, 0.91, r'$\times 10^{-2}$') fig.text(0.2, 0.8, r'$\alpha=103^\circ,\ \delta=-31.5^\circ$') plt.xlabel('Minutes in orbit %d [min]' % o) plt.ylabel(r'$\mathrm{Mean\ stray\ light\ flux\ }\left[\frac{\mathrm{ph}}{\mathrm{px}\cdot\mathrm{s}}\right]$') plt.grid() plt.plot(sl*100,lw=2) from matplotlib.ticker import MaxNLocator, MultipleLocator, FormatStrFormatter ax.yaxis.set_major_locator(MultipleLocator(0.5)) ax.yaxis.set_minor_locator(MultipleLocator(0.25)) ax.xaxis.set_major_locator(MultipleLocator(20.)) ax.xaxis.set_minor_locator(MultipleLocator(10.)) ax.xaxis.grid(True,'minor') ax.yaxis.grid(True,'minor') ax.xaxis.grid(True,'major',linewidth=2) ax.yaxis.grid(True,'major',linewidth=2) figures.savefig('all_figures/flux_fixed_direction',fig,True) plt.show()
{ "repo_name": "kuntzer/SALSA-public", "path": "a_flux-one-direction.py", "copies": "1", "size": "2279", "license": "bsd-3-clause", "hash": 6666022488726133000, "line_mean": 28.5974025974, "line_max": 111, "alpha_frac": 0.6682755595, "autogenerated": false, "ratio": 2.810110974106042, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3978386533606042, "avg_score": null, "num_lines": null }
# a foomodule for simple polls # Rene Kuettner <rene@bitkanal.net> # # licensed under GPL version 2 from datetime import datetime, timedelta import math import foomodules.Base as Base # FIXME: global variables are evil active_polls = {} class Poll(object): def __init__(self, pollctl, owner=(None, None), dt_start=datetime.now(), duration=1, topic=None, options=[], timer_name=None): self.pollctl = pollctl self.owner = owner self.dt_start = dt_start self.duration = duration self.topic = topic self.options = options self.timer_name = timer_name self._votes = {} self._results = [] def _recalc_results(self): self._results = [ [0, 0] for i in range(len(self.options)) ] vote_count = len(self.votes.keys()) # are there any votes? if vote_count == 0: return # count votes for each option for user in self.votes.keys(): index = self.votes[user][1] self._results[index][0] += 1 # calculate percentage for i in range(0, len(self._results)): self._results[i][1] = self._results[i][0] / vote_count def set_vote(self, ident, nick, index): self._votes[ident] = (nick, index) self._recalc_results() def unset_vote(self, ident): del self._votes[ident] self._recalc_results() @property def votes(self): return self._votes @property def voters(self): return self._votes.keys() @property def results(self): return self._results class Vote(Base.ArgparseCommand): # string templates ST_INDEX_HELP = 'The index of the option you are voting for.' ST_NO_OPT_WITH_IDX = 'There is no option with index {index} for this poll.' ST_VOTE_COUNTED = 'Vote counted: {items}' ST_VOTE_WITHDRAWN = 'Vote withdrawn: {items}' ST_NOT_VOTED = 'You have not voted yet.' ST_VOTE_ITEM = '[ {bar} {option} ({perc}%) ]' ST_VOTE_ITEM_SEP = ', ' ST_PERC_BARS = '▁▂▃▄▅▆▇█' ST_NO_ACTIVE_POLL = 'No active poll in this room.' def __init__(self, timeout=3, command_name='vote', maxlen=64, **kwargs): super().__init__(command_name, **kwargs) self.timeout = timeout self.maxlen = maxlen self.argparse.add_argument( 'index', type = int, help = self.ST_INDEX_HELP) def _send_update_msg(self, poll, orig_msg, reply): vote_count = len(poll.votes.keys()) items_list = [] for i in range(0, len(poll.results)): bar_index = int((len(self.ST_PERC_BARS) - 1) * poll.results[i][1]) items_list.append(self.ST_VOTE_ITEM.format( bar = list(self.ST_PERC_BARS)[bar_index], perc = round(poll.results[i][1] * 100), index = i + 1, option = poll.options[i])) self.reply(orig_msg, reply.format( count = vote_count, items = self.ST_VOTE_ITEM_SEP.join(items_list))) def _call(self, msg, args, errorSink=None): mucname = msg.get_mucroom() # get vote for this room if available try: poll = active_polls[mucname] except KeyError: self.reply(msg, self.ST_NO_ACTIVE_POLL) return ident = poll.pollctl.get_identifier_from_msg(msg) args.index = int(args.index) if args.index == 0: # withdraw try: poll.unset_vote(ident) reply = self.ST_VOTE_WITHDRAWN except KeyError: self.reply(msg, self.ST_NOT_VOTED) return else: # vote if args.index < 1 or args.index > len(poll.options): self.reply(msg, self.ST_NO_OPT_WITH_IDX.format( index = args.index)) return poll.set_vote(ident, msg['mucnick'], args.index - 1) reply = self.ST_VOTE_COUNTED self._send_update_msg(poll, msg, reply) class PollCtl(Base.ArgparseCommand): ST_ARG_HELP_ACTION = 'Poll management actions' ST_ARG_HELP_DURATION = 'Duration of the poll in minutes (defaults to: 1)' ST_ARG_HELP_TOPIC = 'The topic of the poll (e.g. a question)' ST_ARG_HELP_OPTIONS = 'The options voters may choose from.' ST_ARG_HELP_START = 'Start a new vote' ST_ARG_HELP_CANCEL = 'Cancel an active poll' ST_ARG_HELP_STATUS = 'Request poll status' ST_SHORT_USAGE = 'Usage: !pollctl [-h] {start,cancel,status} ...' ST_POLL_ACTIVE = 'There is already an active poll in this room!' ST_NO_ACTIVE_POLL = 'There is no active poll in this room at the moment!' ST_INVALID_DURATION = 'Poll duration must be in range [1, 60] ∌ {duration}!' ST_TOO_FEW_OPTIONS = 'You have to specify at least 2 *different* options!' ST_TOO_MANY_OPTIONS = 'You must not add more than 9 vote options!' ST_POLL_ANNOUNCEMENT = ('{owner} has started a poll ({t} min): "{topic}"\n' ' {options}') ST_POLL_OPTION = ' [{index}]: {option} ' ST_CANCELED_BY_USER = 'Poll has been canceled by {owner}.' ST_CANCELED_NO_VOTES = 'Poll canceled. No votes have been placed!' ST_CANCEL_DENIED = 'Only {owner} may cancel this poll!' ST_POLL_STATUS = ('Active poll from {owner}: "{topic}"\n' ' {options}\n' 'Place your vote with "!vote <index>". {tm} mins and {ts} secs left.') ST_POLL_TIME_LEFT = 'Poll ends soon. Don\'t forget to vote!' ST_POLL_RESULTS = ('{owner}\'s poll "{topic}" finished with {count} votes: ' '{results}') ST_RESULT_BAR = '\n {perc: >3}% {bar:▏<10}▏({count: >2}) {option}' ST_RESULT_BAR_BLOCKS = '█▏▎▍▌▋▊█' def __init__(self, timeout=3, command_name='pollctl', maxlen=256, use_jid=True, **kwargs): super().__init__(command_name, **kwargs) self.timeout = timeout self.maxlen = maxlen self._use_jid = use_jid subparsers = self.argparse.add_subparsers( dest='action', help=self.ST_ARG_HELP_ACTION ) # arg parser for the start command parser_start = subparsers.add_parser('start', help=self.ST_ARG_HELP_START) self.subparsers.append(parser_start) parser_start.add_argument( '-d', '--duration', dest = 'duration', default = 1, type = int, help = self.ST_ARG_HELP_DURATION) parser_start.add_argument('topic', help=self.ST_ARG_HELP_TOPIC) parser_start.add_argument('options', nargs = '+', help=self.ST_ARG_HELP_OPTIONS) parser_start.set_defaults(func=self._poll_start) # arg parser for the cancel command parser_cancel = subparsers.add_parser('cancel', help = self.ST_ARG_HELP_CANCEL, aliases = [ 'stop', 'abort' ]) self.subparsers.append(parser_cancel) parser_cancel.set_defaults(func=self._poll_cancel) # arg parser for the status command parser_status = subparsers.add_parser('status', help = self.ST_ARG_HELP_STATUS, aliases = [ 'info' ]) self.subparsers.append(parser_status) parser_status.set_defaults(func=self._poll_status) def get_identifier_from_muc_and_nick(self, mucjid, nick): if self._use_jid: return self.XMPP.muc.getJidProperty(mucjid, nick, 'jid') else: return nick def get_identifier_from_msg(self, msg): return self.get_identifier_from_muc_and_nick( msg['from'].bare, msg['mucnick']) def _call(self, msg, args, errorSink=None): # func has been set using set_default args.func(msg, args, errorSink) def _poll_start(self, msg, args, errorSink): mucname = msg.get_mucroom() if mucname in active_polls.keys(): self.reply(msg, self.ST_POLL_ACTIVE) return args.duration = int(args.duration) args.options = list(set(args.options)) # remove dups # maybe we want to allow for longer vote durations # however, votes may block other votes in the channel if args.duration < 1 or args.duration > 60: self.reply(msg, self.ST_INVALID_DURATION.format( duration=args.duration)) return if len(args.options) < 2: self.reply(msg, self.ST_TOO_FEW_OPTIONS) return if len(args.options) > 9: self.reply(msg, self.ST_TOO_MANY_OPTIONS) return # create poll owner_info = (msg['mucnick'], self.get_identifier_from_msg(msg)) active_polls[mucname] = Poll( self, owner = owner_info, dt_start = datetime.now(), duration = args.duration, topic = args.topic, options = args.options, timer_name = '{muc}_poll_service'.format(muc=mucname)) # schedule finish event for this poll self.xmpp.scheduler.add( active_polls[mucname].timer_name, args.duration * 60, self._on_poll_finished_event, kwargs = { 'room': mucname, 'msg': msg }) # tell everyone about the new poll options_str = '' for i in range(0, len(args.options)): options_str += self.ST_POLL_OPTION.format( index = i + 1, option = args.options[i]) self.reply(msg, self.ST_POLL_ANNOUNCEMENT.format( owner = owner_info[0], topic = args.topic, t = args.duration, options = options_str)) def _poll_cancel(self, msg, args, errorSink): user = self.get_identifier_from_msg(msg) mucname = msg.get_mucroom() try: poll = active_polls[mucname] except KeyError: self.reply(msg, self.ST_NO_ACTIVE_POLL) return if poll.owner[1] == user: del active_polls[mucname] self.xmpp.scheduler.remove(poll.timer_name) self.reply(msg, self.ST_CANCELED_BY_USER.format( owner=poll.owner[0])) else: self.reply(msg, self.ST_CANCEL_DENIED.format( owner=poll.owner[0])) def _poll_status(self, msg, args, errorSink): mucname = msg.get_mucroom() try: poll = active_polls[mucname] except KeyError: self.reply(msg, self.ST_NO_ACTIVE_POLL) return delta_t = poll.dt_start + timedelta(minutes=poll.duration) - datetime.now() minutes_left = int(delta_t.total_seconds() / 60) seconds_left = int(delta_t.total_seconds() % 60) options_str = '' for i in range(0, len(poll.options)): options_str += self.ST_POLL_OPTION.format( index = i + 1, option = poll.options[i]) self.reply(msg, self.ST_POLL_STATUS.format( owner = poll.owner[0], topic = poll.topic, tm = minutes_left, ts = seconds_left, count = len(poll.votes.keys()), options = options_str)) def _on_poll_bump_event(self, room=None, msg=None): poll = active_polls[room] delta_t = poll.dt_start + timedelta(minutes=poll.duration) seconds_left = (delta_t - datetime.now()).total_seconds() if seconds_left >= 0: self.reply(msg, self.ST_POLL_TIME_LEFT.format( s=int(seconds_left))) def _on_poll_finished_event(self, room=None, msg=None): poll = active_polls[room] # remove poll del active_polls[room] vc = len(poll.votes.keys()) if vc < 1: self.reply(msg, self.ST_CANCELED_NO_VOTES) return results_str = '' for i in range(0, len(poll.results)): real_bar_width = poll.results[i][1] * 10.0 full_block_width = int(real_bar_width) frac_block_index = round(math.modf(real_bar_width)[0] * 7.0) results_bar = '{full}{fract}'.format( full = self.ST_RESULT_BAR_BLOCKS[0] * full_block_width, fract = self.ST_RESULT_BAR_BLOCKS[frac_block_index] if frac_block_index > 0 else '') results_str += self.ST_RESULT_BAR.format( option = poll.options[i], bar = results_bar, perc = int(poll.results[i][1] * 100), count = poll.results[i][0]) self.reply(msg, self.ST_POLL_RESULTS.format( owner = poll.owner[0], topic = poll.topic, count = vc, results = results_str))
{ "repo_name": "horazont/xmpp-crowd", "path": "foomodules/Poll.py", "copies": "1", "size": "13459", "license": "mit", "hash": -3341357589599865000, "line_mean": 36.4776536313, "line_max": 100, "alpha_frac": 0.5326078855, "autogenerated": false, "ratio": 3.615467528967933, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4648075414467933, "avg_score": null, "num_lines": null }
"""A fork of flask_restplus.reqparse for finer error handling""" from __future__ import unicode_literals import decimal import six import flask_restplus from collections import Hashable from copy import deepcopy from flask import current_app, request from werkzeug.datastructures import MultiDict, FileStorage from werkzeug import exceptions from flask_restplus.errors import abort, SpecsError from flask_restplus.marshalling import marshal from flask_restplus.model import Model from flask_restplus._http import HTTPStatus class ParseResult(dict): """ The default result container as an Object dict. """ def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) def __setattr__(self, name, value): self[name] = value _friendly_location = { "json": "the JSON body", "form": "the post body", "args": "the query string", "values": "the post body or the query string", "headers": "the HTTP headers", "cookies": "the request's cookies", "files": "an uploaded file", } #: Maps Flask-RESTPlus RequestParser locations to Swagger ones LOCATIONS = { "args": "query", "form": "formData", "headers": "header", "json": "body", "values": "query", "files": "formData", } #: Maps Python primitives types to Swagger ones PY_TYPES = { int: "integer", str: "string", bool: "boolean", float: "number", None: "void", } SPLIT_CHAR = "," text_type = lambda x: six.text_type(x) # noqa class Argument(object): """ :param name: Either a name or a list of option strings, e.g. foo or -f, --foo. :param default: The value produced if the argument is absent from the request. :param dest: The name of the attribute to be added to the object returned by :meth:`~reqparse.RequestParser.parse_args()`. :param bool required: Whether or not the argument may be omitted (optionals only). :param string action: The basic type of action to be taken when this argument is encountered in the request. Valid options are "store" and "append". :param bool ignore: Whether to ignore cases where the argument fails type conversion :param type: The type to which the request argument should be converted. If a type raises an exception, the message in the error will be returned in the response. Defaults to :class:`unicode` in python2 and :class:`str` in python3. :param location: The attributes of the :class:`flask.Request` object to source the arguments from (ex: headers, args, etc.), can be an iterator. The last item listed takes precedence in the result set. :param choices: A container of the allowable values for the argument. :param help: A brief description of the argument, returned in the response when the argument is invalid. May optionally contain an "{error_msg}" interpolation token, which will be replaced with the text of the error raised by the type converter. :param bool case_sensitive: Whether argument values in the request are case sensitive or not (this will convert all values to lowercase) :param bool store_missing: Whether the arguments default value should be stored if the argument is missing from the request. :param bool trim: If enabled, trims whitespace around the argument. :param bool nullable: If enabled, allows null value in argument. :param error: The error message to be displayed when a validation error occurs. If empty, {help} will be shown instead. """ def __init__( self, name, default=None, dest=None, required=False, ignore=False, type=text_type, location=("json", "values",), choices=(), action="store", help=None, operators=("=",), case_sensitive=True, store_missing=True, trim=False, nullable=True, error=None, ): self.name = name self.default = default self.dest = dest self.required = required self.ignore = ignore self.location = location self.type = type self.choices = choices self.action = action self.help = help self.case_sensitive = case_sensitive self.operators = operators self.store_missing = store_missing self.trim = trim self.nullable = nullable self.error = error def source(self, request): """ Pulls values off the request in the provided location :param request: The flask request object to parse arguments from """ if isinstance(self.location, six.string_types): value = getattr(request, self.location, MultiDict()) if callable(value): value = value() if value is not None: return value else: values = MultiDict() for l in self.location: value = getattr(request, l, None) if callable(value): value = value() if value is not None: values.update(value) return values return MultiDict() def convert(self, value, op): # Don't cast None if value is None: if not self.nullable: raise ValueError("Must not be null!") return None elif isinstance(self.type, Model) and isinstance(value, dict): return marshal(value, self.type) # and check if we're expecting a filestorage and haven't overridden `type` # (required because the below instantiation isn't valid for FileStorage) elif isinstance(value, FileStorage) and self.type == FileStorage: return value try: return self.type(value, self.name, op) except TypeError: try: if self.type is decimal.Decimal: return self.type(str(value), self.name) else: return self.type(value, self.name) except TypeError: return self.type(value) def handle_validation_error(self, error, bundle_errors): """ Called when an error is raised while parsing. Aborts the request with a 400 status and an error message :param error: the error that was raised :param bool bundle_errors: do not abort when first error occurs, return a dict with the name of the argument and the error message to be bundled """ error_str = six.text_type(error) if self.error: error_msg = six.text_type(self.error) elif self.help: error_msg = " ".join([six.text_type(self.help), error_str]) else: error_msg = error_str errors = {self.name: error_msg} if bundle_errors: return ValueError(error), errors abort(HTTPStatus.BAD_REQUEST, "Input payload validation failed", errors=errors) def parse(self, request, bundle_errors=False): """ Parses argument value(s) from the request, converting according to the argument's type. :param request: The flask request object to parse arguments from :param bool bundle_errors: do not abort when first error occurs, return a dict with the name of the argument and the error message to be bundled """ bundle_errors = current_app.config.get("BUNDLE_ERRORS", False) or bundle_errors source = self.source(request) results = [] # Sentinels _not_found = False _found = True for operator in self.operators: name = self.name + operator.replace("=", "", 1) if name in source: # Account for MultiDict and regular dict if hasattr(source, "getlist"): values = source.getlist(name) else: values = [source.get(name)] for value in values: if hasattr(value, "strip") and self.trim: value = value.strip() if hasattr(value, "lower") and not self.case_sensitive: value = value.lower() if hasattr(self.choices, "__iter__"): self.choices = [choice.lower() for choice in self.choices] try: if self.action == "split": value = [ self.convert(v, operator) for v in value.split(SPLIT_CHAR) ] else: value = self.convert(value, operator) except Exception as error: if self.ignore: continue return self.handle_validation_error(error, bundle_errors) if self.choices and value not in self.choices: msg = "The value '{0}' is not a valid choice for '{1}'.".format( value, name ) return self.handle_validation_error(msg, bundle_errors) if name in request.unparsed_arguments: request.unparsed_arguments.pop(name) results.append(value) if not results and self.required: if isinstance(self.location, six.string_types): location = _friendly_location.get(self.location, self.location) else: locations = [_friendly_location.get(loc, loc) for loc in self.location] location = " or ".join(locations) error_msg = "Missing required parameter in {0}".format(location) return self.handle_validation_error(error_msg, bundle_errors) if not results: if callable(self.default): return self.default(), _not_found else: return self.default, _not_found if self.action == "append": return results, _found if self.action == "store" or len(results) == 1: return results[0], _found return results, _found @property def __schema__(self): if self.location == "cookie": return param = {"name": self.name, "in": LOCATIONS.get(self.location, "query")} _handle_arg_type(self, param) if self.required: param["required"] = True if self.help: param["description"] = self.help if self.default is not None: param["default"] = ( self.default() if callable(self.default) else self.default ) if self.action == "append": param["items"] = {"type": param["type"]} param["type"] = "array" param["collectionFormat"] = "multi" if self.action == "split": param["items"] = {"type": param["type"]} param["type"] = "array" param["collectionFormat"] = "csv" if self.choices: param["enum"] = self.choices param["collectionFormat"] = "multi" return param class RequestParser(object): """ Enables adding and parsing of multiple arguments in the context of a single request. Ex:: from flask_restplus import RequestParser parser = RequestParser() parser.add_argument('foo') parser.add_argument('int_bar', type=int) args = parser.parse_args() :param bool trim: If enabled, trims whitespace on all arguments in this parser :param bool bundle_errors: If enabled, do not abort when first error occurs, return a dict with the name of the argument and the error message to be bundled and return all validation errors """ def __init__( self, argument_class=Argument, result_class=ParseResult, trim=False, bundle_errors=False, ): self.args = [] self.argument_class = argument_class self.result_class = result_class self.trim = trim self.bundle_errors = bundle_errors def add_argument(self, *args, **kwargs): """ Adds an argument to be parsed. Accepts either a single instance of Argument or arguments to be passed into :class:`Argument`'s constructor. See :class:`Argument`'s constructor for documentation on the available options. """ if len(args) == 1 and isinstance(args[0], self.argument_class): self.args.append(args[0]) else: self.args.append(self.argument_class(*args, **kwargs)) # Do not know what other argument classes are out there if self.trim and self.argument_class is Argument: # enable trim for appended element self.args[-1].trim = kwargs.get("trim", self.trim) return self def parse_args(self, req=None, strict=False): """ Parse all arguments from the provided request and return the results as a ParseResult :param bool strict: if req includes args not in parser, throw 400 BadRequest exception :return: the parsed results as :class:`ParseResult` (or any class defined as :attr:`result_class`) :rtype: ParseResult """ if req is None: req = request result = self.result_class() # A record of arguments not yet parsed; as each is found # among self.args, it will be popped out req.unparsed_arguments = ( dict(self.argument_class("").source(req)) if strict else {} ) errors = {} for arg in self.args: value, found = arg.parse(req, self.bundle_errors) if isinstance(value, ValueError): errors.update(found) found = None if found or arg.store_missing: result[arg.dest or arg.name] = value if errors: # abort(HTTPStatus.BAD_REQUEST, 'Input payload validation failed', errors=errors) abort(HTTPStatus.BAD_REQUEST, str(list(errors.values())[0]), errors=errors) if strict and req.unparsed_arguments: arguments = ", ".join(req.unparsed_arguments.keys()) msg = "Unknown arguments: {0}".format(arguments) raise exceptions.BadRequest(msg) return result def copy(self): """Creates a copy of this RequestParser with the same set of arguments""" parser_copy = self.__class__(self.argument_class, self.result_class) parser_copy.args = deepcopy(self.args) parser_copy.trim = self.trim parser_copy.bundle_errors = self.bundle_errors return parser_copy def replace_argument(self, name, *args, **kwargs): """Replace the argument matching the given name with a new version.""" new_arg = self.argument_class(name, *args, **kwargs) for index, arg in enumerate(self.args[:]): if new_arg.name == arg.name: del self.args[index] self.args.append(new_arg) break return self def remove_argument(self, name): """Remove the argument matching the given name.""" for index, arg in enumerate(self.args[:]): if name == arg.name: del self.args[index] break return self @property def __schema__(self): params = [] locations = set() for arg in self.args: param = arg.__schema__ if param: params.append(param) locations.add(param["in"]) if "body" in locations and "formData" in locations: raise SpecsError("Can't use formData and body at the same time") return params def _handle_arg_type(arg, param): if isinstance(arg.type, Hashable) and arg.type in PY_TYPES: param["type"] = PY_TYPES[arg.type] elif hasattr(arg.type, "__apidoc__"): param["type"] = arg.type.__apidoc__["name"] param["in"] = "body" elif hasattr(arg.type, "__schema__"): param.update(arg.type.__schema__) elif arg.location == "files": param["type"] = "file" else: param["type"] = "string"
{ "repo_name": "royragsdale/picoCTF", "path": "picoCTF-web/api/reqparse.py", "copies": "2", "size": "16557", "license": "mit", "hash": 909731619432618100, "line_mean": 34.9934782609, "line_max": 106, "alpha_frac": 0.5792716072, "autogenerated": false, "ratio": 4.496740901683867, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6076012508883868, "avg_score": null, "num_lines": null }
# A fork of https://github.com/cms-sw/cmssw/blob/CMSSW_7_6_X/HLTrigger/Configuration/python/Tools/dasFileQuery.py, # which can query DAS and return a list of files. import sys import json import das_client_fork as das_client def dasFileQuery(dataset, instance='prod/global'): query = 'dataset dataset=%s instance=%s' % (dataset, instance) host = 'https://cmsweb.cern.ch' # default idx = 0 # default limit = 0 # unlimited debug = 0 # default thr = 300 # default ckey = "" # default cert = "" # default jsondict = das_client.get_data(host, query, idx, limit, debug, thr, ckey, cert) # check if the pattern matches none, many, or one dataset if not jsondict['data'] or not jsondict['data'][0]['dataset']: sys.stderr.write('Error: the pattern "%s" does not match any dataset\n' % dataset) sys.exit(1) return [] elif len(jsondict['data']) > 1: sys.stderr.write('Error: the pattern "%s" matches multiple datasets\n' % dataset) for d in jsondict['data']: sys.stderr.write(' %s\n' % d['dataset'][0]['name']) sys.exit(1) return [] else: # expand the dataset name dataset = jsondict['data'][0]['dataset'][0]['name'] query = 'instance=%s file dataset=%s' % (instance, dataset) jsondict = das_client.get_data(host, query, idx, limit, debug, thr, ckey, cert) # parse the results in JSON format, and extract the list of files files = sorted( f['file'][0]['name'] for f in jsondict['data'] ) return files
{ "repo_name": "TC01/Treemaker", "path": "Treemaker/python/dbsapi/dasFileQuery.py", "copies": "1", "size": "1632", "license": "mit", "hash": 6489032561331591000, "line_mean": 43.1081081081, "line_max": 114, "alpha_frac": 0.5980392157, "autogenerated": false, "ratio": 3.270541082164329, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.920756005355486, "avg_score": 0.03220404886189385, "num_lines": 37 }
""" A formater module that keeps trac of indentation """ class Formater(object): """ A very simple code formater that handles efficient concatenation and indentation of lines. """ def __init__(self, indent_string=" "): self.__buffer = [] self.__indentation = 0 self.__indent_string = indent_string self.__indent_temp = "" self.__string_buffer = "" def dedent(self): """ Subtracts one indentation level. """ self.__indentation -= 1 self.__indent_temp = self.__indent_string*self.__indentation def indent(self): """ Adds one indentation level. """ self.__indentation += 1 self.__indent_temp = self.__indent_string*self.__indentation def indent_string(self): """ return current indentation string. """ return self.__indent_temp def clear(self): self.__buffer = [] def write(self, text, indent=True, newline=True): """ Writes the string text to the buffer with indentation and a newline if not specified otherwise. """ if text == None: raise RubyError("Convert Error.") if indent: self.__buffer.append(self.__indent_temp) self.__buffer.append(text) if newline: self.__buffer.append("\n") def read(self, size=None): """ Returns a string representation of the buffer. """ if size == None: text = self.__string_buffer + "".join(self.__buffer) self.__buffer = [] self.__string_buffer = "" return text else: if len(self.__string_buffer) < size: self.__string_buffer += "".join(self.__buffer) self.__buffer = [] if len(self.__string_buffer) < size: text, self.__string_buffer = self.__string_buffer, "" return text else: text, self.__string_buffer = self.__string_buffer[:size], \ self.__string_buffer[size:] return text else: text, self.__string_buffer = self.__string_buffer[:size], \ self.__string_buffer[size:] return text def capitalize(self, text): """ Returns a capitalize string. """ if text == '': return '' return text[0].upper() + text[1:]
{ "repo_name": "naitoh/py2rb", "path": "py2rb/formater.py", "copies": "1", "size": "2531", "license": "mit", "hash": 5602359176081805000, "line_mean": 29.8658536585, "line_max": 103, "alpha_frac": 0.5033583564, "autogenerated": false, "ratio": 4.722014925373134, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5725373281773134, "avg_score": null, "num_lines": null }
"""A formatter and StreamHandler for colorizing logging output.""" import logging import sys from certbot import le_util class StreamHandler(logging.StreamHandler): """Sends colored logging output to a stream. If the specified stream is not a tty, the class works like the standard logging.StreamHandler. Default red_level is logging.WARNING. :ivar bool colored: True if output should be colored :ivar bool red_level: The level at which to output """ def __init__(self, stream=None): if sys.version_info < (2, 7): # pragma: no cover # pylint: disable=non-parent-init-called logging.StreamHandler.__init__(self, stream) else: super(StreamHandler, self).__init__(stream) self.colored = (sys.stderr.isatty() if stream is None else stream.isatty()) self.red_level = logging.WARNING def format(self, record): """Formats the string representation of record. :param logging.LogRecord record: Record to be formatted :returns: Formatted, string representation of record :rtype: str """ out = (logging.StreamHandler.format(self, record) if sys.version_info < (2, 7) else super(StreamHandler, self).format(record)) if self.colored and record.levelno >= self.red_level: return ''.join((le_util.ANSI_SGR_RED, out, le_util.ANSI_SGR_RESET)) else: return out
{ "repo_name": "DavidGarciaCat/letsencrypt", "path": "certbot/colored_logging.py", "copies": "4", "size": "1508", "license": "apache-2.0", "hash": -8738075824027138000, "line_mean": 32.5111111111, "line_max": 79, "alpha_frac": 0.6266578249, "autogenerated": false, "ratio": 4.320916905444126, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 45 }
"""A formatter and StreamHandler for colorizing logging output.""" import logging import sys from certbot import util class StreamHandler(logging.StreamHandler): """Sends colored logging output to a stream. If the specified stream is not a tty, the class works like the standard logging.StreamHandler. Default red_level is logging.WARNING. :ivar bool colored: True if output should be colored :ivar bool red_level: The level at which to output """ def __init__(self, stream=None): if sys.version_info < (2, 7): # pragma: no cover # pylint: disable=non-parent-init-called logging.StreamHandler.__init__(self, stream) else: super(StreamHandler, self).__init__(stream) self.colored = (sys.stderr.isatty() if stream is None else stream.isatty()) self.red_level = logging.WARNING def format(self, record): """Formats the string representation of record. :param logging.LogRecord record: Record to be formatted :returns: Formatted, string representation of record :rtype: str """ out = (logging.StreamHandler.format(self, record) if sys.version_info < (2, 7) else super(StreamHandler, self).format(record)) if self.colored and record.levelno >= self.red_level: return ''.join((util.ANSI_SGR_RED, out, util.ANSI_SGR_RESET)) else: return out
{ "repo_name": "jtl999/certbot", "path": "certbot/colored_logging.py", "copies": "7", "size": "1499", "license": "apache-2.0", "hash": 1418232429767131600, "line_mean": 32.3111111111, "line_max": 73, "alpha_frac": 0.6264176117, "autogenerated": false, "ratio": 4.370262390670554, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 45 }
"""A formatter and StreamHandler for colorizing logging output.""" import logging import sys from letsencrypt import le_util class StreamHandler(logging.StreamHandler): """Sends colored logging output to a stream. If the specified stream is not a tty, the class works like the standard logging.StreamHandler. Default red_level is logging.WARNING. :ivar bool colored: True if output should be colored :ivar bool red_level: The level at which to output """ def __init__(self, stream=None): if sys.version_info < (2, 7): # pragma: no cover # pylint: disable=non-parent-init-called logging.StreamHandler.__init__(self, stream) else: super(StreamHandler, self).__init__(stream) self.colored = (sys.stderr.isatty() if stream is None else stream.isatty()) self.red_level = logging.WARNING def format(self, record): """Formats the string representation of record. :param logging.LogRecord record: Record to be formatted :returns: Formatted, string representation of record :rtype: str """ out = (logging.StreamHandler.format(self, record) if sys.version_info < (2, 7) else super(StreamHandler, self).format(record)) if self.colored and record.levelno >= self.red_level: return ''.join((le_util.ANSI_SGR_RED, out, le_util.ANSI_SGR_RESET)) else: return out
{ "repo_name": "TheBoegl/letsencrypt", "path": "letsencrypt/colored_logging.py", "copies": "20", "size": "1512", "license": "apache-2.0", "hash": 2871731704706345500, "line_mean": 32.6, "line_max": 79, "alpha_frac": 0.6276455026, "autogenerated": false, "ratio": 4.332378223495702, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
"""A formatter which formats phone numbers as they are entered. An AsYouTypeFormatter can be created by invoking AsYouTypeFormatter(region_code). After that digits can be added by invoking input_digit() on the formatter instance, and the partially formatted phone number will be returned each time a digit is added. clear() should be invoked before a new number needs to be formatted. See the unit tests for more details on how the formatter is to be used. """ # Based on original Java code: # java/src/com/google/i18n/phonenumbers/AsYouTypeFormatter.java # Copyright (C) 2009-2011 The Libphonenumber Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from .util import u, unicod, U_EMPTY_STRING, U_SPACE from .unicode_util import digit as unicode_digit from .re_util import fullmatch from .phonemetadata import PhoneMetadata from .phonenumberutil import _VALID_PUNCTUATION, REGION_CODE_FOR_NON_GEO_ENTITY from .phonenumberutil import _PLUS_SIGN, _PLUS_CHARS_PATTERN from .phonenumberutil import _extract_country_code, region_code_for_country_code from .phonenumberutil import country_code_for_region, normalize_diallable_chars_only from .phonenumberutil import _formatting_rule_has_first_group_only # Character used when appropriate to separate a prefix, such as a long NDD or # a country calling code, from the national number. _SEPARATOR_BEFORE_NATIONAL_NUMBER = U_SPACE _EMPTY_METADATA = PhoneMetadata(id=unicod(""), international_prefix=unicod("NA"), register=False) # A set of characters that, if found in a national prefix formatting rules, are an indicator to # us that we should separate the national prefix from the number when formatting. _NATIONAL_PREFIX_SEPARATORS_PATTERN = re.compile("[- ]") # A pattern that is used to determine if a number_format under # available_formats is eligible to be used by the AYTF. It is eligible when # the format element under number_format contains groups of the dollar sign # followed by a single digit, separated by valid phone number # punctuation. This prevents invalid punctuation (such as the star sign in # Israeli star numbers) getting into the output of the AYTF. _ELIGIBLE_FORMAT_PATTERN = re.compile(unicod("[") + _VALID_PUNCTUATION + unicod("]*") + unicod("(\\\\\\d") + unicod("[") + _VALID_PUNCTUATION + unicod("]*)+")) # This is the minimum length of national number accrued that is required to # trigger the formatter. The first element of the leading_digits_pattern of each # number_format contains a regular expression that matches up to this number of # digits. _MIN_LEADING_DIGITS_LENGTH = 3 # The digits that have not been entered yet will be represented by a \u2008, # the punctuation space. _DIGIT_PLACEHOLDER = u("\u2008") _DIGIT_PATTERN = re.compile(_DIGIT_PLACEHOLDER) def _get_metadata_for_region(region_code): """The metadata needed by this class is the same for all regions sharing the same country calling code. Therefore, we return the metadata for "main" region for this country calling code.""" country_calling_code = country_code_for_region(region_code) main_country = region_code_for_country_code(country_calling_code) # Set to a default instance of the metadata. This allows us to # function with an incorrect region code, even if formatting only # works for numbers specified with "+". return PhoneMetadata.metadata_for_region(main_country, _EMPTY_METADATA) class AsYouTypeFormatter(object): def __init__(self, region_code): """Gets an AsYouTypeFormatter for the specific region. Arguments: region_code -- The region where the phone number is being entered Return an AsYouTypeFormatter} object, which could be used to format phone numbers in the specific region "as you type" """ self._clear() self._default_country = region_code.upper() self._current_metadata = _get_metadata_for_region(self._default_country) self._default_metadata = self._current_metadata def _maybe_create_new_template(self): """Returns True if a new template is created as opposed to reusing the existing template. When there are multiple available formats, the formatter uses the first format where a formatting template could be created. """ ii = 0 while ii < len(self._possible_formats): number_format = self._possible_formats[ii] pattern = number_format.pattern if self._current_formatting_pattern == pattern: return False if self._create_formatting_template(number_format): self._current_formatting_pattern = pattern if number_format.national_prefix_formatting_rule is None: self._should_add_space_after_national_prefix = False else: self._should_add_space_after_national_prefix = bool(_NATIONAL_PREFIX_SEPARATORS_PATTERN.search(number_format.national_prefix_formatting_rule)) # With a new formatting template, the matched position using # the old template needs to be reset. self._last_match_position = 0 return True else: # Remove the current number format from _possible_formats del self._possible_formats[ii] ii -= 1 ii += 1 self._able_to_format = False return False def _get_available_formats(self, leading_digits): # First decide whether we should use international or national number rules. is_international_number = (self._is_complete_number and len(self._extracted_national_prefix) == 0) if (is_international_number and len(self._current_metadata.intl_number_format) > 0): format_list = self._current_metadata.intl_number_format else: format_list = self._current_metadata.number_format for this_format in format_list: # Discard a few formats that we know are not relevant based on the presence of the national # prefix. if (len(self._extracted_national_prefix) > 0 and _formatting_rule_has_first_group_only(this_format.national_prefix_formatting_rule) and not this_format.national_prefix_optional_when_formatting and not (this_format.domestic_carrier_code_formatting_rule is not None)): # If it is a national number that had a national prefix, any rules that aren't valid with a # national prefix should be excluded. A rule that has a carrier-code formatting rule is # kept since the national prefix might actually be an extracted carrier code - we don't # distinguish between these when extracting it in the AYTF. continue elif (len(self._extracted_national_prefix) == 0 and not self._is_complete_number and not _formatting_rule_has_first_group_only(this_format.national_prefix_formatting_rule) and not this_format.national_prefix_optional_when_formatting): # This number was entered without a national prefix, and this formatting rule requires one, # so we discard it. continue if fullmatch(_ELIGIBLE_FORMAT_PATTERN, this_format.format): self._possible_formats.append(this_format) self._narrow_down_possible_formats(leading_digits) def _narrow_down_possible_formats(self, leading_digits): index_of_leading_digits_pattern = len(leading_digits) - _MIN_LEADING_DIGITS_LENGTH ii = 0 while ii < len(self._possible_formats): num_format = self._possible_formats[ii] ii += 1 if len(num_format.leading_digits_pattern) == 0: # Keep everything that isn't restricted by leading digits. continue last_leading_digits_pattern = min(index_of_leading_digits_pattern, len(num_format.leading_digits_pattern) - 1) leading_digits_pattern = re.compile(num_format.leading_digits_pattern[last_leading_digits_pattern]) m = leading_digits_pattern.match(leading_digits) if not m: # remove the element we've just examined, now at (ii-1) ii -= 1 self._possible_formats.pop(ii) def _create_formatting_template(self, num_format): number_pattern = num_format.pattern self.formatting_template = U_EMPTY_STRING temp_template = self._get_formatting_template(number_pattern, num_format.format) if len(temp_template) > 0: self._formatting_template = temp_template return True return False def _get_formatting_template(self, number_pattern, number_format): """Gets a formatting template which can be used to efficiently format a partial number where digits are added one by one.""" # Create a phone number consisting only of the digit 9 that matches the # number_pattern by applying the pattern to the longest_phone_number string. longest_phone_number = unicod("999999999999999") number_re = re.compile(number_pattern) m = number_re.search(longest_phone_number) # this will always succeed a_phone_number = m.group(0) # No formatting template can be created if the number of digits # entered so far is longer than the maximum the current formatting # rule can accommodate. if len(a_phone_number) < len(self._national_number): return U_EMPTY_STRING # Formats the number according to number_format template = re.sub(number_pattern, number_format, a_phone_number) # Replaces each digit with character _DIGIT_PLACEHOLDER template = re.sub("9", _DIGIT_PLACEHOLDER, template) return template def _clear(self): """Clears the internal state of the formatter, so it can be reused.""" self._current_output = U_EMPTY_STRING self._accrued_input = U_EMPTY_STRING self._accrued_input_without_formatting = U_EMPTY_STRING self._formatting_template = U_EMPTY_STRING self._last_match_position = 0 # The pattern from number_format that is currently used to create # formatting_template. self._current_formatting_pattern = U_EMPTY_STRING # This contains anything that has been entered so far preceding the # national significant number, and it is formatted (e.g. with space # inserted). For example, this can contain IDD, country code, and/or # NDD, etc. self._prefix_before_national_number = U_EMPTY_STRING self._should_add_space_after_national_prefix = False # This contains the national prefix that has been extracted. It # contains only digits without formatting. self._extracted_national_prefix = U_EMPTY_STRING self._national_number = U_EMPTY_STRING # This indicates whether AsYouTypeFormatter is currently doing the # formatting. self._able_to_format = True # Set to true when users enter their own # formatting. AsYouTypeFormatter will do no formatting at all when # this is set to True. self._input_has_formatting = False # The position of a digit upon which input_digit(remember_position=True) is # most recently invoked, as found in accrued_input_without_formatting. self._position_to_remember = 0 # The position of a digit upon which input_digit(remember_position=True) is # most recently invoked, as found in the original sequence of # characters the user entered. self._original_position = 0 # This is set to true when we know the user is entering a full # national significant number, since we have either detected a # national prefix or an international dialing prefix. When this is # true, we will no longer use local number formatting patterns. self._is_complete_number = False self._is_expecting_country_calling_code = False self._possible_formats = [] def clear(self): """Clears the internal state of the formatter, so it can be reused.""" self._clear() if self._current_metadata != self._default_metadata: self._current_metadata = _get_metadata_for_region(self._default_country) def input_digit(self, next_char, remember_position=False): """Formats a phone number on-the-fly as each digit is entered. If remember_position is set, remembers the position where next_char is inserted, so that it can be retrieved later by using get_remembered_position. The remembered position will be automatically adjusted if additional formatting characters are later inserted/removed in front of next_char. Arguments: next_char -- The most recently entered digit of a phone number. Formatting characters are allowed, but as soon as they are encountered this method formats the number as entered and not "as you type" anymore. Full width digits and Arabic-indic digits are allowed, and will be shown as they are. remember_position -- Whether to track the position where next_char is inserted. Returns the partially formatted phone number. """ self._accrued_input += next_char if remember_position: self._original_position = len(self._accrued_input) # We do formatting on-the-fly only when each character entered is # either a digit, or a plus sign (accepted at the start of the number # only). if not self._is_digit_or_leading_plus_sign(next_char): self._able_to_format = False self._input_has_formatting = True else: next_char = self._normalize_and_accrue_digits_and_plus_sign(next_char, remember_position) if not self._able_to_format: # When we are unable to format because of reasons other than that # formatting chars have been entered, it can be due to really long # IDDs or NDDs. If that is the case, we might be able to do # formatting again after extracting them. if self._input_has_formatting: self._current_output = self._accrued_input return self._current_output elif self._attempt_to_extract_idd(): if self._attempt_to_extract_ccc(): self._current_output = self._attempt_to_choose_pattern_with_prefix_extracted() return self._current_output elif self._able_to_extract_longer_ndd(): # Add an additional space to separate long NDD and national # significant number for readability. We don't set # should_add_space_after_national_prefix to True, since we don't # want this to change later when we choose formatting # templates. self._prefix_before_national_number += _SEPARATOR_BEFORE_NATIONAL_NUMBER self._current_output = self._attempt_to_choose_pattern_with_prefix_extracted() return self._current_output self._current_output = self._accrued_input return self._current_output # We start to attempt to format only when at least # MIN_LEADING_DIGITS_LENGTH digits (the plus sign is counted as a # digit as well for this purpose) have been entered. len_input = len(self._accrued_input_without_formatting) if len_input >= 0 and len_input <= 2: self._current_output = self._accrued_input return self._current_output elif len_input == 3: if self._attempt_to_extract_idd(): self._is_expecting_country_calling_code = True else: # No IDD or plus sign is found, might be entering in national format. self._extracted_national_prefix = self._remove_national_prefix_from_national_number() self._current_output = self._attempt_to_choose_formatting_pattern() return self._current_output if self._is_expecting_country_calling_code: if self._attempt_to_extract_ccc(): self._is_expecting_country_calling_code = False self._current_output = self._prefix_before_national_number + self._national_number return self._current_output if len(self._possible_formats) > 0: # The formatting patterns are already chosen. temp_national_number = self._input_digit_helper(next_char) # See if the accrued digits can be formatted properly already. If # not, use the results from input_digit_helper, which does # formatting based on the formatting pattern chosen. formatted_number = self._attempt_to_format_accrued_digits() if len(formatted_number) > 0: self._current_output = formatted_number return self._current_output self._narrow_down_possible_formats(self._national_number) if self._maybe_create_new_template(): self._current_output = self._input_accrued_national_number() return self._current_output if self._able_to_format: self._current_output = self._append_national_number(temp_national_number) return self._current_output else: self._current_output = self._accrued_input return self._current_output else: self._current_output = self._attempt_to_choose_formatting_pattern() return self._current_output def _attempt_to_choose_pattern_with_prefix_extracted(self): self._able_to_format = True self._is_expecting_country_calling_code = False self._possible_formats = [] self._last_match_position = 0 self._formatting_template = U_EMPTY_STRING self._current_formatting_pattern = U_EMPTY_STRING return self._attempt_to_choose_formatting_pattern() # Some national prefixes are a substring of others. If extracting the # shorter NDD doesn't result in a number we can format, we try to see if # we can extract a longer version here. def _able_to_extract_longer_ndd(self): if len(self._extracted_national_prefix) > 0: # Put the extracted NDD back to the national number before # attempting to extract a new NDD. self._national_number = self._extracted_national_prefix + self._national_number # Remove the previously extracted NDD from # prefixBeforeNationalNumber. We cannot simply set it to empty # string because people sometimes incorrectly enter national # prefix after the country code, e.g. +44 (0)20-1234-5678. index_of_previous_ndd = self._prefix_before_national_number.rfind(self._extracted_national_prefix) self._prefix_before_national_number = self._prefix_before_national_number[:index_of_previous_ndd] return self._extracted_national_prefix != self._remove_national_prefix_from_national_number() def _is_digit_or_leading_plus_sign(self, next_char): return (next_char.isdigit() or (len(self._accrued_input) == 1 and fullmatch(_PLUS_CHARS_PATTERN, next_char))) def _attempt_to_format_accrued_digits(self): """Checks to see if there is an exact pattern match for these digits. If so, we should use this instead of any other formatting template whose leadingDigitsPattern also matches the input. """ for number_format in self._possible_formats: num_re = re.compile(number_format.pattern) if fullmatch(num_re, self._national_number): if number_format.national_prefix_formatting_rule is None: self._should_add_space_after_national_prefix = False else: self._should_add_space_after_national_prefix = bool(_NATIONAL_PREFIX_SEPARATORS_PATTERN.search(number_format.national_prefix_formatting_rule)) formatted_number = re.sub(num_re, number_format.format, self._national_number) # Check that we did not remove nor add any extra digits when we matched # this formatting pattern. This usually happens after we entered the last # digit during AYTF. Eg: In case of MX, we swallow mobile token (1) when # formatted but AYTF should retain all the number entered and not change # in order to match a format (of same leading digits and length) display # in that way. full_output = self._append_national_number(formatted_number) formatted_number_digits_only = normalize_diallable_chars_only(full_output) if formatted_number_digits_only == self._accrued_input_without_formatting: # If it's the same (i.e entered number and format is same), then it's # safe to return this in formatted number as nothing is lost / added. return full_output return U_EMPTY_STRING def get_remembered_position(self): """Returns the current position in the partially formatted phone number of the character which was previously passed in as the parameter of input_digit(remember_position=True).""" if not self._able_to_format: return self._original_position accrued_input_index = 0 current_output_index = 0 while (accrued_input_index < self._position_to_remember and current_output_index < len(self._current_output)): if (self._accrued_input_without_formatting[accrued_input_index] == self._current_output[current_output_index]): accrued_input_index += 1 current_output_index += 1 return current_output_index def _append_national_number(self, national_number): """Combines the national number with any prefix (IDD/+ and country code or national prefix) that was collected. A space will be inserted between them if the current formatting template indicates this to be suitable. """ prefix_before_nn_len = len(self._prefix_before_national_number) if (self._should_add_space_after_national_prefix and prefix_before_nn_len > 0 and self._prefix_before_national_number[-1] != _SEPARATOR_BEFORE_NATIONAL_NUMBER): # We want to add a space after the national prefix if the national # prefix formatting rule indicates that this would normally be # done, with the exception of the case where we already appended a # space because the NDD was surprisingly long. return self._prefix_before_national_number + _SEPARATOR_BEFORE_NATIONAL_NUMBER + national_number else: return self._prefix_before_national_number + national_number def _attempt_to_choose_formatting_pattern(self): """Attempts to set the formatting template and returns a string which contains the formatted version of the digits entered so far.""" # We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national # number (excluding national prefix) have been entered. if len(self._national_number) >= _MIN_LEADING_DIGITS_LENGTH: self._get_available_formats(self._national_number) # See if the accrued digits can be formatted properly already. formatted_number = self._attempt_to_format_accrued_digits() if len(formatted_number) > 0: return formatted_number if self._maybe_create_new_template(): return self._input_accrued_national_number() else: return self._accrued_input else: return self._append_national_number(self._national_number) def _input_accrued_national_number(self): """Invokes input_digit_helper on each digit of the national number accrued, and returns a formatted string in the end.""" length_of_national_number = len(self._national_number) if length_of_national_number > 0: temp_national_number = U_EMPTY_STRING for ii in range(length_of_national_number): temp_national_number = self._input_digit_helper(self._national_number[ii]) if self._able_to_format: return self._append_national_number(temp_national_number) else: return self._accrued_input else: return self._prefix_before_national_number def _is_nanpa_number_with_national_prefix(self): """Returns true if the current country is a NANPA country and the national number begins with the national prefix. """ # For NANPA numbers beginning with 1[2-9], treat the 1 as the national # prefix. The reason is that national significant numbers in NANPA # always start with [2-9] after the national prefix. Numbers # beginning with 1[01] can only be short/emergency numbers, which # don't need the national prefix. return (self._current_metadata.country_code == 1 and self._national_number[0] == '1' and self._national_number[1] != '0' and self._national_number[1] != '1') def _remove_national_prefix_from_national_number(self): start_of_national_number = 0 if self._is_nanpa_number_with_national_prefix(): start_of_national_number = 1 self._prefix_before_national_number += unicod("1") + _SEPARATOR_BEFORE_NATIONAL_NUMBER self._is_complete_number = True elif self._current_metadata.national_prefix_for_parsing is not None: npp_re = re.compile(self._current_metadata.national_prefix_for_parsing) m = npp_re.match(self._national_number) # Since some national prefix patterns are entirely optional, check # that a national prefix could actually be extracted. if m and m.end() > 0: # When the national prefix is detected, we use international # formatting rules instead of national ones, because national # formatting rules could contain local formatting rules for # numbers entered without area code. self._is_complete_number = True start_of_national_number = m.end() self._prefix_before_national_number += self._national_number[:start_of_national_number] national_prefix = self._national_number[:start_of_national_number] self._national_number = self._national_number[start_of_national_number:] return national_prefix def _attempt_to_extract_idd(self): """Extracts IDD and plus sign to self._prefix_before_national_number when they are available, and places the remaining input into _national_number. Returns True when accrued_input_without_formatting begins with the plus sign or valid IDD for default_country. """ international_prefix = re.compile(unicod("\\") + _PLUS_SIGN + unicod("|") + (self._current_metadata.international_prefix or U_EMPTY_STRING)) idd_match = international_prefix.match(self._accrued_input_without_formatting) if idd_match: self._is_complete_number = True start_of_country_calling_code = idd_match.end() self._national_number = self._accrued_input_without_formatting[start_of_country_calling_code:] self._prefix_before_national_number = self._accrued_input_without_formatting[:start_of_country_calling_code] if self._accrued_input_without_formatting[0] != _PLUS_SIGN: self._prefix_before_national_number += _SEPARATOR_BEFORE_NATIONAL_NUMBER return True return False def _attempt_to_extract_ccc(self): """Extracts the country calling code from the beginning of _national_number to _prefix_before_national_number when they are available, and places the remaining input into _national_number. Returns True when a valid country calling code can be found. """ if len(self._national_number) == 0: return False country_code, number_without_ccc = _extract_country_code(self._national_number) if country_code == 0: return False self._national_number = number_without_ccc new_region_code = region_code_for_country_code(country_code) if new_region_code == REGION_CODE_FOR_NON_GEO_ENTITY: self._current_metadata = PhoneMetadata.metadata_for_nongeo_region(country_code) elif new_region_code != self._default_country: self._current_metadata = _get_metadata_for_region(new_region_code) self._prefix_before_national_number += str(country_code) self._prefix_before_national_number += _SEPARATOR_BEFORE_NATIONAL_NUMBER # When we have successfully extracted the IDD, the previously # extracted NDD should be cleared because it is no longer valid. self._extracted_national_prefix = U_EMPTY_STRING return True def _normalize_and_accrue_digits_and_plus_sign(self, next_char, remember_position): """Accrues digits and the plus sign to _accrued_input_without_formatting for later use. If next_char contains a digit in non-ASCII format (e.g. the full-width version of digits), it is first normalized to the ASCII version. The return value is next_char itself, or its normalized version, if next_char is a digit in non-ASCII format. This method assumes its input is either a digit or the plus sign.""" if next_char == _PLUS_SIGN: normalized_char = next_char self._accrued_input_without_formatting += next_char else: next_digit = unicode_digit(next_char, -1) if next_digit != -1: normalized_char = unicod(next_digit) else: # pragma no cover normalized_char = next_char self._accrued_input_without_formatting += normalized_char self._national_number += normalized_char if remember_position: self._position_to_remember = len(self._accrued_input_without_formatting) return normalized_char def _input_digit_helper(self, next_char): # Note that formattingTemplate is not guaranteed to have a value, it # could be empty, e.g. when the next digit is entered after extracting # an IDD or NDD. digit_match = _DIGIT_PATTERN.search(self._formatting_template, self._last_match_position) if digit_match: # Reset to search for _DIGIT_PLACEHOLDER from start of string digit_match = _DIGIT_PATTERN.search(self._formatting_template) temp_template = re.sub(_DIGIT_PATTERN, next_char, self._formatting_template, count=1) self._formatting_template = temp_template + self._formatting_template[len(temp_template):] self._last_match_position = digit_match.start() return self._formatting_template[:self._last_match_position + 1] else: if len(self._possible_formats) == 1: # More digits are entered than we could handle, and there are # no other valid patterns to try. self._able_to_format = False # else, we just reset the formatting pattern. self._current_formatting_pattern = U_EMPTY_STRING return self._accrued_input
{ "repo_name": "daviddrysdale/python-phonenumbers", "path": "python/phonenumbers/asyoutypeformatter.py", "copies": "1", "size": "32841", "license": "apache-2.0", "hash": 2719993812631465500, "line_mean": 53.1930693069, "line_max": 162, "alpha_frac": 0.6474224293, "autogenerated": false, "ratio": 4.276171875, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0015074839829167619, "num_lines": 606 }
"""A Fortran 90 namelist parser and generator. :copyright: Copyright 2014 Marshall Ward, see AUTHORS for details. :license: Apache License, Version 2.0, see LICENSE for details. """ from f90nml.namelist import Namelist from f90nml.parser import Parser __version__ = '1.3.1' def read(nml_path): """Parse a Fortran namelist file and return its contents. File object usage: >>> with open(nml_path) as nml_file: >>> nml = f90nml.read(nml_file) File path usage: >>> nml = f90nml.read(nml_path) This function is equivalent to the ``read`` function of the ``Parser`` object. >>> parser = f90nml.Parser() >>> nml = parser.read(nml_file) """ parser = Parser() return parser.read(nml_path) def reads(nml_string): """Parse a Fortran namelist string and return its contents. >>> nml_str = '&data_nml x=1 y=2 /' >>> nml = f90nml.reads(nml_str) This function is equivalent to the ``reads`` function of the ``Parser`` object. >>> parser = f90nml.Parser() >>> nml = parser.reads(nml_str) """ parser = Parser() return parser.reads(nml_string) def write(nml, nml_path, force=False, sort=False): """Save a namelist to disk using either a file object or its file path. File object usage: >>> with open(nml_path, 'w') as nml_file: >>> f90nml.write(nml, nml_file) File path usage: >>> f90nml.write(nml, 'data.nml') This function is equivalent to the ``write`` function of the ``Namelist`` object ``nml``. >>> nml.write('data.nml') By default, ``write`` will not overwrite an existing file. To override this, use the ``force`` flag. >>> nml.write('data.nml', force=True) To alphabetically sort the ``Namelist`` keys, use the ``sort`` flag. >>> nml.write('data.nml', sort=True) """ # Promote dicts to Namelists if not isinstance(nml, Namelist) and isinstance(nml, dict): nml_in = Namelist(nml) else: nml_in = nml nml_in.write(nml_path, force=force, sort=sort) def patch(nml_path, nml_patch, out_path=None): """Create a new namelist based on an input namelist and reference dict. >>> f90nml.patch('data.nml', nml_patch, 'patched_data.nml') This function is equivalent to the ``read`` function of the ``Parser`` object with the patch output arguments. >>> parser = f90nml.Parser() >>> nml = parser.read('data.nml', nml_patch, 'patched_data.nml') A patched namelist file will retain any formatting or comments from the original namelist file. Any modified values will be formatted based on the settings of the ``Namelist`` object. """ parser = Parser() return parser.read(nml_path, nml_patch, out_path)
{ "repo_name": "marshallward/f90nml", "path": "f90nml/__init__.py", "copies": "1", "size": "2753", "license": "apache-2.0", "hash": 7832349143007193000, "line_mean": 25.9901960784, "line_max": 79, "alpha_frac": 0.6418452597, "autogenerated": false, "ratio": 3.3329297820823243, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9474775041782324, "avg_score": 0, "num_lines": 102 }
""" A Fortran code analyzer and linter. """ from argparse import ArgumentParser from collections import defaultdict, namedtuple from . import alphanumeric, letter, digit, one_of, whitespace, none_of from . import Failure, succeed, matches, spaces, wildcard from . import join, exact, liberal, satisfies, singleton, EOF, parser, concat def inexact(string): """ Ignore case. """ return exact(string, ignore_case=True) def keyword(string): """ Match a case-insensitive keyword. """ return liberal(inexact(string)) def sum_parsers(parsers): """ Construct a sequential parser from a list of parsers. """ result = succeed("") for this in parsers: result = result + this return result class Token(object): """ Classification of tokens. """ def __init__(self, tag, value): self.value = value self.tag = tag def __repr__(self): return self.tag + "{" + self.value + "}" def tag_token(tag): """ Returns a function that wraps a value with the specified `tag`. """ def inner(value): """ The function that applies the `tag`. """ return Token(tag, value) return inner def name_tokens(list_of_tokens): """ Only select the tokens that have the tag 'name'. """ return [token.value.lower() for token in list_of_tokens if token.tag == 'name'] class Grammar(object): """ Grammar specification of Fortran 77. """ #: position of column where the continuation mark should be continuation_column = 5 #: starting column for code margin_column = continuation_column + 1 #: classification of statements statements = {} statements["control nonblock"] = [['go', 'to'], ['call'], ['return'], ['continue'], ['stop'], ['pause']] statements["control block"] = [['if'], ['else', 'if'], ['else'], ['end', 'if'], ['do'], ['end', 'do']] statements["control"] = (statements["control block"] + statements["control nonblock"]) statements["io"] = [['read'], ['write'], ['print'], ['rewind'], ['backspace'], ['endfile'], ['open'], ['close'], ['inquire']] statements["assign"] = [['assign']] statements["executable"] = (statements["control"] + statements["assign"] + statements["io"]) statements["type"] = [['integer'], ['real'], ['double', 'precision'], ['complex'], ['logical'], ['character']] statements["specification"] = (statements["type"] + [['dimension'], ['common'], ['equivalence'], ['implicit'], ['parameter'], ['external'], ['intrinsic'], ['save']]) statements["top level"] = [['program'], ['end', 'program'], ['function'], ['end', 'function'], ['subroutine'], ['end', 'subroutine'], ['block', 'data'], ['end', 'block', 'data'], ['end']] statements["misc nonexec"] = [['entry'], ['data'], ['format']] statements["non-executable"] = (statements["specification"] + statements["misc nonexec"] + statements["top level"]) # order is important here # because 'end' should come before 'end if' et cetera statements["all"] = (statements["executable"] + statements["non-executable"]) #: intrinsic functions intrinsics = ['abs', 'acos', 'aimag', 'aint', 'alog', 'alog10', 'amax10', 'amax0', 'amax1', 'amin0', 'amin1', 'amod', 'anint', 'asin', 'atan', 'atan2', 'cabs', 'ccos', 'char', 'clog', 'cmplx', 'conjg', 'cos', 'cosh', 'csin', 'csqrt', 'dabs', 'dacos', 'dasin', 'datan', 'datan2', 'dble', 'dcos', 'dcosh', 'ddim', 'dexp', 'dim', 'dint', 'dint', 'dlog', 'dlog10', 'dmax1', 'dmin1', 'dmod', 'dnint', 'dprod', 'dreal', 'dsign', 'dsin', 'dsinh', 'dsqrt', 'dtan', 'dtanh', 'exp', 'float', 'iabs', 'ichar', 'idim', 'idint', 'idnint', 'iflx', 'index', 'int', 'isign', 'len', 'lge', 'lgt', 'lle', 'llt', 'log', 'log10', 'max', 'max0', 'max1', 'min', 'min0', 'min1', 'mod', 'nint', 'real', 'sign', 'sin', 'sinh', 'sngl', 'sqrt', 'tan', 'tanh', 'matmul', 'cycle'] #: one word term = inexact #: valid Fortran identifier name = letter + alphanumeric.many() // join #: statement label label = digit.between(1, 5) // join #: integer literal integer = (one_of("+-").optional() + +digit) // join #: logical literal logical = term(".true.") | term(".false.") #: character literal segment char_segment = ((term('"') + none_of('"').many() // join + term('"')) | (term("'") + none_of("'").many() // join + term("'"))) #: character literal (string) character = (+char_segment) // join #: basic real number basic_real = (one_of("+-").optional() + +digit + exact(".") // singleton + digit.many()) // join #: single precision exponent part single_exponent = one_of("eE") + integer #: single precision real single = ((basic_real + single_exponent.optional() // join) | (integer + single_exponent)) #: double precision exponent part double_exponent = one_of("dD") + integer #: double precision real double = (basic_real | integer) + double_exponent #: real number literal real = double | single #: comment line comment = exact("!") + none_of("\n").many() // join #: arithmetic operators equals, plus, minus, times, slash = [exact(c) for c in "=+-*/"] #: comparison operators lt_, le_, eq_, ne_, gt_, ge_ = [term(c) for c in ['.lt.', '.le.', '.eq.', '.ne.', '.gt.', '.ge.']] #: logical operators not_, and_, or_ = [term(c) for c in ['.not.', '.and.', '.or.']] #: more logical operators eqv, neqv = [term(c) for c in ['.eqv.', '.neqv.']] lparen, rparen, dot, comma, dollar = [exact(c) for c in "().,$"] apostrophe, quote, colon, langle, rangle = [exact(c) for c in "'\":<>"] #: exponentiation operator exponent = exact("**") #: string concatenation operator concatenation = exact("//") #: one single token single_token = (character // tag_token("character") | comment // tag_token("comment") | logical // tag_token("logical") | lt_ // tag_token("lt") | le_ // tag_token("le") | eq_ // tag_token("eq") | ne_ // tag_token("ne") | gt_ // tag_token("gt") | ge_ // tag_token("ge") | not_ // tag_token("not") | and_ // tag_token("and") | or_ // tag_token("or") | eqv // tag_token("eqv") | neqv // tag_token("neqv") | real // tag_token("real") | integer // tag_token("integer") | name // tag_token("name") | equals // tag_token("equals") | plus // tag_token("plus") | minus // tag_token("minus") | exponent // tag_token("exponent") | times // tag_token("times") | concatenation // tag_token("concat") | slash // tag_token("slash") | lparen // tag_token("lparen") | rparen // tag_token("rparen") | dot // tag_token("dot") | comma // tag_token("comma") | dollar // tag_token("dollar") | apostrophe // tag_token("apostrophe") | quote // tag_token("quote") | colon // tag_token("colon") | langle // tag_token("langle") | rangle // tag_token("rangle") | spaces // tag_token("whitespace") | wildcard // tag_token("unknown")) #: list of tokens tokenizer = (single_token).many() def outer_block(statement): """ Returns a function that marks a block with `statement`. """ def inner(children): """ Wraps `children` in an :class:`OuterBlock` marked as `statement`. """ return OuterBlock(children, statement) return inner class OuterBlock(object): """ Represents a block. Its children are inner blocks. """ def __init__(self, children, statement): self.children = children self.statement = statement def accept(self, visitor): """ Accept a visitor by invoking its outer block processing function. """ return visitor.outer_block(self) def __repr__(self): return print_details(self) def __str__(self): return plain(self) def inner_block(logical_lines): """ Wraps a collection of logical lines into an :class:`InnerBlock`. """ return InnerBlock(logical_lines) class InnerBlock(object): """ Represents the statements inside a block. """ def __init__(self, logical_lines): statements = Grammar.statements @parser def if_block(text, start): """ Process an ``if`` block or statement. """ def new_style_if(list_of_lines): """ An ``if`` statement accompanied by a ``then`` keyword. """ then = [token for token in name_tokens(list_of_lines.tokens_after) if token == 'then'] return len(then) > 0 if_statement = one_of_types([["if"]]) else_if_statement = one_of_types([["else", "if"]]) else_statement = one_of_types([["else"]]) end_if_statement = one_of_types([["end", "if"]]) begin = (if_statement.guard(new_style_if, "new style if") // singleton) inner = (non_block | do_block | if_block | none_of_types([["end", "if"], ["else", "if"], ["else"]])) else_or_else_if = else_if_statement | else_statement def inner_block_or_empty(list_of_lines): """ Wraps a list of lines in an :class:`InnerBlock` if not already empty. """ if list_of_lines != []: return [inner_block(list_of_lines)] else: return [] section = ((inner.many() // inner_block_or_empty) + else_or_else_if.optional()).guard(lambda l: l != [], "anything") sections = section.many() // concat end = (end_if_statement // singleton) result = (((begin + sections + end) // outer_block("if_block")) .scan(text, start)) return result @parser def do_block(text, start): """ Process a ``do`` block. """ def new_style_do(list_of_lines): """ A proper ``do`` block with ``end do``. """ return not matches(keyword("do") + liberal(Grammar.label), list_of_lines.code.lower()) do_statement = one_of_types([["do"]]) end_do_statement = one_of_types([["end", "do"]]) begin = (do_statement.guard(new_style_do, "new style do") // singleton) inner = ((non_block | do_block | if_block | none_of_types([["end", "do"]])) .many() // inner_block // singleton) end = end_do_statement // singleton return (((begin + inner + end) // outer_block("do_block")) .scan(text, start)) non_block = one_of_types(statements["io"] + statements["assign"] + statements["specification"] + statements["misc nonexec"] + statements["control nonblock"]) block_or_line = non_block | do_block | if_block | wildcard self.children = block_or_line.many().parse(logical_lines) def accept(self, visitor): """ Accept a visitor by invoking its inner block processing function. """ return visitor.inner_block(self) def __repr__(self): return print_details(self) def __str__(self): return plain(self) class RawLine(object): """ Represents a line in the source code. Classifies whether the line is a comment, an initial or a continuation line. """ def __init__(self, line): self.original = line continuation_column = Grammar.continuation_column margin_column = Grammar.margin_column lowered = line.rstrip().lower() if matches(EOF | one_of("*c") | keyword("!"), lowered): self.type = "comment" return self.code = line[margin_column:] self.tokens = Grammar.tokenizer.parse(self.code) self.tokens_after = self.tokens if len(lowered) > continuation_column: if matches(none_of("0 "), lowered, continuation_column): self.type = "continuation" assert len(lowered[:continuation_column].strip()) == 0 self.cont = line[continuation_column:margin_column] return self.type = "initial" # extract the statement label if applicable statement_label = lowered[:continuation_column] if len(statement_label.strip()) > 0: self.label = (liberal(Grammar.label) // int).parse(statement_label) def check(words): """ See if the words match any known (sequence of) keywords. """ msg = succeed(" ".join(words)) parser_sum = sum_parsers([keyword(w) for w in words]) try: success = (parser_sum >> msg).scan(self.code) tokenizer = Grammar.tokenizer self.statement = success.value self.tokens_after = tokenizer.parse(self.code, success.end) # seems like a have a complete match raise StopIteration() except Failure: pass try: for words in Grammar.statements["all"]: check(words) except StopIteration: return self.statement = 'assignment' def accept(self, visitor): """ Accept a visitor by invoking its raw line processing function. """ return visitor.raw_line(self) def __repr__(self): return print_details(self) def __str__(self): return plain(self) class LogicalLine(object): """ Represents a logical line. Continuation lines are merged. """ def __init__(self, children): initial_line = [l for l in children if l.type == 'initial'] assert len(initial_line) == 1 initial_line = initial_line[0] self.children = children self.statement = initial_line.statement try: self.label = initial_line.label except AttributeError: pass code_lines = [l for l in children if l.type != 'comment'] self.code = "\n".join([l.code for l in code_lines]) self.tokens = concat([l.tokens for l in code_lines]) self.tokens_after = concat([l.tokens_after for l in code_lines]) def accept(self, visitor): """ Accept a visitor by invoking its logical line processing function. """ return visitor.logical_line(self) def __repr__(self): return print_details(self) def __str__(self): return plain(self) def parse_into_logical_lines(lines): """ Groups a set of raw lines into logical lines. """ def of_type(type_name): """ A parser that recognizes only a specific kind of raw line. """ return satisfies(lambda l: l.type == type_name, type_name) comment, continuation, initial = (of_type(t) for t in ['comment', 'continuation', 'initial']) logical_line = (comment.many() + initial // singleton + (comment | continuation).many()) // LogicalLine return logical_line.many().parse(lines) def parse_source(logical_lines): """ Organizes a list of logical lines into blocks. """ statements = Grammar.statements def top_level_block(kind, first_line_optional=False): """ Parses a top level block: the main program, a function, a subroutine or a block data. """ if first_line_optional: first_line = one_of_types([kind]).optional() else: first_line = one_of_types([kind]) // singleton mid_lines = (none_of_types(statements["top level"]).many() // inner_block // singleton) last_line = one_of_types([["end"] + kind, ["end"]]) // singleton block_statement = "_".join(kind + ["block"]) return ((first_line + mid_lines + last_line) // outer_block(block_statement)) function, subroutine, block_data = [top_level_block(kind) for kind in [["function"], ["subroutine"], ["block", "data"]]] subprogram = function | subroutine | block_data main_program = top_level_block(["program"], True) program_unit = subprogram | main_program return (+program_unit // outer_block("source_file")).parse(logical_lines) def one_of_list(names): """ Readable representation of a list of alternatives. """ if len(names) == 0: return "nothing" if len(names) == 1: return " ".join(names[0]) if len(names) == 2: return " ".join(names[0]) + " or " + " ".join(names[1]) proper_names = [" ".join(name) for name in names] return "one of " + ", ".join(proper_names) + " or " + " ".join(names[-1]) def one_of_types(names): """ Whether the statement belongs to any one of the given types. """ return satisfies(lambda l: l.statement in [" ".join(name) for name in names], one_of_list(names)) def none_of_types(names): """ Whether the statement belongs to none of the given types. """ return satisfies(lambda l: l.statement not in [" ".join(name) for name in names], one_of_list(names)) def remove_blanks(raw_lines): """ Removes empty lines from a list of :class:`RawLine` objects. """ empty = satisfies(lambda l: matches(whitespace << EOF, l.original), "empty line") remove = (+empty // (lambda ls: RawLine("\n")) | wildcard).many() return str((remove // outer_block("source")).parse(raw_lines)) def new_comments(raw_lines): """ Converts old style comments to new style ones. """ def of_type(type_name): """ Whether the line is of some particular type. """ return satisfies(lambda l: l.type == type_name, type_name) def change_comment(line): """ Replace old comment characters with '!'. """ if matches(one_of("c*"), line.original): return RawLine("!" + line.original[1:]) else: return line upgrade = of_type("comment") // change_comment | wildcard return str((upgrade.many() // outer_block("source")).parse(raw_lines)) class Visitor(object): """ Template for implementors of the visitor pattern. The default implementation just returns the original source code. """ def raw_line(self, line): """ Process a raw line. """ return [line.original] def logical_line(self, line): """ Process a logical line with continuations taken into account. """ return concat([l.accept(self) for l in line.children]) def inner_block(self, block): """ Process the inside lines of a block. """ return concat([b.accept(self) for b in block.children]) def outer_block(self, block): """ Process lines including the bracketing ones for a block. """ return concat([b.accept(self) for b in block.children]) def top_level(self, block): """ Process the top most level of a source file. """ return "".join(block.accept(self)) def indent(doc, indent_width=4): """ Re-indent source code. """ margin_column = Grammar.margin_column class Indent(Visitor): """ Visitor implementation of re-indentation. """ def __init__(self): # current level of indentation self.current = 1 def raw_line(self, line): if line.type == 'comment': return [line.original] if line.type == 'continuation': tab = " " * (self.current + indent_width) else: tab = " " * self.current return [line.original[:margin_column] + tab + line.code.lstrip()] def inner_block(self, block): self.current += indent_width result = concat([b.accept(self) for b in block.children]) self.current -= indent_width return result return Indent().top_level(doc) def plain(doc): """ Basically no processing, just return the source code intact. """ return Visitor().top_level(doc) def remove_comments(doc): """ Remove comments from source code. """ class Remove(Visitor): """ Visitor implementation of comment removal. """ def raw_line(self, line): if line.type == 'comment': return [] else: return [line.original] return Remove().top_level(doc) def print_details(doc): """ Print details of the parse tree for easy inspection. """ class Details(Visitor): """ Visitor implementation of details. """ def __init__(self): self.level = 0 self.statement = None def raw_line(self, line): if line.type == "comment": return [] elif line.type == "continuation": self.level += 1 result = ["||| " * self.level + self.statement + " continued: " + line.code.lstrip()] self.level -= 1 return result elif line.type == "initial": try: info = "{}[{}]: ".format(line.statement, line.label) except AttributeError: info = "{}: ".format(line.statement) return ["||| " * self.level + info + line.code.lstrip()] def logical_line(self, line): self.statement = line.statement return concat([b.accept(self) for b in line.children]) def inner_block(self, block): self.level += 1 result = concat([b.accept(self) for b in block.children]) self.level -= 1 return result return Details().top_level(doc) def read_file(filename): """ Read the contents of a file and convert it to a list of :class:`RawLine` objects. """ with open(filename) as input_file: return [RawLine(line) for line in input_file] def parse_file(filename): """ Read the contents of a file and convert it to our internal representation of nested blocks. """ return parse_source(parse_into_logical_lines(read_file(filename))) def reconstruct(unit): """ Re-construct the source code from parsed representation. """ class Reconstruct(Visitor): """ Visitor implementation of the reconstruction. """ def raw_line(self, line): if line.type == 'comment': return [line.original] cont_col = Grammar.continuation_column marg_col = Grammar.margin_column if line.type == 'continuation': result = " " * cont_col + line.cont else: try: result = ("{:<" + str(marg_col) + "}").format(line.label) except AttributeError: result = " " * marg_col for token in line.tokens: result += token.value return [result] return Reconstruct().top_level(unit) def collect_unit_names(source): """ Return a collection of the defined names in the source code. """ unit_names = [] for unit in source.children: assert isinstance(unit, OuterBlock) first = unit.children[0] if isinstance(first, LogicalLine): unit_names.append(mentioned_names(first)[0]) return unit_names def analyze(source): """ Analyze the source code and spit out detailed information about it. """ unit_names = collect_unit_names(source) print 'line numbers refer to the line number within the program unit' print 'not counting blank lines' print print 'found program units:', unit_names print for unit in source.children: analyze_unit(unit, unit_names) def mentioned_names(line): """ The defined names that have been actually used in the program. """ return [token for token in name_tokens(line.tokens_after)] def analyze_header(unit): """ Extract information about the formal parameters of a top-level block. """ first = unit.children[0] if isinstance(first, LogicalLine): statement = first.statement tokens = [token for token in first.tokens_after if token.tag != 'whitespace' and token.tag != 'comment'] assert len(tokens) > 0 assert tokens[0].tag == 'name', "got {}".format(tokens[0].tag) program_name = tokens[0].value formal_params = name_tokens(tokens[1:]) assert len(unit.children) == 3 main_block = unit.children[1] else: statement = "program" program_name = None formal_params = [] assert len(unit.children) == 2 main_block = unit.children[0] return statement, program_name, formal_params, main_block Interval = namedtuple('Interval', ['var', 'start', 'end']) def make_timeline(occur_dict): """ Create a timeline from the occurrence information for the variables. """ occur_list = [Interval(var, occur_dict[var][0], occur_dict[var][-1]) for var in occur_dict if occur_dict[var] != []] return sorted(occur_list, key=lambda x: x.start) def draw_timeline(occur_list, last_line, graph_cols=60): """ ASCII rendering of timeline information. """ def graph_pos(lineno): """ Where in the timeline `lineno` should be. """ return int(round((float(lineno) / last_line) * graph_cols)) graph_list = [Interval(d.var, graph_pos(d.start), graph_pos(d.end)) for d in occur_list] for period in graph_list: print "{:10s}|{}{}{}|".format(str(period.var), " " * period.start, "=" * (period.end - period.start + 1), " " * (graph_cols - period.end)) print def analyze_labels(main_block): """ Analyze label information. """ class Label(Visitor): """ Visitor implemention of collection of labels. """ def __init__(self): self.current_line = 0 def logical_line(self, line): self.current_line += 1 try: if line.statement != 'format': return [(self.current_line, line.label)] except AttributeError: pass return [] labels = main_block.accept(Label()) if labels: print "labels:", [lbl for _, lbl in labels] print occur_dict = defaultdict(list) last_line = [0] for decl_line, lbl in labels: class Occurrences(Visitor): """ Visitor implementation of occurrence check for labels. """ def __init__(self): self.current_line = 0 def logical_line(self, line): self.current_line += 1 last_line[0] = self.current_line int_tokens = [int(token.value) for token in line.tokens_after if token.tag == 'integer'] if lbl in int_tokens: occur_dict[lbl].append(self.current_line) return [] main_block.accept(Occurrences()) for decl_line, lbl in labels: print lbl, 'defined at: ' + str(decl_line), print 'occurred at: ', occur_dict[lbl] occur_dict[lbl] = sorted(occur_dict[lbl] + [decl_line]) print draw_timeline(make_timeline(occur_dict), last_line[0]) def analyze_variables(unit_names, formal_params, main_block): """ Analyze variable usage information. """ class Variables(Visitor): """ Collect mentions of variable names. """ def logical_line(self, line): if line.statement == 'format': return [] return mentioned_names(line) unique_names = list(set(main_block.accept(Variables()))) specs = [" ".join(s) for s in Grammar.statements["specification"]] class Locals(Visitor): """ Collect local variable declarations. """ def logical_line(self, line): if line.statement not in specs: return [] name_list = mentioned_names(line) if line.statement == 'implicit' and name_list == ['none']: return [] return name_list local_variables = list(set(main_block.accept(Locals()))) keywords = list(set(concat(Grammar.statements["all"]))) + ['then', 'none'] local_names = list(set(local_variables + formal_params)) unaccounted_for = list(set(unique_names) - set(local_names) - set(keywords) - set(Grammar.intrinsics) - set(unit_names)) if unaccounted_for: print 'unaccounted for:', unaccounted_for print concern = list(set(local_variables + formal_params + unaccounted_for)) occur_dict = defaultdict(list) last_line = [0] class Occurrences(Visitor): """ Collect occurrence information for variables. """ def __init__(self, var): self.current_line = 0 self.var = var def logical_line(self, line): self.current_line += 1 last_line[0] = self.current_line if line.statement not in specs: if self.var in name_tokens(line.tokens_after): occur_dict[self.var].append(self.current_line) return [] for var in concern: main_block.accept(Occurrences(var)) never_occur_list = sorted([var for var in concern if occur_dict[var] == []]) if never_occur_list: print 'never occurred:', never_occur_list print for var in occur_dict: print var, 'occurred at: ', occur_dict[var] draw_timeline(make_timeline(occur_dict), last_line[0]) def analyze_unit(unit, unit_names): """ Analyze a unit for labels and variables. """ statement, program_name, formal_params, main_block = analyze_header(unit) print statement, program_name, formal_params print analyze_labels(main_block) analyze_variables(unit_names, formal_params, main_block) def _argument_parser_(): arg_parser = ArgumentParser() task_list = ['remove-blanks', 'print-details', 'indent', 'new-comments', 'plain', 'analyze', 'reconstruct', 'remove-comments'] arg_parser.add_argument("task", choices=task_list, metavar="task", help="in {}".format(task_list)) arg_parser.add_argument("filename") return arg_parser def main(): """ The main entry point for the executable. Performs the task specified. Possible tasks are: - ``plain``: echo the source file lines back, basically a no-op - ``remove-comments``: remove all comments from source code - ``remove-blanks``: remove blank lines from source code - ``indent``: re-indent source code - ``print-details``: detailed information about the structure - ``new-comments``: convert old style comments to new (Fortran 90) style - ``reconstruct``: try and reconstruct the source code from the nested structure - ``analyze``: detailed analysis and linting of the code """ arg_parser = _argument_parser_() args = arg_parser.parse_args() raw_lines = read_file(args.filename) logical_lines = parse_into_logical_lines(read_file(args.filename)) parsed = parse_source(logical_lines) if args.task == 'plain': print plain(parsed), elif args.task == 'remove-comments': print remove_comments(parsed) elif args.task == 'remove-blanks': print remove_blanks(raw_lines), elif args.task == 'indent': print indent(parsed), elif args.task == 'print-details': print print_details(parsed), elif args.task == 'new-comments': print new_comments(raw_lines), elif args.task == 'reconstruct': print reconstruct(parsed), elif args.task == 'analyze': analyze(parsed) else: raise ValueError("invalid choice: {}".format(args.task)) if __name__ == '__main__': main()
{ "repo_name": "uchchwhash/fortran-linter", "path": "linter/fortran.py", "copies": "1", "size": "34439", "license": "mit", "hash": -8257785461827161000, "line_mean": 32.4359223301, "line_max": 79, "alpha_frac": 0.5311710561, "autogenerated": false, "ratio": 4.222017898737281, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5253188954837281, "avg_score": null, "num_lines": null }
"""AFOS Database Workflow.""" # 3rd Party from twisted.internet import reactor from txyam.client import YamClient from pyiem.util import LOG from pyiem.nws import product # Local from pywwa import common from pywwa.ldm import bridge from pywwa.database import get_database DBPOOL = get_database("afos", cp_max=5) MEMCACHE_EXCLUDE = [ "RR1", "RR2", "RR3", "RR4", "RR5", "RR6", "RR7", "RR8", "RR9", "ROB", "HML", ] MEMCACHE_CLIENT = YamClient(reactor, ["tcp:iem-memcached3:11211"]) MEMCACHE_CLIENT.connect() def process_data(data): """Process the product""" defer = DBPOOL.runInteraction(real_parser, data) defer.addCallback(write_memcache) defer.addErrback(common.email_error, data) defer.addErrback(LOG.error) def write_memcache(nws): """write our TextProduct to memcached""" if nws is None: return # 10 minutes should be enough time LOG.debug("writing %s to memcache", nws.get_product_id()) df = MEMCACHE_CLIENT.set( nws.get_product_id().encode("utf-8"), nws.unixtext.replace("\001\n", "").encode("utf-8"), expireTime=600, ) df.addErrback(LOG.error) def real_parser(txn, buf): """Actually do something with the buffer, please""" if buf.strip() == "": return None utcnow = common.utcnow() nws = product.TextProduct(buf, utcnow=utcnow, parse_segments=False) # When we are in realtime processing, do not consider old data, typically # when a WFO fails to update the date in their MND if (utcnow - nws.valid).days > 180 or (utcnow - nws.valid).days < -180: raise Exception(f"Very Latent Product! {nws.valid}") if nws.warnings: common.email_error("\n".join(nws.warnings), buf) if nws.afos is None: if nws.source[0] not in ["K", "P"]: return None raise Exception("TextProduct.afos is null") txn.execute( "INSERT into products (pil, data, entered, " "source, wmo) VALUES(%s, %s, %s, %s, %s)", (nws.afos.strip(), nws.text, nws.valid, nws.source, nws.wmo), ) if nws.afos[:3] in MEMCACHE_EXCLUDE: return None return nws def main(): """Fire up our workflow.""" common.main(with_jabber=False) bridge(process_data) reactor.run() # @UndefinedVariable # See how we are called. if __name__ == "__main__": main()
{ "repo_name": "akrherz/pyWWA", "path": "parsers/pywwa/workflows/afos_dump.py", "copies": "1", "size": "2394", "license": "mit", "hash": 8739327433401430000, "line_mean": 25.0217391304, "line_max": 77, "alpha_frac": 0.6282372598, "autogenerated": false, "ratio": 3.1835106382978724, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9311747898097873, "avg_score": 0, "num_lines": 92 }
"""A framework for developing enterprise level python applications See: https://github.com/velexio/pyLegos """ # Always prefer setuptools over distutils import setuptools from pylegos.core import ConfigManager from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path from ast import literal_eval here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() majorVer = '0.2' minorVer = '.0a6' setup( name='pylegos', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version=majorVer+minorVer, description='A python framework for enterprise projects', long_description=long_description, # The project's main homepage. url='https://github.com/velexio/pylegos', # Author details author='Gerry Christiansen', author_email='gchristiansen@velexio.com', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 2 - Pre-Alpha', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Application Frameworks', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', ], # What does your project relate to? keywords='framework enterprise development libraries database tools', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["my_module"], # List run-time dependencies here. These will be installed by pip when # your project is installed. For an analysis of "install_requires" vs pip's # requirements files see: # https://packaging.python.org/en/latest/requirements.html install_requires=['argparse', 'inflect', 'pycnic'], # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. package_data={ 'pylegos': ['framework_usage.dat', 'pylegos_manifest.ini'], 'pylegos.cli': ['templates/code/*', 'templates/config/*', 'templates/launchers/*'] }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' #data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'pylegos=pylegos.cli.pycli:main', ], }, )
{ "repo_name": "velexio/pyLegos", "path": "setup.py", "copies": "1", "size": "3827", "license": "mit", "hash": -5275636858090849000, "line_mean": 35.1132075472, "line_max": 94, "alpha_frac": 0.6757251111, "autogenerated": false, "ratio": 4.0031380753138075, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.009722611831379865, "num_lines": 106 }
"""A framework for restful APIs.""" # ----------------------------------------------------------------------------- # Module: dpa.restful # Author: Josh Tomlinson (jtomlin) # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # Imports: # ----------------------------------------------------------------------------- import copy from .client import RestfulClientError from .mixins import ListMixin, GetMixin # ----------------------------------------------------------------------------- # Public Classes # ----------------------------------------------------------------------------- class RestfulObject(object): exception_class = None # ------------------------------------------------------------------------- # Special methods: # ------------------------------------------------------------------------- def __init__(self, data): self._data = _RestfulData(data) # ------------------------------------------------------------------------- def __getattr__(self, attr): # look up the attribute in the _data try: return self._data.get(attr) except _RestfulDataError: raise AttributeError( '{cls} instance has no attribute "{attr}"'.format( cls=self.__class__.__name__, attr=attr, ) ) # ----------------------------------------------------------------------------- class RestfulObjectError(RestfulClientError): pass RestfulObject.exception_class = RestfulObjectError # ----------------------------------------------------------------------------- class ReadOnlyRestfulObject(ListMixin, GetMixin, RestfulObject): pass # ----------------------------------------------------------------------------- # Private Classes: # ----------------------------------------------------------------------------- class _RestfulData(object): # ------------------------------------------------------------------------- # Special methods: # ------------------------------------------------------------------------- def __init__(self, data_dict): """Constructor.""" super(_RestfulData, self).__init__() self._data = data_dict # ------------------------------------------------------------------------- # Instance methods: # ------------------------------------------------------------------------- def get(self, attr): try: return self._data[attr] except KeyError: raise _RestfulDataError( "No attribute '{a}' in data object.".format(a=attr)) # ------------------------------------------------------------------------- def set(self, attr, value): if not attr in self._data.keys(): raise _RestfulDataError( "No attribute '{a}' in data object.".format(a=attr)) self._data[attr] = value # ------------------------------------------------------------------------- # Properties # ------------------------------------------------------------------------- @property def data_dict(self): return self._data # ------------------------------------------------------------------------- @data_dict.setter def data_dict(self, data): self._data = data # ----------------------------------------------------------------------------- # Public exception classes: # ----------------------------------------------------------------------------- class _RestfulDataError(Exception): pass
{ "repo_name": "Clemson-DPA/dpa-pipe", "path": "dpa/restful/__init__.py", "copies": "1", "size": "3672", "license": "mit", "hash": 8085209448410311000, "line_mean": 34.3076923077, "line_max": 79, "alpha_frac": 0.2938453159, "autogenerated": false, "ratio": 7.0344827586206895, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.782832807452069, "avg_score": null, "num_lines": null }
"""A framework to analyse MS/MS clustering results in the .clustering file format. See: https://github.com/spectra-cluster/spectra-cluster-py """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path import re def get_property(prop, project): """ Extracts a property from the project's __init__ file :param prop: Property to extract :param project: Name of the project to process :return: Property value as string """ result = re.search(r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(prop), open(project + '/__init__.py').read()) return result.group(1) here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='spectra_cluster', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version=get_property('__version__', "spectra_cluster"), description='Framework to analyse MS/MS clustering results in the .clustering file format', long_description=long_description, # The project's main homepage. url='https://github.com/spectra-cluster/spectra-cluster-py/', # Author details author='Johannes Griss', author_email='johannes.griss@meduniwien.ac.at', # Choose your license license='Apache version 2', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'Topic :: Scientific/Engineering :: Bio-Informatics', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: Apache Software License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], # What does your project relate to? keywords='bioinformatics mass_spectrometry proteomics clustering', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['build', 'dist', 'docs', 'tests']), # List run-time dependencies here. These will be installed by pip when # your project is installed. For an analysis of "install_requires" vs pip's # requirements files see: # https://packaging.python.org/en/latest/requirements.html install_requires=['docopt', 'pyteomics >= 3.4', 'numpy', 'maspy'], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ 'dev': ['pyinstaller'], #'test': ['coverage'], }, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. #package_data={ # 'sample': ['package_data.dat'], #}, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' #data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ 'console_scripts': [ 'cluster_features_cli=spectra_cluster.ui.cluster_features_cli:main', 'cluster_parameter_extractor=spectra_cluster.ui.cluster_parameter_extractor:main', 'consensus_spectrum_exporter=spectra_cluster.ui.consensus_spectrum_exporter:main', 'id_transferer_cli=spectra_cluster.ui.id_transferer_cli:main', 'split_moff_file=spectra_cluster.ui.split_moff_file:main', 'mgf_search_result_annotator=spectra_cluster.ui.mgf_search_result_annotator:main', 'protein_annotator=spectra_cluster.ui.protein_annotator:main', 'unique_fasta_extractor=spectra_cluster.ui.unique_fasta_extractor:main', 'spectra_in_cluster=spectra_cluster.tools.spectra_in_cluster:main', 'fasta_species_filter=spectra_cluster.ui.fasta_species_filter:main', 'clustering_stats=spectra_cluster.ui.clustering_stats:main', 'cluster_result_comparator=spectra_cluster.ui.cluster_result_comparator:main' ], }, )
{ "repo_name": "spectra-cluster/spectra-cluster-py", "path": "setup.py", "copies": "1", "size": "5390", "license": "apache-2.0", "hash": -5920254116919606000, "line_mean": 39.8333333333, "line_max": 107, "alpha_frac": 0.6717996289, "autogenerated": false, "ratio": 3.8749101365923795, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5046709765492379, "avg_score": null, "num_lines": null }
# Africa 2010 # Problem A: Store Credit # Jon Hanson # # Declare Variables # ifile = 'input.txt' # simple input ofile = 'output.txt' # simple output #ifile = 'A-large-practice.in' # official input #ofile = 'A-large-practice.out' # official output caselist = [] # list containing cases # # Problem State (Case) Class # class CredCase(object): def __init__(self,credit,itemCount,items): # Initialize: self.credit = int(credit) # credit amount self.itemCount = int(itemCount) # item count self.items = list(map(int,items.split())) # item values list self.cost = -1 # total cost self.solution = [] # output list def trySolution(self,indices): cost = self.items[indices[0]] + self.items[indices[1]] if (cost <= self.credit) and (cost > self.cost): self.cost = cost self.solution = [x+1 for x in indices] # # Read Input File # with open(ifile) as f: cases = int(f.readline()) for n in range(0,cases): case = CredCase(f.readline(),f.readline(),f.readline()) caselist.append(case) # # Conduct Algorithm # for n in range(0,cases): case = caselist[n] for i in range(0,case.itemCount): for j in range( (i+1) , case.itemCount ): case.trySolution( [i,j] ) if case.credit == case.cost: break if case.credit == case.cost: break # # Write Output File # with open(ofile,'w') as f: for n in range(0,cases): case = caselist[n] casestr = 'Case #'+str(n+1)+': ' casestr = casestr+str(case.solution[0])+' '+str(case.solution[1])+'\n' checkstr = 'Check: Credit='+str(case.credit) checkstr += ' Cost='+str(case.cost) checkstr += ' Item'+str(case.solution[0])+'=' checkstr += str(case.items[case.solution[0]-1]) checkstr += ' Item'+str(case.solution[1])+'=' checkstr += str(case.items[case.solution[1]-1])+'\n' f.write(casestr) #f.write(checkstr)
{ "repo_name": "jonjon33/sandbox", "path": "python/codejam/2010-africa/a-StoreCredit/storeCredit.py", "copies": "1", "size": "2120", "license": "mit", "hash": 2951676645574412000, "line_mean": 28.4444444444, "line_max": 78, "alpha_frac": 0.5561320755, "autogenerated": false, "ratio": 3.297045101088647, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4353177176588647, "avg_score": null, "num_lines": null }
# Africa 2010 # Problem C - T9 Spelling # Jon Hanson # Declare Variables ifile = 'input.txt' ofile = 'output.txt' caselist = [] outlist = [] leadletter = ['a','d','g','j','m','p','t','w'] # Read Input File with open(ifile,"r") as f: # Open ifile as f cases = int(f.readline()) # Get num of cases from 1st line for n in range(0,cases): # For each case: caselist.append( f.readline() ) # Append a line to the caselist # Do Operation for n in range(0,cases): # For each case: buf = caselist[n] # Take the case string outstr = '' # Prep an output str prev = 0 # Previous t9 key 'value' val = 0 # Current t9 key 'value' qty = 0 # Current t9 key 'quantity' for i in range(0,len(buf)-1): # For each char in the case string: ch = buf[i] # Take a char if ch == ' ': # if it's space val = 0 # t9 val is 0 qty = 1 # qty is 1 else: # otherwise for n in range(2,10): # For each possible t9 value: if ord(ch) >= ord(leadletter[9-n]): # if char > ll val = (9-n)+2 # take that ll val qty = ord(ch) - ord(leadletter[9-n]) + 1 # eval qty of val break # break the for if val == prev: # If val didn't change: outstr += ' ' # Add a space to output string for j in range(0,qty): # Iterate qty times: outstr += str(val) # Add val to output string prev = val # Set prev to val outlist.append( outstr+'\n' ) # Append case output str to an output list # Write Output File with open(ofile,"w") as f: for n in range(0,cases): result = 'Case #' + str(n+1) + ': ' + outlist[n] f.write(result)
{ "repo_name": "jonjon33/sandbox", "path": "python/codejam/2010-africa/c-T9/t9.py", "copies": "1", "size": "2088", "license": "mit", "hash": 3236282141314642400, "line_mean": 39.9411764706, "line_max": 79, "alpha_frac": 0.4530651341, "autogenerated": false, "ratio": 3.80327868852459, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9711949387321954, "avg_score": 0.008878887060527038, "num_lines": 51 }
"""A friendly Python SFTP interface.""" from __future__ import print_function import os from contextlib import contextmanager import ntpath import posixpath import socket from stat import S_IMODE, S_ISDIR, S_ISREG import tempfile import warnings import paramiko from paramiko import SSHException # make available from paramiko import AuthenticationException # make available from paramiko import AgentKey __version__ = "0.2.9" # pylint: disable = R0913 def st_mode_to_int(val): '''SFTAttributes st_mode returns an stat type that shows more than what can be set. Trim off those bits and convert to an int representation. if you want an object that was `chmod 711` to return a value of 711, use this function :param int val: the value of an st_mode attr returned by SFTPAttributes :returns int: integer representation of octal mode ''' return int(str(oct(S_IMODE(val)))[-3:]) class ConnectionException(Exception): """Exception raised for connection problems Attributes: message -- explanation of the error """ def __init__(self, host, port): # Call the base class constructor with the parameters it needs Exception.__init__(self, host, port) self.message = 'Could not connect to host:port. %s:%s' class CredentialException(Exception): """Exception raised for credential problems Attributes: message -- explanation of the error """ def __init__(self, message): # Call the base class constructor with the parameters it needs Exception.__init__(self, message) self.message = message class WTCallbacks(object): '''an object to house the callbacks, used internally''' def __init__(self): '''set instance vars''' self._flist = [] self._dlist = [] self._ulist = [] def file_cb(self, pathname): '''called for regular files, appends pathname to .flist :param str pathname: file path ''' self._flist.append(pathname) def dir_cb(self, pathname): '''called for directories, appends pathname to .dlist :param str pathname: directory path ''' self._dlist.append(pathname) def unk_cb(self, pathname): '''called for unknown file types, appends pathname to .ulist :param str pathname: unknown entity path ''' self._ulist.append(pathname) @property def flist(self): '''return a sorted list of files currently traversed :getter: returns the list :setter: sets the list :type: list ''' return sorted(self._flist) @flist.setter def flist(self, val): '''setter for _flist ''' self._flist = val @property def dlist(self): '''return a sorted list of directories currently traversed :getter: returns the list :setter: sets the list :type: list ''' return sorted(self._dlist) @dlist.setter def dlist(self, val): '''setter for _dlist ''' self._dlist = val @property def ulist(self): '''return a sorted list of unknown entities currently traversed :getter: returns the list :setter: sets the list :type: list ''' return sorted(self._ulist) @ulist.setter def ulist(self, val): '''setter for _ulist ''' self._ulist = val class CnOpts(object): '''additional connection options beyond authentication :ivar bool|str log: initial value: False - log connection/handshake details? If set to True, pysftp creates a temporary file and logs to that. If set to a valid path and filename, pysftp logs to that. The name of the logfile can be found at ``.logfile`` :ivar bool compression: initial value: False - Enables compression on the transport, if set to True. :ivar list|None ciphers: initial value: None - List of ciphers to use in order. ''' def __init__(self): # self.ciphers = None # self.compression = False self.log = False self.compression = False self.ciphers = None class Connection(object): """Connects and logs into the specified hostname. Arguments that are not given are guessed from the environment. :param str host: The Hostname or IP of the remote machine. :param str|None username: *Default: None* - Your username at the remote machine. :param str|obj|None private_key: *Default: None* - path to private key file(str) or paramiko.AgentKey :param str|None password: *Default: None* - Your password at the remote machine. :param int port: *Default: 22* - The SSH port of the remote machine. :param str|None private_key_pass: *Default: None* - password to use, if private_key is encrypted. :param list|None ciphers: *Deprecated* - see ``pysftp.CnOpts`` and ``cnopts`` parameter :param bool|str log: *Deprecated* - see ``pysftp.CnOpts`` and ``cnopts`` parameter :param None|CnOpts cnopts: *Default: None* - extra connection options set in a CnOpts object. :returns: (obj) connection to the requested host :raises ConnectionException: :raises CredentialException: :raises SSHException: :raises AuthenticationException: :raises PasswordRequiredException: """ def __init__(self, host, username=None, private_key=None, password=None, port=22, private_key_pass=None, ciphers=None, log=False, cnopts=None ): if cnopts is None: self._cnopts = CnOpts() else: self._cnopts = cnopts # TODO: remove this if block and log param above in v0.3.0 if log: wmsg = "log parameter is deprecated and will be remove in 0.3.0. "\ "Use cnopts param." warnings.warn(wmsg, DeprecationWarning) self._cnopts.log = log # TODO: remove this if block and log param above in v0.3.0 if ciphers is not None: wmsg = "ciphers parameter is deprecated and will be remove in "\ "0.3.0. Use cnopts param." warnings.warn(wmsg, DeprecationWarning) self._cnopts.ciphers = ciphers self._sftp_live = False self._sftp = None if not username: username = os.environ['LOGNAME'] self._logfile = self._cnopts.log if self._cnopts.log: if isinstance(self._cnopts.log, bool): # Log to a temporary file. fhnd, self._logfile = tempfile.mkstemp('.txt', 'ssh-') os.close(fhnd) # don't want os file descriptors open paramiko.util.log_to_file(self._logfile) # Begin the SSH transport. self._transport_live = False try: self._transport = paramiko.Transport((host, port)) # Set security ciphers if set if self._cnopts.ciphers is not None: ciphers = self._cnopts.ciphers self._transport.get_security_options().ciphers = ciphers self._transport_live = True except (AttributeError, socket.gaierror): # couldn't connect raise ConnectionException(host, port) # Toggle compression self._transport.use_compression(self._cnopts.compression) # Authenticate the transport. prefer password if given if password is not None: # Using Password. self._transport.connect(username=username, password=password) else: # Use Private Key. if not private_key: # Try to use default key. if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')): private_key = '~/.ssh/id_rsa' elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')): private_key = '~/.ssh/id_dsa' else: raise CredentialException("You have not specified a " "password or key.") if not isinstance(private_key, AgentKey): private_key_file = os.path.expanduser(private_key) try: # try rsa rsakey = paramiko.RSAKey prv_key = rsakey.from_private_key_file(private_key_file, private_key_pass) except paramiko.SSHException: # if it fails, try dss dsskey = paramiko.DSSKey prv_key = dsskey.from_private_key_file(private_key_file, private_key_pass) else: # use the paramiko agent key prv_key = private_key self._transport.connect(username=username, pkey=prv_key) def _sftp_connect(self): """Establish the SFTP connection.""" if not self._sftp_live: self._sftp = paramiko.SFTPClient.from_transport(self._transport) self._sftp_live = True @property def pwd(self): '''return the current working directory :returns: (str) current working directory ''' self._sftp_connect() return self._sftp.normalize('.') def get(self, remotepath, localpath=None, callback=None, preserve_mtime=False): """Copies a file between the remote host and the local host. :param str remotepath: the remote path and filename, source :param str localpath: the local path and filename to copy, destination. If not specified, file is copied to local current working directory :param callable callback: optional callback function (form: ``func(int, int)``) that accepts the bytes transferred so far and the total bytes to be transferred. :param bool preserve_mtime: *Default: False* - make the modification time(st_mtime) on the local file match the time on the remote. (st_atime can differ because stat'ing the localfile can/does update it's st_atime) :returns: None :raises: IOError """ if not localpath: localpath = os.path.split(remotepath)[1] self._sftp_connect() if preserve_mtime: sftpattrs = self._sftp.stat(remotepath) self._sftp.get(remotepath, localpath, callback=callback) if preserve_mtime: os.utime(localpath, (sftpattrs.st_atime, sftpattrs.st_mtime)) def get_d(self, remotedir, localdir, preserve_mtime=False): """get the contents of remotedir and write to locadir. (non-recursive) :param str remotedir: the remote directory to copy from (source) :param str localdir: the local directory to copy to (target) :param bool preserve_mtime: *Default: False* - preserve modification time on files :returns: None :raises: """ self._sftp_connect() with self.cd(remotedir): for sattr in self._sftp.listdir_attr('.'): if S_ISREG(sattr.st_mode): rname = sattr.filename self.get(rname, reparent(localdir, rname), preserve_mtime=preserve_mtime) def get_r(self, remotedir, localdir, preserve_mtime=False): """recursively copy remotedir structure to localdir :param str remotedir: the remote directory to copy from :param str localdir: the local directory to copy to :param bool preserve_mtime: *Default: False* - preserve modification time on files :returns: None :raises: """ self._sftp_connect() wtcb = WTCallbacks() self.walktree(remotedir, wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb) # handle directories we recursed through for dname in wtcb.dlist: for subdir in path_advance(dname): try: os.mkdir(reparent(localdir, subdir)) # force result to a list for setter, wtcb.dlist = wtcb.dlist + [subdir, ] except OSError: # dir exists pass for fname in wtcb.flist: # they may have told us to start down farther, so we may not have # recursed through some, ensure local dir structure matches head, _ = os.path.split(fname) if head not in wtcb.dlist: for subdir in path_advance(head): if subdir not in wtcb.dlist and subdir != '.': os.mkdir(reparent(localdir, subdir)) wtcb.dlist = wtcb.dlist + [subdir, ] self.get(fname, reparent(localdir, fname), preserve_mtime=preserve_mtime) def getfo(self, remotepath, flo, callback=None): """Copy a remote file (remotepath) to a file-like object, flo. :param str remotepath: the remote path and filename, source :param flo: open file like object to write, destination. :param callable callback: optional callback function (form: ``func(int, int``)) that accepts the bytes transferred so far and the total bytes to be transferred. :returns: (int) the number of bytes written to the opened file object :raises: Any exception raised by operations will be passed through. """ self._sftp_connect() return self._sftp.getfo(remotepath, flo, callback=callback) def put(self, localpath, remotepath=None, callback=None, confirm=True, preserve_mtime=False): """Copies a file between the local host and the remote host. :param str localpath: the local path and filename :param str remotepath: the remote path, else the remote :attr:`.pwd` and filename is used. :param callable callback: optional callback function (form: ``func(int, int``)) that accepts the bytes transferred so far and the total bytes to be transferred. :param bool confirm: whether to do a stat() on the file afterwards to confirm the file size :param bool preserve_mtime: *Default: False* - make the modification time(st_mtime) on the remote file match the time on the local. (st_atime can differ because stat'ing the localfile can/does update it's st_atime) :returns: (obj) SFTPAttributes containing attributes about the given file :raises IOError: if remotepath doesn't exist :raises OSError: if localpath doesn't exist """ if not remotepath: remotepath = os.path.split(localpath)[1] self._sftp_connect() if preserve_mtime: local_stat = os.stat(localpath) times = (local_stat.st_atime, local_stat.st_mtime) sftpattrs = self._sftp.put(localpath, remotepath, callback=callback, confirm=confirm) if preserve_mtime: self._sftp.utime(remotepath, times) sftpattrs = self._sftp.stat(remotepath) return sftpattrs def put_d(self, localpath, remotepath, confirm=True, preserve_mtime=False): """Copies a local directory's contents to a remotepath :param str localpath: the local path to copy (source) :param str remotepath: the remote path to copy to (target) :param bool confirm: whether to do a stat() on the file afterwards to confirm the file size :param bool preserve_mtime: *Default: False* - make the modification time(st_mtime) on the remote file match the time on the local. (st_atime can differ because stat'ing the localfile can/does update it's st_atime) :returns: None :raises IOError: if remotepath doesn't exist :raises OSError: if localpath doesn't exist """ self._sftp_connect() wtcb = WTCallbacks() cur_local_dir = os.getcwd() os.chdir(localpath) walktree('.', wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb, recurse=False) for fname in wtcb.flist: src = os.path.join(localpath, fname) dest = reparent(remotepath, fname) # print('put', src, dest) self.put(src, dest, confirm=confirm, preserve_mtime=preserve_mtime) # restore local directory os.chdir(cur_local_dir) def put_r(self, localpath, remotepath, confirm=True, preserve_mtime=False): """Recursively copies a local directory's contents to a remotepath :param str localpath: the local path to copy (source) :param str remotepath: the remote path to copy to (target) :param bool confirm: whether to do a stat() on the file afterwards to confirm the file size :param bool preserve_mtime: *Default: False* - make the modification time(st_mtime) on the remote file match the time on the local. (st_atime can differ because stat'ing the localfile can/does update it's st_atime) :returns: None :raises IOError: if remotepath doesn't exist :raises OSError: if localpath doesn't exist """ self._sftp_connect() wtcb = WTCallbacks() cur_local_dir = os.getcwd() os.chdir(localpath) walktree('.', wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb) # restore local directory os.chdir(cur_local_dir) for dname in wtcb.dlist: if dname != '.': self.mkdir(reparent(remotepath, dname)) for fname in wtcb.flist: head, _ = os.path.split(fname) if head not in wtcb.dlist: for subdir in path_advance(head): if subdir not in wtcb.dlist and subdir != '.': self.mkdir(reparent(remotepath, subdir)) wtcb.dlist = wtcb.dlist + [subdir, ] src = os.path.join(localpath, fname) dest = reparent(remotepath, fname) # print('put', src, dest) self.put(src, dest, confirm=confirm, preserve_mtime=preserve_mtime) def putfo(self, flo, remotepath=None, file_size=0, callback=None, confirm=True): """Copies the contents of a file like object to remotepath. :param flo: a file-like object that supports .read() :param str remotepath: the remote path. :param int file_size: the size of flo, if not given the second param passed to the callback function will always be 0. :param callable callback: optional callback function (form: ``func(int, int``)) that accepts the bytes transferred so far and the total bytes to be transferred. :param bool confirm: whether to do a stat() on the file afterwards to confirm the file size :returns: (obj) SFTPAttributes containing attributes about the given file :raises: TypeError, if remotepath not specified, any underlying error """ self._sftp_connect() return self._sftp.putfo(flo, remotepath, file_size=file_size, callback=callback, confirm=confirm) def execute(self, command): """Execute the given commands on a remote machine. The command is executed without regard to the remote :attr:`.pwd`. :param str command: the command to execute. :returns: (list of str) representing the results of the command :raises: Any exception raised by command will be passed through. """ channel = self._transport.open_session() channel.exec_command(command) output = channel.makefile('rb', -1).readlines() if output: return output else: return channel.makefile_stderr('rb', -1).readlines() @contextmanager def cd(self, remotepath=None): """context manager that can change to a optionally specified remote directory and restores the old pwd on exit. :param str|None remotepath: *Default: None* - remotepath to temporarily make the current directory :returns: None :raises: IOError, if remote path doesn't exist """ try: original_path = self.pwd if remotepath is not None: self.cwd(remotepath) yield finally: self.cwd(original_path) def chdir(self, remotepath): """change the current working directory on the remote :param str remotepath: the remote path to change to :returns: None :raises: IOError, if path does not exist """ self._sftp_connect() self._sftp.chdir(remotepath) cwd = chdir # synonym for chdir def chmod(self, remotepath, mode=777): """set the mode of a remotepath to mode, where mode is an integer representation of the octal mode to use. :param str remotepath: the remote path/file to modify :param int mode: *Default: 777* - int representation of octal mode for directory :returns: None :raises: IOError, if the file doesn't exist """ self._sftp_connect() self._sftp.chmod(remotepath, mode=int(str(mode), 8)) def chown(self, remotepath, uid=None, gid=None): """ set uid and/or gid on a remotepath, you may specify either or both. Unless you have **permission** to do this on the remote server, you will raise an IOError: 13 - permission denied :param str remotepath: the remote path/file to modify :param int uid: the user id to set on the remotepath :param int gid: the group id to set on the remotepath :returns: None :raises: IOError, if you don't have permission or the file doesn't exist """ self._sftp_connect() if uid is None or gid is None: if uid is None and gid is None: # short circuit if no change return rstat = self._sftp.stat(remotepath) if uid is None: uid = rstat.st_uid if gid is None: gid = rstat.st_gid self._sftp.chown(remotepath, uid=uid, gid=gid) def getcwd(self): """return the current working directory on the remote. This is a wrapper for paramiko's method and not to be confused with the SFTP command, cwd. :returns: (str) the current remote path. None, if not set. """ self._sftp_connect() return self._sftp.getcwd() def listdir(self, remotepath='.'): """return a list of files/directories for the given remote path. Unlike, paramiko, the directory listing is sorted. :param str remotepath: path to list on the server :returns: (list of str) directory entries, sorted """ self._sftp_connect() return sorted(self._sftp.listdir(remotepath)) def listdir_attr(self, remotepath='.'): """return a list of SFTPAttribute objects of the files/directories for the given remote path. The list is in arbitrary order. It does not include the special entries '.' and '..'. The returned SFTPAttributes objects will each have an additional field: longname, which may contain a formatted string of the file's attributes, in unix format. The content of this string will depend on the SFTP server. :param str remotepath: path to list on the server :returns: (list of SFTPAttributes), sorted """ self._sftp_connect() return sorted(self._sftp.listdir_attr(remotepath), key=lambda attr: attr.filename) def mkdir(self, remotepath, mode=777): """Create a directory named remotepath with mode. On some systems, mode is ignored. Where it is used, the current umask value is first masked out. :param str remotepath: directory to create` :param int mode: *Default: 777* - int representation of octal mode for directory :returns: None """ self._sftp_connect() self._sftp.mkdir(remotepath, mode=int(str(mode), 8)) def normalize(self, remotepath): """Return the expanded path, w.r.t the server, of a given path. This can be used to resolve symlinks or determine what the server believes to be the :attr:`.pwd`, by passing '.' as remotepath. :param str remotepath: path to be normalized :return: (str) normalized form of the given path :raises: IOError, if remotepath can't be resolved """ self._sftp_connect() return self._sftp.normalize(remotepath) def isdir(self, remotepath): """return true, if remotepath is a directory :param str remotepath: the path to test :returns: (bool) """ self._sftp_connect() try: result = S_ISDIR(self._sftp.stat(remotepath).st_mode) except IOError: # no such file result = False return result def isfile(self, remotepath): """return true if remotepath is a file :param str remotepath: the path to test :returns: (bool) """ self._sftp_connect() try: result = S_ISREG(self._sftp.stat(remotepath).st_mode) except IOError: # no such file result = False return result def makedirs(self, remotedir, mode=777): """create all directories in remotedir as needed, setting their mode to mode, if created. If remotedir already exists, silently complete. If a regular file is in the way, raise an exception. :param str remotedir: the directory structure to create :param int mode: *Default: 777* - int representation of octal mode for directory :returns: None :raises: OSError """ self._sftp_connect() if self.isdir(remotedir): pass elif self.isfile(remotedir): raise OSError("a file with the same name as the remotedir, " "'%s', already exists." % remotedir) else: head, tail = os.path.split(remotedir) if head and not self.isdir(head): self.makedirs(head, mode) if tail: self.mkdir(remotedir, mode=mode) def readlink(self, remotelink): """Return the target of a symlink (shortcut). The result will be an absolute pathname. :param str remotelink: remote path of the symlink :return: (str) absolute path to target """ self._sftp_connect() return self._sftp.normalize(self._sftp.readlink(remotelink)) def remove(self, remotefile): """remove the file @ remotefile, remotefile may include a path, if no path, then :attr:`.pwd` is used. This method only works on files :param str remotefile: the remote file to delete :returns: None :raises: IOError """ self._sftp_connect() self._sftp.remove(remotefile) unlink = remove # synonym for remove def rmdir(self, remotepath): """remove remote directory :param str remotepath: the remote directory to remove :returns: None """ self._sftp_connect() self._sftp.rmdir(remotepath) def rename(self, remote_src, remote_dest): """rename a file or directory on the remote host. :param str remote_src: the remote file/directory to rename :param str remote_dest: the remote file/directory to put it :returns: None :raises: IOError """ self._sftp_connect() self._sftp.rename(remote_src, remote_dest) def stat(self, remotepath): """return information about file/directory for the given remote path :param str remotepath: path to stat :returns: (obj) SFTPAttributes """ self._sftp_connect() return self._sftp.stat(remotepath) def lstat(self, remotepath): """return information about file/directory for the given remote path, without following symbolic links. Otherwise, the same as .stat() :param str remotepath: path to stat :returns: (obj) SFTPAttributes object """ self._sftp_connect() return self._sftp.lstat(remotepath) def close(self): """Closes the connection and cleans up.""" # Close SFTP Connection. if self._sftp_live: self._sftp.close() self._sftp_live = False # Close the SSH Transport. if self._transport_live: self._transport.close() self._transport_live = False # clean up any loggers if self._cnopts.log: # if handlers are active they hang around until the app exits # this closes and removes the handlers if in use at close import logging lgr = logging.getLogger("paramiko") if lgr: lgr.handlers = [] def open(self, remote_file, mode='r', bufsize=-1): """Open a file on the remote server. See http://paramiko-docs.readthedocs.org/en/latest/api/sftp.html for details. :param str remote_file: name of the file to open. :param str mode: mode (Python-style) to open file (always assumed binary) :param int bufsize: *Default: -1* - desired buffering :returns: (obj) SFTPFile, a handle the remote open file :raises: IOError, if the file could not be opened. """ self._sftp_connect() return self._sftp.open(remote_file, mode=mode, bufsize=bufsize) def exists(self, remotepath): """Test whether a remotepath exists. :param str remotepath: the remote path to verify :returns: (bool) True, if remotepath exists, else False """ self._sftp_connect() try: self._sftp.stat(remotepath) except IOError: return False return True def lexists(self, remotepath): """Test whether a remotepath exists. Returns True for broken symbolic links :param str remotepath: the remote path to verify :returns: (bool), True, if lexists, else False """ self._sftp_connect() try: self._sftp.lstat(remotepath) except IOError: return False return True def symlink(self, remote_src, remote_dest): '''create a symlink for a remote file on the server :param str remote_src: path of original file :param str remote_dest: path of the created symlink :returns: None :raises: any underlying error, IOError if something already exists at remote_dest ''' self._sftp_connect() self._sftp.symlink(remote_src, remote_dest) def truncate(self, remotepath, size): """Change the size of the file specified by path. Used to modify the size of the file, just like the truncate method on Python file objects. The new file size is confirmed and returned. :param str remotepath: remote file path to modify :param int|long size: the new file size :returns: (int) new size of file :raises: IOError, if file does not exist """ self._sftp_connect() self._sftp.truncate(remotepath, size) return self._sftp.stat(remotepath).st_size def walktree(self, remotepath, fcallback, dcallback, ucallback, recurse=True): '''recursively descend, depth first, the directory tree rooted at remotepath, calling discreet callback functions for each regular file, directory and unknown file type. :param str remotepath: root of remote directory to descend, use '.' to start at :attr:`.pwd` :param callable fcallback: callback function to invoke for a regular file. (form: ``func(str)``) :param callable dcallback: callback function to invoke for a directory. (form: ``func(str)``) :param callable ucallback: callback function to invoke for an unknown file type. (form: ``func(str)``) :param bool recurse: *Default: True* - should it recurse :returns: None :raises: ''' self._sftp_connect() for entry in self.listdir(remotepath): pathname = posixpath.join(remotepath, entry) mode = self._sftp.stat(pathname).st_mode if S_ISDIR(mode): # It's a directory, call the dcallback function dcallback(pathname) if recurse: # now, recurse into it self.walktree(pathname, fcallback, dcallback, ucallback) elif S_ISREG(mode): # It's a file, call the fcallback function fcallback(pathname) else: # Unknown file type ucallback(pathname) @property def sftp_client(self): """give access to the underlying, connected paramiko SFTPClient object see http://paramiko-docs.readthedocs.org/en/latest/api/sftp.html :params: None :returns: (obj) the active SFTPClient object """ self._sftp_connect() return self._sftp @property def active_ciphers(self): """Get tuple of currently used local and remote ciphers. :returns: (tuple of str) currently used ciphers (local_cipher, remote_cipher) """ return self._transport.local_cipher, self._transport.remote_cipher @property def active_compression(self): """Get tuple of currently used local and remote compression. :returns: (tuple of str) currently used compression (local_compression, remote_compression) """ localc = self._transport.local_compression remotec = self._transport.remote_compression return localc, remotec @property def security_options(self): """return the available security options recognized by paramiko. :returns: (obj) security preferences of the ssh transport. These are tuples of acceptable `.ciphers`, `.digests`, `.key_types`, and key exchange algorithms `.kex`, listed in order of preference. """ return self._transport.get_security_options() @property def logfile(self): '''return the name of the file used for logging or False it not logging :returns: (str)logfile or (bool) False ''' return self._logfile @property def timeout(self): ''' (float|None) *Default: None* - get or set the underlying socket timeout for pending read/write ops. :returns: (float|None) seconds to wait for a pending read/write operation before raising socket.timeout, or None for no timeout ''' self._sftp_connect() channel = self._sftp.get_channel() return channel.gettimeout() @timeout.setter def timeout(self, val): '''setter for timeout''' self._sftp_connect() channel = self._sftp.get_channel() channel.settimeout(val) def __del__(self): """Attempt to clean up if not explicitly closed.""" self.close() def __enter__(self): return self def __exit__(self, etype, value, traceback): self.close() def path_advance(thepath, sep=os.sep): '''generator to iterate over a file path forwards :param str thepath: the path to navigate forwards :param str sep: *Default: os.sep* - the path separator to use :returns: (iter)able of strings ''' # handle a direct path pre = '' if thepath[0] == sep: pre = sep curpath = '' parts = thepath.split(sep) if pre: if parts[0]: parts[0] = pre + parts[0] else: parts[1] = pre + parts[1] for part in parts: curpath = os.path.join(curpath, part) if curpath: yield curpath def path_retreat(thepath, sep=os.sep): '''generator to iterate over a file path in reverse :param str thepath: the path to retreat over :param str sep: *Default: os.sep* - the path separator to use :returns: (iter)able of strings ''' pre = '' if thepath[0] == sep: pre = sep parts = thepath.split(sep) while parts: if os.path.join(*parts): yield '%s%s' % (pre, os.path.join(*parts)) parts = parts[:-1] def reparent(newparent, oldpath): '''when copying or moving a directory structure, you need to re-parent the oldpath. When using os.path.join to calculate this new path, the appearance of a / root path at the beginning of oldpath, supplants the newparent and we don't want this to happen, so we need to make the oldpath root appear as a child of the newparent. :param: str newparent: the new parent location for oldpath (target) :param str oldpath: the path being adopted by newparent (source) :returns: (str) resulting adoptive path ''' if oldpath[0] in (posixpath.sep, ntpath.sep): oldpath = '.' + oldpath return os.path.join(newparent, oldpath) def walktree(localpath, fcallback, dcallback, ucallback, recurse=True): '''on the local file system, recursively descend, depth first, the directory tree rooted at localpath, calling discreet callback functions for each regular file, directory and unknown file type. :param str localpath: root of remote directory to descend, use '.' to start at :attr:`.pwd` :param callable fcallback: callback function to invoke for a regular file. (form: ``func(str)``) :param callable dcallback: callback function to invoke for a directory. (form: ``func(str)``) :param callable ucallback: callback function to invoke for an unknown file type. (form: ``func(str)``) :param bool recurse: *Default: True* - should it recurse :returns: None :raises: OSError, if localpath doesn't exist ''' for entry in os.listdir(localpath): pathname = os.path.join(localpath, entry) mode = os.stat(pathname).st_mode if S_ISDIR(mode): # It's a directory, call the dcallback function dcallback(pathname) if recurse: # now, recurse into it walktree(pathname, fcallback, dcallback, ucallback) elif S_ISREG(mode): # It's a file, call the fcallback function fcallback(pathname) else: # Unknown file type ucallback(pathname) @contextmanager def cd(localpath=None): """context manager that can change to a optionally specified local directory and restores the old pwd on exit. :param str|None localpath: *Default: None* - local path to temporarily make the current directory :returns: None :raises: OSError, if local path doesn't exist """ try: original_path = os.getcwd() if localpath is not None: os.chdir(localpath) yield finally: os.chdir(original_path)
{ "repo_name": "Clean-Cole/pysftp", "path": "pysftp.py", "copies": "1", "size": "40211", "license": "bsd-3-clause", "hash": -6920847075844406000, "line_mean": 32.2872516556, "line_max": 80, "alpha_frac": 0.5942155132, "autogenerated": false, "ratio": 4.383148027032919, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5477363540232919, "avg_score": null, "num_lines": null }
"""A friendly Python SFTP interface.""" from __future__ import print_function import os from contextlib import contextmanager import socket from stat import S_IMODE, S_ISDIR, S_ISREG import tempfile import paramiko from paramiko import SSHException # make available from paramiko import AuthenticationException # make available from paramiko import AgentKey __version__ = "0.2.8" # pylint: disable = R0913 def st_mode_to_int(val): '''SFTAttributes st_mode returns an stat type that shows more than what can be set. Trim off those bits and convert to an int representation. if you want an object that was `chmod 711` to return a value of 711, use this function :param int val: the value of an st_mode attr returned by SFTPAttributes :returns int: integer representation of octal mode ''' return int(str(oct(S_IMODE(val)))[-3:]) class ConnectionException(Exception): """Exception raised for connection problems Attributes: message -- explanation of the error """ def __init__(self, host, port): # Call the base class constructor with the parameters it needs Exception.__init__(self, host, port) self.message = 'Could not connect to host:port. %s:%s' class CredentialException(Exception): """Exception raised for credential problems Attributes: message -- explanation of the error """ def __init__(self, message): # Call the base class constructor with the parameters it needs Exception.__init__(self, message) self.message = message class WTCallbacks(object): '''an object to house the callbacks, used internally :ivar flist: list of files currently traversed :ivar dlist: list of directories currently traversed :ivar ulist: list of unknown entities currently traversed ''' def __init__(self): '''set instance vars''' self.flist = [] self.dlist = [] self.ulist = [] def file_cb(self, pathname): '''called for regular files, appends pathname to .flist :param str pathname: file path ''' self.flist.append(pathname) def dir_cb(self, pathname): '''called for directories, appends pathname to .dlist :param str pathname: directory path ''' self.dlist.append(pathname) def unk_cb(self, pathname): '''called for unknown file types, appends pathname to .ulist :param str pathname: unknown entity path ''' self.ulist.append(pathname) class Connection(object): """Connects and logs into the specified hostname. Arguments that are not given are guessed from the environment. :param str host: The Hostname or IP of the remote machine. :param str|None username: *Default: None* - Your username at the remote machine. :param str|obj|None private_key: *Default: None* - path to private key file(str) or paramiko.AgentKey :param str|None password: *Default: None* - Your password at the remote machine. :param int port: *Default: 22* - The SSH port of the remote machine. :param str|None private_key_pass: *Default: None* - password to use, if private_key is encrypted. :param list|None ciphers: *Default: None* - List of ciphers to use in order. :param bool|str log: *Default: False* - log connection/handshake details? If set to True, pysftp creates a temporary file and logs to that. If set to a valid path and filename, pysftp logs to that. The name of the logfile can be found at ``.logfile`` :returns: (obj) connection to the requested host :raises ConnectionException: :raises CredentialException: :raises SSHException: :raises AuthenticationException: :raises PasswordRequiredException: """ def __init__(self, host, username=None, private_key=None, password=None, port=22, private_key_pass=None, ciphers=None, log=False, ): self._sftp_live = False self._sftp = None if not username: username = os.environ['LOGNAME'] self._logfile = log if log: if isinstance(log, bool): # Log to a temporary file. fhnd, self._logfile = tempfile.mkstemp('.txt', 'ssh-') os.close(fhnd) # don't want os file descriptors open paramiko.util.log_to_file(self._logfile) # Begin the SSH transport. self._transport_live = False try: self._transport = paramiko.Transport((host, port)) # Set security ciphers if set if ciphers is not None: self._transport.get_security_options().ciphers = ciphers self._transport_live = True except (AttributeError, socket.gaierror): # couldn't connect raise ConnectionException(host, port) # Authenticate the transport. prefer password if given if password is not None: # Using Password. self._transport.connect(username=username, password=password) else: # Use Private Key. if not private_key: # Try to use default key. if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')): private_key = '~/.ssh/id_rsa' elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')): private_key = '~/.ssh/id_dsa' else: raise CredentialException("You have not specified a "\ "password or key.") if not isinstance(private_key, AgentKey): private_key_file = os.path.expanduser(private_key) try: #try rsa rsakey = paramiko.RSAKey prv_key = rsakey.from_private_key_file(private_key_file, private_key_pass) except paramiko.SSHException: #if it fails, try dss dsskey = paramiko.DSSKey prv_key = dsskey.from_private_key_file(private_key_file, private_key_pass) else: # use the paramiko agent key prv_key = private_key self._transport.connect(username=username, pkey=prv_key) def _sftp_connect(self): """Establish the SFTP connection.""" if not self._sftp_live: self._sftp = paramiko.SFTPClient.from_transport(self._transport) self._sftp_live = True @property def pwd(self): '''return the current working directory :returns: (str) current working directory ''' self._sftp_connect() return self._sftp.normalize('.') def get(self, remotepath, localpath=None, callback=None, preserve_mtime=False): """Copies a file between the remote host and the local host. :param str remotepath: the remote path and filename, source :param str localpath: the local path and filename to copy, destination. If not specified, file is copied to local current working directory :param callable callback: optional callback function (form: ``func(int, int)``) that accepts the bytes transferred so far and the total bytes to be transferred. :param bool preserve_mtime: *Default: False* - make the modification time(st_mtime) on the local file match the time on the remote. (st_atime can differ because stat'ing the localfile can/does update it's st_atime) :returns: None :raises: IOError """ if not localpath: localpath = os.path.split(remotepath)[1] self._sftp_connect() if preserve_mtime: sftpattrs = self._sftp.stat(remotepath) self._sftp.get(remotepath, localpath, callback=callback) if preserve_mtime: os.utime(localpath, (sftpattrs.st_atime, sftpattrs.st_mtime)) def get_d(self, remotedir, localdir, preserve_mtime=False): """get the contents of remotedir and write to locadir. (non-recursive) :param str remotedir: the remote directory to copy from (source) :param str localdir: the local directory to copy to (target) :param bool preserve_mtime: *Default: False* - preserve modification time on files :returns: None :raises: """ self._sftp_connect() with self.cd(remotedir): for sattr in self._sftp.listdir_attr('.'): if S_ISREG(sattr.st_mode): rname = sattr.filename self.get(rname, reparent(localdir, rname), preserve_mtime=preserve_mtime) def get_r(self, remotedir, localdir, preserve_mtime=False): """recursively copy remotedir structure to localdir :param str remotedir: the remote directory to copy from :param str localdir: the local directory to copy to :param bool preserve_mtime: *Default: False* - preserve modification time on files :returns: None :raises: """ self._sftp_connect() wtcb = WTCallbacks() self.walktree(remotedir, wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb) # handle directories we recursed through for dname in wtcb.dlist: for subdir in path_advance(dname): try: os.mkdir(reparent(localdir, subdir)) wtcb.dlist.append(subdir) except OSError: # dir exists pass for fname in wtcb.flist: # they may have told us to start down farther, so we may not have # recursed through some, ensure local dir structure matches head, _ = os.path.split(fname) if head not in wtcb.dlist: for subdir in path_advance(head): if subdir not in wtcb.dlist and subdir != '.': os.mkdir(reparent(localdir, subdir)) wtcb.dlist.append(subdir) self.get(fname, reparent(localdir, fname), preserve_mtime=preserve_mtime ) def getfo(self, remotepath, flo, callback=None): """Copy a remote file (remotepath) to a file-like object, flo. :param str remotepath: the remote path and filename, source :param flo: open file like object to write, destination. :param callable callback: optional callback function (form: ``func(int, int``)) that accepts the bytes transferred so far and the total bytes to be transferred. :returns: (int) the number of bytes written to the opened file object :raises: Any exception raised by operations will be passed through. """ self._sftp_connect() return self._sftp.getfo(remotepath, flo, callback=callback) def put(self, localpath, remotepath=None, callback=None, confirm=True, preserve_mtime=False): """Copies a file between the local host and the remote host. :param str localpath: the local path and filename :param str remotepath: the remote path, else the remote :attr:`.pwd` and filename is used. :param callable callback: optional callback function (form: ``func(int, int``)) that accepts the bytes transferred so far and the total bytes to be transferred.. :param bool confirm: whether to do a stat() on the file afterwards to confirm the file size :param bool preserve_mtime: *Default: False* - make the modification time(st_mtime) on the remote file match the time on the local. (st_atime can differ because stat'ing the localfile can/does update it's st_atime) :returns: (obj) SFTPAttributes containing attributes about the given file :raises IOError: if remotepath doesn't exist :raises OSError: if localpath doesn't exist """ if not remotepath: remotepath = os.path.split(localpath)[1] self._sftp_connect() if preserve_mtime: local_stat = os.stat(localpath) times = (local_stat.st_atime, local_stat.st_mtime) sftpattrs = self._sftp.put(localpath, remotepath, callback=callback, confirm=confirm) if preserve_mtime: self._sftp.utime(remotepath, times) sftpattrs = self._sftp.stat(remotepath) return sftpattrs def put_d(self, localpath, remotepath, confirm=True, preserve_mtime=False): """Copies a local directory's contents to a remotepath :param str localpath: the local path to copy (source) :param str remotepath: the remote path to copy to (target) :param bool confirm: whether to do a stat() on the file afterwards to confirm the file size :param bool preserve_mtime: *Default: False* - make the modification time(st_mtime) on the remote file match the time on the local. (st_atime can differ because stat'ing the localfile can/does update it's st_atime) :returns: None :raises IOError: if remotepath doesn't exist :raises OSError: if localpath doesn't exist """ self._sftp_connect() wtcb = WTCallbacks() cur_local_dir = os.getcwd() os.chdir(localpath) walktree('.', wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb, recurse=False) for fname in wtcb.flist: src = os.path.join(localpath, fname) dest = reparent(remotepath, fname) # print('put', src, dest) self.put(src, dest, confirm=confirm, preserve_mtime=preserve_mtime) # restore local directory os.chdir(cur_local_dir) def put_r(self, localpath, remotepath, confirm=True, preserve_mtime=False): """Recursively copies a local directory's contents to a remotepath :param str localpath: the local path to copy (source) :param str remotepath: the remote path to copy to (target) :param bool confirm: whether to do a stat() on the file afterwards to confirm the file size :param bool preserve_mtime: *Default: False* - make the modification time(st_mtime) on the remote file match the time on the local. (st_atime can differ because stat'ing the localfile can/does update it's st_atime) :returns: None :raises IOError: if remotepath doesn't exist :raises OSError: if localpath doesn't exist """ self._sftp_connect() wtcb = WTCallbacks() cur_local_dir = os.getcwd() os.chdir(localpath) walktree('.', wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb) # restore local directory os.chdir(cur_local_dir) for dname in wtcb.dlist: #for subdir in path_advance(dname): if dname != '.': self.mkdir(reparent(remotepath, dname)) for fname in wtcb.flist: head, _ = os.path.split(fname) if head not in wtcb.dlist: for subdir in path_advance(head): if subdir not in wtcb.dlist and subdir != '.': self.mkdir(reparent(remotepath, subdir)) wtcb.dlist.append(subdir) src = os.path.join(localpath, fname) dest = reparent(remotepath, fname) # print('put', src, dest) self.put(src, dest, confirm=confirm, preserve_mtime=preserve_mtime) def putfo(self, flo, remotepath=None, file_size=0, callback=None, confirm=True): """Copies the contents of a file like object to remotepath. :param flo: a file-like object that supports .read() :param str remotepath: the remote path. :param int file_size: the size of flo, if not given the second param passed to the callback function will always be 0. :param callable callback: optional callback function (form: ``func(int, int``)) that accepts the bytes transferred so far and the total bytes to be transferred.. :param bool confirm: whether to do a stat() on the file afterwards to confirm the file size :returns: (obj) SFTPAttributes containing attributes about the given file :raises: TypeError, if remotepath not specified, any underlying error """ self._sftp_connect() return self._sftp.putfo(flo, remotepath, file_size=file_size, callback=callback, confirm=confirm) def execute(self, command): """Execute the given commands on a remote machine. The command is executed without regard to the remote :attr:`.pwd`. :param str command: the command to execute. :returns: (list of str) representing the results of the command :raises: Any exception raised by command will be passed through. """ channel = self._transport.open_session() channel.exec_command(command) output = channel.makefile('rb', -1).readlines() if output: return output else: return channel.makefile_stderr('rb', -1).readlines() @contextmanager def cd(self, remotepath=None): """context manager that can change to a optionally specified remote directory and restores the old pwd on exit. :param str|None remotepath: *Default: None* - remotepath to temporarily make the current directory :returns: None :raises: IOError, if remote path doesn't exist """ try: original_path = self.pwd if remotepath is not None: self.cwd(remotepath) yield finally: self.cwd(original_path) def chdir(self, remotepath): """change the current working directory on the remote :param str remotepath: the remote path to change to :returns: None :raises: IOError, if path does not exist """ self._sftp_connect() self._sftp.chdir(remotepath) cwd = chdir # synonym for chdir def chmod(self, remotepath, mode=777): """set the mode of a remotepath to mode, where mode is an integer representation of the octal mode to use. :param str remotepath: the remote path/file to modify :param int mode: *Default: 777* - int representation of octal mode for directory :returns: None :raises: IOError, if the file doesn't exist """ self._sftp_connect() self._sftp.chmod(remotepath, mode=int(str(mode), 8)) def chown(self, remotepath, uid=None, gid=None): """ set uid and/or gid on a remotepath, you may specify either or both. Unless you have **permission** to do this on the remote server, you will raise an IOError: 13 - permission denied :param str remotepath: the remote path/file to modify :param int uid: the user id to set on the remotepath :param int gid: the group id to set on the remotepath :returns: None :raises: IOError, if you don't have permission or the file doesn't exist """ self._sftp_connect() if uid is None or gid is None: if uid is None and gid is None: # short circuit if no change return rstat = self._sftp.stat(remotepath) if uid is None: uid = rstat.st_uid if gid is None: gid = rstat.st_gid self._sftp.chown(remotepath, uid=uid, gid=gid) def getcwd(self): """return the current working directory on the remote. This is a wrapper for paramiko's method and not to be confused with the SFTP command, cwd. :returns: (str) the current remote path. None, if not set. """ self._sftp_connect() return self._sftp.getcwd() def listdir(self, remotepath='.'): """return a list of files/directories for the given remote path. Unlike, paramiko, the directory listing is sorted. :param str remotepath: path to list on the server :returns: (list of str) directory entries, sorted """ self._sftp_connect() return sorted(self._sftp.listdir(remotepath)) def listdir_attr(self, remotepath='.'): """return a list of SFTPAttribute objects of the files/directories for the given remote path. The list is in arbitrary order. It does not include the special entries '.' and '..'. The returned SFTPAttributes objects will each have an additional field: longname, which may contain a formatted string of the file's attributes, in unix format. The content of this string will depend on the SFTP server. :param str remotepath: path to list on the server :returns: (list of SFTPAttributes), sorted """ self._sftp_connect() return sorted(self._sftp.listdir_attr(remotepath), key=lambda attr: attr.filename) def mkdir(self, remotepath, mode=777): """Create a directory named remotepath with mode. On some systems, mode is ignored. Where it is used, the current umask value is first masked out. :param str remotepath: directory to create` :param int mode: *Default: 777* - int representation of octal mode for directory :returns: None """ self._sftp_connect() self._sftp.mkdir(remotepath, mode=int(str(mode), 8)) def normalize(self, remotepath): """Return the expanded path, w.r.t the server, of a given path. This can be used to resolve symlinks or determine what the server believes to be the :attr:`.pwd`, by passing '.' as remotepath. :param str remotepath: path to be normalized :return: (str) normalized form of the given path :raises: IOError, if remotepath can't be resolved """ self._sftp_connect() return self._sftp.normalize(remotepath) def isdir(self, remotepath): """return true, if remotepath is a directory :param str remotepath: the path to test :returns: (bool) """ self._sftp_connect() try: result = S_ISDIR(self._sftp.stat(remotepath).st_mode) except IOError: # no such file result = False return result def isfile(self, remotepath): """return true if remotepath is a file :param str remotepath: the path to test :returns: (bool) """ self._sftp_connect() try: result = S_ISREG(self._sftp.stat(remotepath).st_mode) except IOError: # no such file result = False return result def makedirs(self, remotedir, mode=777): """create all directories in remotedir as needed, setting their mode to mode, if created. If remotedir already exists, silently complete. If a regular file is in the way, raise an exception. :param str remotedir: the directory structure to create :param int mode: *Default: 777* - int representation of octal mode for directory :returns: None :raises: OSError """ self._sftp_connect() if self.isdir(remotedir): pass elif self.isfile(remotedir): raise OSError("a file with the same name as the remotedir, " \ "'%s', already exists." % remotedir) else: head, tail = os.path.split(remotedir) if head and not self.isdir(head): self.makedirs(head, mode) if tail: self.mkdir(remotedir, mode=mode) def readlink(self, remotelink): """Return the target of a symlink (shortcut). The result will be an absolute pathname. :param str remotelink: remote path of the symlink :return: (str) absolute path to target """ self._sftp_connect() return self._sftp.normalize(self._sftp.readlink(remotelink)) def remove(self, remotefile): """remove the file @ remotefile, remotefile may include a path, if no path, then :attr:`.pwd` is used. This method only works on files :param str remotefile: the remote file to delete :returns: None :raises: IOError """ self._sftp_connect() self._sftp.remove(remotefile) unlink = remove # synonym for remove def rmdir(self, remotepath): """remove remote directory :param str remotepath: the remote directory to remove :returns: None """ self._sftp_connect() self._sftp.rmdir(remotepath) def rename(self, remote_src, remote_dest): """rename a file or directory on the remote host. :param str remote_src: the remote file/directory to rename :param str remote_dest: the remote file/directory to put it :returns: None :raises: IOError """ self._sftp_connect() self._sftp.rename(remote_src, remote_dest) def stat(self, remotepath): """return information about file/directory for the given remote path :param str remotepath: path to stat :returns: (obj) SFTPAttributes """ self._sftp_connect() return self._sftp.stat(remotepath) def lstat(self, remotepath): """return information about file/directory for the given remote path, without following symbolic links. Otherwise, the same as .stat() :param str remotepath: path to stat :returns: (obj) SFTPAttributes object """ self._sftp_connect() return self._sftp.lstat(remotepath) def close(self): """Closes the connection and cleans up.""" # Close SFTP Connection. if self._sftp_live: self._sftp.close() self._sftp_live = False # Close the SSH Transport. if self._transport_live: self._transport.close() self._transport_live = False def open(self, remote_file, mode='r', bufsize=-1): """Open a file on the remote server. See http://paramiko-docs.readthedocs.org/en/latest/api/sftp.html?highlight=open#paramiko.sftp_client.SFTPClient.open for details. :param str remote_file: name of the file to open. :param str mode: mode (Python-style) to open file (always assumed binary) :param int bufsize: *Default: -1* - desired buffering :returns: (obj) SFTPFile, a handle the remote open file :raises: IOError, if the file could not be opened. """ self._sftp_connect() return self._sftp.open(remote_file, mode=mode, bufsize=bufsize) def exists(self, remotepath): """Test whether a remotepath exists. :param str remotepath: the remote path to verify :returns: (bool) True, if remotepath exists, else False """ self._sftp_connect() try: self._sftp.stat(remotepath) except IOError: return False return True def lexists(self, remotepath): """Test whether a remotepath exists. Returns True for broken symbolic links :param str remotepath: the remote path to verify :returns: (bool), True, if lexists, else False """ self._sftp_connect() try: self._sftp.lstat(remotepath) except IOError: return False return True def symlink(self, remote_src, remote_dest): '''create a symlink for a remote file on the server :param str remote_src: path of original file :param str remote_dest: path of the created symlink :returns: None :raises: any underlying error, IOError if something already exists at remote_dest ''' self._sftp_connect() self._sftp.symlink(remote_src, remote_dest) def truncate(self, remotepath, size): """Change the size of the file specified by path. Used to modify the size of the file, just like the truncate method on Python file objects. The new file size is confirmed and returned. :param str remotepath: remote file path to modify :param int|long size: the new file size :returns: (int) new size of file :raises: IOError, if file does not exist """ self._sftp_connect() self._sftp.truncate(remotepath, size) return self._sftp.stat(remotepath).st_size def walktree(self, remotepath, fcallback, dcallback, ucallback, recurse=True): '''recursively descend, depth first, the directory tree rooted at remotepath, calling discreet callback functions for each regular file, directory and unknown file type. :param str remotepath: root of remote directory to descend, use '.' to start at :attr:`.pwd` :param callable fcallback: callback function to invoke for a regular file. (form: ``func(str)``) :param callable dcallback: callback function to invoke for a directory. (form: ``func(str)``) :param callable ucallback: callback function to invoke for an unknown file type. (form: ``func(str)``) :param bool recurse: *Default: True* - should it recurse :returns: None :raises: ''' self._sftp_connect() for entry in self._sftp.listdir(remotepath): pathname = os.path.join(remotepath, entry) mode = self._sftp.stat(pathname).st_mode if S_ISDIR(mode): # It's a directory, call the dcallback function dcallback(pathname) if recurse: # now, recurse into it self.walktree(pathname, fcallback, dcallback, ucallback) elif S_ISREG(mode): # It's a file, call the fcallback function fcallback(pathname) else: # Unknown file type ucallback(pathname) @property def sftp_client(self): """give access to the underlying, connected paramiko SFTPClient object see http://paramiko-docs.readthedocs.org/en/latest/api/sftp.html?highlight=sftpclient :params: None :returns: (obj) the active SFTPClient object """ self._sftp_connect() return self._sftp @property def active_ciphers(self): """Get tuple of currently used local and remote ciphers. :returns: (tuple of str) currently used ciphers (local_cipher, remote_cipher) """ return self._transport.local_cipher, self._transport.remote_cipher @property def security_options(self): """return the available security options recognized by paramiko. :returns: (obj) security preferences of the ssh transport. These are tuples of acceptable `.ciphers`, `.digests`, `.key_types`, and key exchange algorithms `.kex`, listed in order of preference. """ return self._transport.get_security_options() @property def logfile(self): '''return the name of the file used for logging or False it not logging :returns: (str)logfile or (bool) False ''' return self._logfile @property def timeout(self): ''' (float|None) *Default: None* - get or set the underlying socket timeout for pending read/write ops. :returns: (float|None) seconds to wait for a pending read/write operation before raising socket.timeout, or None for no timeout ''' self._sftp_connect() channel = self._sftp.get_channel() return channel.gettimeout() @timeout.setter def timeout(self, val): '''setter for timeout''' self._sftp_connect() channel = self._sftp.get_channel() channel.settimeout(val) def __del__(self): """Attempt to clean up if not explicitly closed.""" self.close() def __enter__(self): return self def __exit__(self, etype, value, traceback): self.close() def path_advance(thepath, sep=os.sep): '''generator to iterate over a file path forwards :param str thepath: the path to navigate forwards :param str sep: *Default: os.sep* - the path separator to use :returns: (iter)able of strings ''' # handle a direct path pre = '' if thepath[0] == sep: pre = sep curpath = '' parts = thepath.split(sep) if pre: if parts[0]: parts[0] = pre + parts[0] else: parts[1] = pre + parts[1] for part in parts: curpath = os.path.join(curpath, part) if curpath: yield curpath def path_retreat(thepath, sep=os.sep): '''generator to iterate over a file path in reverse :param str thepath: the path to retreat over :param str sep: *Default: os.sep* - the path separator to use :returns: (iter)able of strings ''' pre = '' if thepath[0] == sep: pre = sep parts = thepath.split(sep) while parts: if os.path.join(*parts): yield '%s%s' % (pre, os.path.join(*parts)) parts = parts[:-1] def reparent(newparent, oldpath): '''when copying or moving a directory structure, you need to re-parent the oldpath. When using os.path.join to calculate this new path, the appearance of a / root path at the beginning of oldpath, supplants the newparent and we don't want this to happen, so we need to make the oldpath root appear as a child of the newparent. :param: str newparent: the new parent location for oldpath (target) :param str oldpath: the path being adopted by newparent (source) :returns: (str) resulting adoptive path ''' if oldpath[0] == os.sep: oldpath = '.' + oldpath return os.path.join(newparent, oldpath) def walktree(localpath, fcallback, dcallback, ucallback, recurse=True): '''on the local file system, recursively descend, depth first, the directory tree rooted at localpath, calling discreet callback functions for each regular file, directory and unknown file type. :param str localpath: root of remote directory to descend, use '.' to start at :attr:`.pwd` :param callable fcallback: callback function to invoke for a regular file. (form: ``func(str)``) :param callable dcallback: callback function to invoke for a directory. (form: ``func(str)``) :param callable ucallback: callback function to invoke for an unknown file type. (form: ``func(str)``) :param bool recurse: *Default: True* - should it recurse :returns: None :raises: OSError, if localpath doesn't exist ''' for entry in os.listdir(localpath): pathname = os.path.join(localpath, entry) mode = os.stat(pathname).st_mode if S_ISDIR(mode): # It's a directory, call the dcallback function dcallback(pathname) if recurse: # now, recurse into it walktree(pathname, fcallback, dcallback, ucallback) elif S_ISREG(mode): # It's a file, call the fcallback function fcallback(pathname) else: # Unknown file type ucallback(pathname) @contextmanager def cd(localpath=None): """context manager that can change to a optionally specified local directory and restores the old pwd on exit. :param str|None localpath: *Default: None* - local path to temporarily make the current directory :returns: None :raises: OSError, if local path doesn't exist """ try: original_path = os.getcwd() if localpath is not None: os.chdir(localpath) yield finally: os.chdir(original_path)
{ "repo_name": "midma101/m0du1ar", "path": ".venv/lib/python2.7/site-packages/pysftp.py", "copies": "2", "size": "36938", "license": "mit", "hash": 506225220826612030, "line_mean": 32.7333333333, "line_max": 137, "alpha_frac": 0.5974064649, "autogenerated": false, "ratio": 4.38433234421365, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.598173880911365, "avg_score": null, "num_lines": null }
# A frontend for yay0 decoder import os, tempfile, logging import yay0, N64img paletteFormats = [ "ci4", "ci8"] paletteSizes = {"ci8":512, "ci4":32} #TODO: Extend with other support formats with palette. log = logging.getLogger("frontend") def parseFilename(fileName): # Ignore any leading directory paths fileName = os.path.basename(fileName) ext = os.path.splitext(fileName)[-1][1:] title, dimensions = (os.path.splitext(fileName)[-2]).split('.') width, height = dimensions.split('x') width = int(width) height = int(height) return (title, dimensions, width, height, ext) def getPaletteFileName(fn): """ Return the palette file name. Assumes the palette file is located in the same directory with extension .pal and same file title but without dimensions. """ dirname = os.path.dirname(fn) title = parseFilename(fn)[0] return os.path.join(dirname,title+".pal") def getPngFileName(fn): (title, dim, w, h, ext) = parseFilename(fn) return title+"."+dim+".png" def processSingleFileImage(fn): with open(fn, "rb") as imageFile: imagedata = imageFile.read() (title, dim, w, h, ext) = parseFilename(fn) if(ext in paletteFormats): palSize = paletteSizes.get(ext, 0) paldata = imagedata[:palSize] imagedata = imagedata[palSize:] else: paldata = None # Decompress image data if necessary if(b"Yay0" == imagedata[:0x04]): log.info ("Yay!!! Found yay0") imagedata = yay0.yay0Dec(imagedata) # Convert to PNG fd,tmpFilePath = tempfile.mkstemp() os.close(fd) N64img.img('png', 'out', cmd=ext, img=imagedata, pal=paldata, width=w, height=h, name=tmpFilePath) return tmpFilePath def processMultiFileImage(fn): with open(fn, "rb") as imageFile: imagedata = imageFile.read() # Check for header and decompress if necessary if(b"Yay0" == imagedata[:0x04]): log.info ("Yay!!! Found yay0") imagedata = yay0.yay0Dec(imagedata) (title, dim, w, h, ext) = parseFilename(fn) # Strip trailing 'y' from extension for backwards compatibility. if 'y' == ext[-1]: ext = ext[:-1] if(ext in paletteFormats): pfn = getPaletteFileName(fn) log.info(("Opening palette file %s" % pfn)) with open(pfn, "rb") as palFile: paldata = palFile.read() else: paldata = None # Convert to PNG fd,tmpFilePath = tempfile.mkstemp() os.close(fd) N64img.img('png', 'out', cmd=ext, img=imagedata, pal=paldata, width=w, height=h, name=tmpFilePath) return tmpFilePath def main(): infilename = "game_over.256x32.ci8y" tmpfilename = processMultiFileImage(infilename) outfilename = getPngFileName(infilename) os.rename(tmpfilename, outfilename) if __name__ == '__main__': main()
{ "repo_name": "madhuri2k/fantastic-spoon", "path": "yay0/frontend.py", "copies": "1", "size": "2884", "license": "mit", "hash": -1766181601700820700, "line_mean": 29.6808510638, "line_max": 76, "alpha_frac": 0.6386962552, "autogenerated": false, "ratio": 3.3730994152046785, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4511795670404678, "avg_score": null, "num_lines": null }
"""A FrontendWidget that emulates a repl for a Jupyter kernel. This supports the additional functionality provided by Jupyter kernel. """ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from collections import namedtuple import os.path import re from subprocess import Popen import sys import time from textwrap import dedent from qtconsole.qt import QtCore, QtGui from IPython.lib.lexers import IPythonLexer, IPython3Lexer from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound from qtconsole import __version__ from traitlets import Bool, Unicode from .frontend_widget import FrontendWidget from . import styles #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- # Default strings to build and display input and output prompts (and separators # in between) default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' default_input_sep = '\n' default_output_sep = '' default_output_sep2 = '' # Base path for most payload sources. zmq_shell_source = 'ipykernel.zmqshell.ZMQInteractiveShell' if sys.platform.startswith('win'): default_editor = 'notepad' else: default_editor = '' #----------------------------------------------------------------------------- # JupyterWidget class #----------------------------------------------------------------------------- class IPythonWidget(FrontendWidget): """Dummy class for config inheritance. Destroyed below.""" class JupyterWidget(IPythonWidget): """A FrontendWidget for a Jupyter kernel.""" # If set, the 'custom_edit_requested(str, int)' signal will be emitted when # an editor is needed for a file. This overrides 'editor' and 'editor_line' # settings. custom_edit = Bool(False) custom_edit_requested = QtCore.Signal(object, object) editor = Unicode(default_editor, config=True, help=""" A command for invoking a system text editor. If the string contains a {filename} format specifier, it will be used. Otherwise, the filename will be appended to the end the command. """) editor_line = Unicode(config=True, help=""" The editor command to use when a specific line number is requested. The string should contain two format specifiers: {line} and {filename}. If this parameter is not specified, the line number option to the %edit magic will be ignored. """) style_sheet = Unicode(config=True, help=""" A CSS stylesheet. The stylesheet can contain classes for: 1. Qt: QPlainTextEdit, QFrame, QWidget, etc 2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) 3. QtConsole: .error, .in-prompt, .out-prompt, etc """) syntax_style = Unicode(config=True, help=""" If not empty, use this Pygments style for syntax highlighting. Otherwise, the style sheet is queried for Pygments style information. """) # Prompts. in_prompt = Unicode(default_in_prompt, config=True) out_prompt = Unicode(default_out_prompt, config=True) input_sep = Unicode(default_input_sep, config=True) output_sep = Unicode(default_output_sep, config=True) output_sep2 = Unicode(default_output_sep2, config=True) # JupyterWidget protected class variables. _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number']) _payload_source_edit = 'edit_magic' _payload_source_exit = 'ask_exit' _payload_source_next_input = 'set_next_input' _payload_source_page = 'page' _retrying_history_request = False _starting = False #--------------------------------------------------------------------------- # 'object' interface #--------------------------------------------------------------------------- def __init__(self, *args, **kw): super(JupyterWidget, self).__init__(*args, **kw) # JupyterWidget protected variables. self._payload_handlers = { self._payload_source_edit : self._handle_payload_edit, self._payload_source_exit : self._handle_payload_exit, self._payload_source_page : self._handle_payload_page, self._payload_source_next_input : self._handle_payload_next_input } self._previous_prompt_obj = None self._keep_kernel_on_exit = None # Initialize widget styling. if self.style_sheet: self._style_sheet_changed() self._syntax_style_changed() else: self.set_default_style() #--------------------------------------------------------------------------- # 'BaseFrontendMixin' abstract interface # # For JupyterWidget, override FrontendWidget methods which implement the # BaseFrontend Mixin abstract interface #--------------------------------------------------------------------------- def _handle_complete_reply(self, rep): """Support Jupyter's improved completion machinery. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): content = rep['content'] matches = content['matches'] start = content['cursor_start'] end = content['cursor_end'] start = max(start, 0) end = max(end, start) # Move the control's cursor to the desired end point cursor_pos = self._get_input_buffer_cursor_pos() if end < cursor_pos: cursor.movePosition(QtGui.QTextCursor.Left, n=(cursor_pos - end)) elif end > cursor_pos: cursor.movePosition(QtGui.QTextCursor.Right, n=(end - cursor_pos)) # This line actually applies the move to control's cursor self._control.setTextCursor(cursor) offset = end - start # Move the local cursor object to the start of the match and # complete. cursor.movePosition(QtGui.QTextCursor.Left, n=offset) self._complete_with_items(cursor, matches) def _handle_execute_reply(self, msg): """Support prompt requests. """ msg_id = msg['parent_header'].get('msg_id') info = self._request_info['execute'].get(msg_id) if info and info.kind == 'prompt': content = msg['content'] if content['status'] == 'aborted': self._show_interpreter_prompt() else: number = content['execution_count'] + 1 self._show_interpreter_prompt(number) self._request_info['execute'].pop(msg_id) else: super(JupyterWidget, self)._handle_execute_reply(msg) def _handle_history_reply(self, msg): """ Handle history tail replies, which are only supported by Jupyter kernels. """ content = msg['content'] if 'history' not in content: self.log.error("History request failed: %r"%content) if content.get('status', '') == 'aborted' and \ not self._retrying_history_request: # a *different* action caused this request to be aborted, so # we should try again. self.log.error("Retrying aborted history request") # prevent multiple retries of aborted requests: self._retrying_history_request = True # wait out the kernel's queue flush, which is currently timed at 0.1s time.sleep(0.25) self.kernel_client.history(hist_access_type='tail',n=1000) else: self._retrying_history_request = False return # reset retry flag self._retrying_history_request = False history_items = content['history'] self.log.debug("Received history reply with %i entries", len(history_items)) items = [] last_cell = u"" for _, _, cell in history_items: cell = cell.rstrip() if cell != last_cell: items.append(cell) last_cell = cell self._set_history(items) def _insert_other_input(self, cursor, content): """Insert function for input from other frontends""" cursor.beginEditBlock() start = cursor.position() n = content.get('execution_count', 0) cursor.insertText('\n') self._insert_html(cursor, self._make_in_prompt(n)) cursor.insertText(content['code']) self._highlighter.rehighlightBlock(cursor.block()) cursor.endEditBlock() def _handle_execute_input(self, msg): """Handle an execute_input message""" self.log.debug("execute_input: %s", msg.get('content', '')) if self.include_output(msg): self._append_custom(self._insert_other_input, msg['content'], before_prompt=True) def _handle_execute_result(self, msg): """Handle an execute_result message""" if self.include_output(msg): self.flush_clearoutput() content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if 'text/plain' in data: self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) text = data['text/plain'] # If the repr is multiline, make sure we start on a new line, # so that its lines are aligned. if "\n" in text and not self.output_sep.endswith("\n"): self._append_plain_text('\n', True) self._append_plain_text(text + self.output_sep2, True) def _handle_display_data(self, msg): """The base handler for the ``display_data`` message.""" # For now, we don't display data from other frontends, but we # eventually will as this allows all frontends to monitor the display # data. But we need to figure out how to handle this in the GUI. if self.include_output(msg): self.flush_clearoutput() data = msg['content']['data'] metadata = msg['content']['metadata'] # In the regular JupyterWidget, we simply print the plain text # representation. if 'text/plain' in data: text = data['text/plain'] self._append_plain_text(text, True) # This newline seems to be needed for text and html output. self._append_plain_text(u'\n', True) def _handle_kernel_info_reply(self, rep): """Handle kernel info replies.""" content = rep['content'] language_name = content['language_info']['name'] pygments_lexer = content['language_info'].get('pygments_lexer', '') try: # Other kernels with pygments_lexer info will have to be # added here by hand. if pygments_lexer == 'ipython3': lexer = IPython3Lexer() elif pygments_lexer == 'ipython2': lexer = IPythonLexer() else: lexer = get_lexer_by_name(language_name) self._highlighter._lexer = lexer except ClassNotFound: pass self.kernel_banner = content.get('banner', '') if self._starting: # finish handling started channels self._starting = False super(JupyterWidget, self)._started_channels() def _started_channels(self): """Make a history request""" self._starting = True self.kernel_client.kernel_info() self.kernel_client.history(hist_access_type='tail', n=1000) #--------------------------------------------------------------------------- # 'FrontendWidget' protected interface #--------------------------------------------------------------------------- def _process_execute_error(self, msg): """Handle an execute_error message""" content = msg['content'] traceback = '\n'.join(content['traceback']) + '\n' if False: # FIXME: For now, tracebacks come as plain text, so we can't # use the html renderer yet. Once we refactor ultratb to # produce properly styled tracebacks, this branch should be the # default traceback = traceback.replace(' ', '&nbsp;') traceback = traceback.replace('\n', '<br/>') ename = content['ename'] ename_styled = '<span class="error">%s</span>' % ename traceback = traceback.replace(ename, ename_styled) self._append_html(traceback) else: # This is the fallback for now, using plain text with ansi # escapes self._append_plain_text(traceback) def _process_execute_payload(self, item): """ Reimplemented to dispatch payloads to handler methods. """ handler = self._payload_handlers.get(item['source']) if handler is None: # We have no handler for this type of payload, simply ignore it return False else: handler(item) return True def _show_interpreter_prompt(self, number=None): """ Reimplemented for IPython-style prompts. """ # If a number was not specified, make a prompt number request. if number is None: msg_id = self.kernel_client.execute('', silent=True) info = self._ExecutionRequest(msg_id, 'prompt') self._request_info['execute'][msg_id] = info return # Show a new prompt and save information about it so that it can be # updated later if the prompt number turns out to be wrong. self._prompt_sep = self.input_sep self._show_prompt(self._make_in_prompt(number), html=True) block = self._control.document().lastBlock() length = len(self._prompt) self._previous_prompt_obj = self._PromptBlock(block, length, number) # Update continuation prompt to reflect (possibly) new prompt length. self._set_continuation_prompt( self._make_continuation_prompt(self._prompt), html=True) def _show_interpreter_prompt_for_reply(self, msg): """ Reimplemented for IPython-style prompts. """ # Update the old prompt number if necessary. content = msg['content'] # abort replies do not have any keys: if content['status'] == 'aborted': if self._previous_prompt_obj: previous_prompt_number = self._previous_prompt_obj.number else: previous_prompt_number = 0 else: previous_prompt_number = content['execution_count'] if self._previous_prompt_obj and \ self._previous_prompt_obj.number != previous_prompt_number: block = self._previous_prompt_obj.block # Make sure the prompt block has not been erased. if block.isValid() and block.text(): # Remove the old prompt and insert a new prompt. cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, self._previous_prompt_obj.length) prompt = self._make_in_prompt(previous_prompt_number) self._prompt = self._insert_html_fetching_plain_text( cursor, prompt) # When the HTML is inserted, Qt blows away the syntax # highlighting for the line, so we need to rehighlight it. self._highlighter.rehighlightBlock(cursor.block()) self._previous_prompt_obj = None # Show a new prompt with the kernel's estimated prompt number. self._show_interpreter_prompt(previous_prompt_number + 1) #--------------------------------------------------------------------------- # 'JupyterWidget' interface #--------------------------------------------------------------------------- def set_default_style(self, colors='lightbg'): """ Sets the widget style to the class defaults. Parameters ---------- colors : str, optional (default lightbg) Whether to use the default light background or dark background or B&W style. """ colors = colors.lower() if colors=='lightbg': self.style_sheet = styles.default_light_style_sheet self.syntax_style = styles.default_light_syntax_style elif colors=='linux': self.style_sheet = styles.default_dark_style_sheet self.syntax_style = styles.default_dark_syntax_style elif colors=='nocolor': self.style_sheet = styles.default_bw_style_sheet self.syntax_style = styles.default_bw_syntax_style else: raise KeyError("No such color scheme: %s"%colors) #--------------------------------------------------------------------------- # 'JupyterWidget' protected interface #--------------------------------------------------------------------------- def _edit(self, filename, line=None): """ Opens a Python script for editing. Parameters ---------- filename : str A path to a local system file. line : int, optional A line of interest in the file. """ if self.custom_edit: self.custom_edit_requested.emit(filename, line) elif not self.editor: self._append_plain_text('No default editor available.\n' 'Specify a GUI text editor in the `JupyterWidget.editor` ' 'configurable to enable the %edit magic') else: try: filename = '"%s"' % filename if line and self.editor_line: command = self.editor_line.format(filename=filename, line=line) else: try: command = self.editor.format() except KeyError: command = self.editor.format(filename=filename) else: command += ' ' + filename except KeyError: self._append_plain_text('Invalid editor command.\n') else: try: Popen(command, shell=True) except OSError: msg = 'Opening editor with command "%s" failed.\n' self._append_plain_text(msg % command) def _make_in_prompt(self, number): """ Given a prompt number, returns an HTML In prompt. """ try: body = self.in_prompt % number except TypeError: # allow in_prompt to leave out number, e.g. '>>> ' from xml.sax.saxutils import escape body = escape(self.in_prompt) return '<span class="in-prompt">%s</span>' % body def _make_continuation_prompt(self, prompt): """ Given a plain text version of an In prompt, returns an HTML continuation prompt. """ end_chars = '...: ' space_count = len(prompt.lstrip('\n')) - len(end_chars) body = '&nbsp;' * space_count + end_chars return '<span class="in-prompt">%s</span>' % body def _make_out_prompt(self, number): """ Given a prompt number, returns an HTML Out prompt. """ try: body = self.out_prompt % number except TypeError: # allow out_prompt to leave out number, e.g. '<<< ' from xml.sax.saxutils import escape body = escape(self.out_prompt) return '<span class="out-prompt">%s</span>' % body #------ Payload handlers -------------------------------------------------- # Payload handlers with a generic interface: each takes the opaque payload # dict, unpacks it and calls the underlying functions with the necessary # arguments. def _handle_payload_edit(self, item): self._edit(item['filename'], item['line_number']) def _handle_payload_exit(self, item): self._keep_kernel_on_exit = item['keepkernel'] self.exit_requested.emit(self) def _handle_payload_next_input(self, item): self.input_buffer = item['text'] def _handle_payload_page(self, item): # Since the plain text widget supports only a very small subset of HTML # and we have no control over the HTML source, we only page HTML # payloads in the rich text widget. data = item['data'] if 'text/html' in data and self.kind == 'rich': self._page(data['text/html'], html=True) else: self._page(data['text/plain'], html=False) #------ Trait change handlers -------------------------------------------- def _style_sheet_changed(self): """ Set the style sheets of the underlying widgets. """ self.setStyleSheet(self.style_sheet) if self._control is not None: self._control.document().setDefaultStyleSheet(self.style_sheet) if self._page_control is not None: self._page_control.document().setDefaultStyleSheet(self.style_sheet) def _syntax_style_changed(self): """ Set the style for the syntax highlighter. """ if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter.set_style(self.syntax_style) self._ansi_processor.set_background_color(self.syntax_style) else: self._highlighter.set_style_sheet(self.style_sheet) #------ Trait default initializers ----------------------------------------- def _banner_default(self): return "Jupyter QtConsole {version}\n".format(version=__version__) # clobber IPythonWidget above: class IPythonWidget(JupyterWidget): """Deprecated class. Use JupyterWidget""" def __init__(self, *a, **kw): warn("IPythonWidget is deprecated, use JupyterWidget") super(IPythonWidget, self).__init__(*a, **kw)
{ "repo_name": "unnikrishnankgs/va", "path": "venv/lib/python3.5/site-packages/qtconsole/jupyter_widget.py", "copies": "3", "size": "22844", "license": "bsd-2-clause", "hash": 7202389712455812000, "line_mean": 39.3604240283, "line_max": 93, "alpha_frac": 0.5551129399, "autogenerated": false, "ratio": 4.4977357747588105, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.004303857591250089, "num_lines": 566 }
""" A FrontendWidget that emulates the interface of the console IPython and supports the additional functionality provided by the IPython kernel. """ #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports from collections import namedtuple import os.path import re from subprocess import Popen import sys import time from textwrap import dedent # System library imports from IPython.external.qt import QtCore, QtGui # Local imports from IPython.core.inputsplitter import IPythonInputSplitter, \ transform_ipy_prompt from IPython.utils.traitlets import Bool, Unicode from frontend_widget import FrontendWidget import styles #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- # Default strings to build and display input and output prompts (and separators # in between) default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' default_input_sep = '\n' default_output_sep = '' default_output_sep2 = '' # Base path for most payload sources. zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell' if sys.platform.startswith('win'): default_editor = 'notepad' else: default_editor = '' #----------------------------------------------------------------------------- # IPythonWidget class #----------------------------------------------------------------------------- class IPythonWidget(FrontendWidget): """ A FrontendWidget for an IPython kernel. """ # If set, the 'custom_edit_requested(str, int)' signal will be emitted when # an editor is needed for a file. This overrides 'editor' and 'editor_line' # settings. custom_edit = Bool(False) custom_edit_requested = QtCore.Signal(object, object) editor = Unicode(default_editor, config=True, help=""" A command for invoking a system text editor. If the string contains a {filename} format specifier, it will be used. Otherwise, the filename will be appended to the end the command. """) editor_line = Unicode(config=True, help=""" The editor command to use when a specific line number is requested. The string should contain two format specifiers: {line} and {filename}. If this parameter is not specified, the line number option to the %edit magic will be ignored. """) style_sheet = Unicode(config=True, help=""" A CSS stylesheet. The stylesheet can contain classes for: 1. Qt: QPlainTextEdit, QFrame, QWidget, etc 2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) 3. IPython: .error, .in-prompt, .out-prompt, etc """) syntax_style = Unicode(config=True, help=""" If not empty, use this Pygments style for syntax highlighting. Otherwise, the style sheet is queried for Pygments style information. """) # Prompts. in_prompt = Unicode(default_in_prompt, config=True) out_prompt = Unicode(default_out_prompt, config=True) input_sep = Unicode(default_input_sep, config=True) output_sep = Unicode(default_output_sep, config=True) output_sep2 = Unicode(default_output_sep2, config=True) # FrontendWidget protected class variables. _input_splitter_class = IPythonInputSplitter _transform_prompt = staticmethod(transform_ipy_prompt) # IPythonWidget protected class variables. _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number']) _payload_source_edit = zmq_shell_source + '.edit_magic' _payload_source_exit = zmq_shell_source + '.ask_exit' _payload_source_next_input = zmq_shell_source + '.set_next_input' _payload_source_page = 'IPython.zmq.page.page' _retrying_history_request = False #--------------------------------------------------------------------------- # 'object' interface #--------------------------------------------------------------------------- def __init__(self, *args, **kw): super(IPythonWidget, self).__init__(*args, **kw) # IPythonWidget protected variables. self._payload_handlers = { self._payload_source_edit : self._handle_payload_edit, self._payload_source_exit : self._handle_payload_exit, self._payload_source_page : self._handle_payload_page, self._payload_source_next_input : self._handle_payload_next_input } self._previous_prompt_obj = None self._keep_kernel_on_exit = None # Initialize widget styling. if self.style_sheet: self._style_sheet_changed() self._syntax_style_changed() else: self.set_default_style() #--------------------------------------------------------------------------- # 'BaseFrontendMixin' abstract interface #--------------------------------------------------------------------------- def _handle_complete_reply(self, rep): """ Reimplemented to support IPython's improved completion machinery. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): matches = rep['content']['matches'] text = rep['content']['matched_text'] offset = len(text) # Clean up matches with period and path separators if the matched # text has not been transformed. This is done by truncating all # but the last component and then suitably decreasing the offset # between the current cursor position and the start of completion. if len(matches) > 1 and matches[0][:offset] == text: parts = re.split(r'[./\\]', text) sep_count = len(parts) - 1 if sep_count: chop_length = sum(map(len, parts[:sep_count])) + sep_count matches = [ match[chop_length:] for match in matches ] offset -= chop_length # Move the cursor to the start of the match and complete. cursor.movePosition(QtGui.QTextCursor.Left, n=offset) self._complete_with_items(cursor, matches) def _handle_execute_reply(self, msg): """ Reimplemented to support prompt requests. """ msg_id = msg['parent_header'].get('msg_id') info = self._request_info['execute'].get(msg_id) if info and info.kind == 'prompt': number = msg['content']['execution_count'] + 1 self._show_interpreter_prompt(number) self._request_info['execute'].pop(msg_id) else: super(IPythonWidget, self)._handle_execute_reply(msg) def _handle_history_reply(self, msg): """ Implemented to handle history tail replies, which are only supported by the IPython kernel. """ content = msg['content'] if 'history' not in content: self.log.error("History request failed: %r"%content) if content.get('status', '') == 'aborted' and \ not self._retrying_history_request: # a *different* action caused this request to be aborted, so # we should try again. self.log.error("Retrying aborted history request") # prevent multiple retries of aborted requests: self._retrying_history_request = True # wait out the kernel's queue flush, which is currently timed at 0.1s time.sleep(0.25) self.kernel_manager.shell_channel.history(hist_access_type='tail',n=1000) else: self._retrying_history_request = False return # reset retry flag self._retrying_history_request = False history_items = content['history'] self.log.debug("Received history reply with %i entries", len(history_items)) items = [] last_cell = u"" for _, _, cell in history_items: cell = cell.rstrip() if cell != last_cell: items.append(cell) last_cell = cell self._set_history(items) def _handle_pyout(self, msg): """ Reimplemented for IPython-style "display hook". """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if data.has_key('text/html'): self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) html = data['text/html'] self._append_plain_text('\n', True) self._append_html(html + self.output_sep2, True) elif data.has_key('text/plain'): self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) text = data['text/plain'] # If the repr is multiline, make sure we start on a new line, # so that its lines are aligned. if "\n" in text and not self.output_sep.endswith("\n"): self._append_plain_text('\n', True) self._append_plain_text(text + self.output_sep2, True) def _handle_display_data(self, msg): """ The base handler for the ``display_data`` message. """ self.log.debug("display: %s", msg.get('content', '')) # For now, we don't display data from other frontends, but we # eventually will as this allows all frontends to monitor the display # data. But we need to figure out how to handle this in the GUI. if not self._hidden and self._is_from_this_session(msg): source = msg['content']['source'] data = msg['content']['data'] metadata = msg['content']['metadata'] # In the regular IPythonWidget, we simply print the plain text # representation. if data.has_key('text/html'): html = data['text/html'] self._append_html(html, True) elif data.has_key('text/plain'): text = data['text/plain'] self._append_plain_text(text, True) # This newline seems to be needed for text and html output. self._append_plain_text(u'\n', True) def _started_channels(self): """Reimplemented to make a history request and load %guiref.""" super(IPythonWidget, self)._started_channels() self._load_guiref_magic() self.kernel_manager.shell_channel.history(hist_access_type='tail', n=1000) def _started_kernel(self): """Load %guiref when the kernel starts (if channels are also started). Principally triggered by kernel restart. """ if self.kernel_manager.shell_channel is not None: self._load_guiref_magic() def _load_guiref_magic(self): """Load %guiref magic.""" self.kernel_manager.shell_channel.execute('\n'.join([ "from IPython.core import usage", "get_ipython().register_magic_function(usage.page_guiref, 'line', 'guiref')", ]), silent=True) #--------------------------------------------------------------------------- # 'ConsoleWidget' public interface #--------------------------------------------------------------------------- #--------------------------------------------------------------------------- # 'FrontendWidget' public interface #--------------------------------------------------------------------------- def execute_file(self, path, hidden=False): """ Reimplemented to use the 'run' magic. """ # Use forward slashes on Windows to avoid escaping each separator. if sys.platform == 'win32': path = os.path.normpath(path).replace('\\', '/') # Perhaps we should not be using %run directly, but while we # are, it is necessary to quote or escape filenames containing spaces # or quotes. # In earlier code here, to minimize escaping, we sometimes quoted the # filename with single quotes. But to do this, this code must be # platform-aware, because run uses shlex rather than python string # parsing, so that: # * In Win: single quotes can be used in the filename without quoting, # and we cannot use single quotes to quote the filename. # * In *nix: we can escape double quotes in a double quoted filename, # but can't escape single quotes in a single quoted filename. # So to keep this code non-platform-specific and simple, we now only # use double quotes to quote filenames, and escape when needed: if ' ' in path or "'" in path or '"' in path: path = '"%s"' % path.replace('"', '\\"') self.execute('%%run %s' % path, hidden=hidden) #--------------------------------------------------------------------------- # 'FrontendWidget' protected interface #--------------------------------------------------------------------------- def _complete(self): """ Reimplemented to support IPython's improved completion machinery. """ # We let the kernel split the input line, so we *always* send an empty # text field. Readline-based frontends do get a real text field which # they can use. text = '' # Send the completion request to the kernel msg_id = self.kernel_manager.shell_channel.complete( text, # text self._get_input_buffer_cursor_line(), # line self._get_input_buffer_cursor_column(), # cursor_pos self.input_buffer) # block pos = self._get_cursor().position() info = self._CompletionRequest(msg_id, pos) self._request_info['complete'] = info def _process_execute_error(self, msg): """ Reimplemented for IPython-style traceback formatting. """ content = msg['content'] traceback = '\n'.join(content['traceback']) + '\n' if False: # FIXME: For now, tracebacks come as plain text, so we can't use # the html renderer yet. Once we refactor ultratb to produce # properly styled tracebacks, this branch should be the default traceback = traceback.replace(' ', '&nbsp;') traceback = traceback.replace('\n', '<br/>') ename = content['ename'] ename_styled = '<span class="error">%s</span>' % ename traceback = traceback.replace(ename, ename_styled) self._append_html(traceback) else: # This is the fallback for now, using plain text with ansi escapes self._append_plain_text(traceback) def _process_execute_payload(self, item): """ Reimplemented to dispatch payloads to handler methods. """ handler = self._payload_handlers.get(item['source']) if handler is None: # We have no handler for this type of payload, simply ignore it return False else: handler(item) return True def _show_interpreter_prompt(self, number=None): """ Reimplemented for IPython-style prompts. """ # If a number was not specified, make a prompt number request. if number is None: msg_id = self.kernel_manager.shell_channel.execute('', silent=True) info = self._ExecutionRequest(msg_id, 'prompt') self._request_info['execute'][msg_id] = info return # Show a new prompt and save information about it so that it can be # updated later if the prompt number turns out to be wrong. self._prompt_sep = self.input_sep self._show_prompt(self._make_in_prompt(number), html=True) block = self._control.document().lastBlock() length = len(self._prompt) self._previous_prompt_obj = self._PromptBlock(block, length, number) # Update continuation prompt to reflect (possibly) new prompt length. self._set_continuation_prompt( self._make_continuation_prompt(self._prompt), html=True) def _show_interpreter_prompt_for_reply(self, msg): """ Reimplemented for IPython-style prompts. """ # Update the old prompt number if necessary. content = msg['content'] # abort replies do not have any keys: if content['status'] == 'aborted': if self._previous_prompt_obj: previous_prompt_number = self._previous_prompt_obj.number else: previous_prompt_number = 0 else: previous_prompt_number = content['execution_count'] if self._previous_prompt_obj and \ self._previous_prompt_obj.number != previous_prompt_number: block = self._previous_prompt_obj.block # Make sure the prompt block has not been erased. if block.isValid() and block.text(): # Remove the old prompt and insert a new prompt. cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, self._previous_prompt_obj.length) prompt = self._make_in_prompt(previous_prompt_number) self._prompt = self._insert_html_fetching_plain_text( cursor, prompt) # When the HTML is inserted, Qt blows away the syntax # highlighting for the line, so we need to rehighlight it. self._highlighter.rehighlightBlock(cursor.block()) self._previous_prompt_obj = None # Show a new prompt with the kernel's estimated prompt number. self._show_interpreter_prompt(previous_prompt_number + 1) #--------------------------------------------------------------------------- # 'IPythonWidget' interface #--------------------------------------------------------------------------- def set_default_style(self, colors='lightbg'): """ Sets the widget style to the class defaults. Parameters: ----------- colors : str, optional (default lightbg) Whether to use the default IPython light background or dark background or B&W style. """ colors = colors.lower() if colors=='lightbg': self.style_sheet = styles.default_light_style_sheet self.syntax_style = styles.default_light_syntax_style elif colors=='linux': self.style_sheet = styles.default_dark_style_sheet self.syntax_style = styles.default_dark_syntax_style elif colors=='nocolor': self.style_sheet = styles.default_bw_style_sheet self.syntax_style = styles.default_bw_syntax_style else: raise KeyError("No such color scheme: %s"%colors) #--------------------------------------------------------------------------- # 'IPythonWidget' protected interface #--------------------------------------------------------------------------- def _edit(self, filename, line=None): """ Opens a Python script for editing. Parameters: ----------- filename : str A path to a local system file. line : int, optional A line of interest in the file. """ if self.custom_edit: self.custom_edit_requested.emit(filename, line) elif not self.editor: self._append_plain_text('No default editor available.\n' 'Specify a GUI text editor in the `IPythonWidget.editor` ' 'configurable to enable the %edit magic') else: try: filename = '"%s"' % filename if line and self.editor_line: command = self.editor_line.format(filename=filename, line=line) else: try: command = self.editor.format() except KeyError: command = self.editor.format(filename=filename) else: command += ' ' + filename except KeyError: self._append_plain_text('Invalid editor command.\n') else: try: Popen(command, shell=True) except OSError: msg = 'Opening editor with command "%s" failed.\n' self._append_plain_text(msg % command) def _make_in_prompt(self, number): """ Given a prompt number, returns an HTML In prompt. """ try: body = self.in_prompt % number except TypeError: # allow in_prompt to leave out number, e.g. '>>> ' body = self.in_prompt return '<span class="in-prompt">%s</span>' % body def _make_continuation_prompt(self, prompt): """ Given a plain text version of an In prompt, returns an HTML continuation prompt. """ end_chars = '...: ' space_count = len(prompt.lstrip('\n')) - len(end_chars) body = '&nbsp;' * space_count + end_chars return '<span class="in-prompt">%s</span>' % body def _make_out_prompt(self, number): """ Given a prompt number, returns an HTML Out prompt. """ body = self.out_prompt % number return '<span class="out-prompt">%s</span>' % body #------ Payload handlers -------------------------------------------------- # Payload handlers with a generic interface: each takes the opaque payload # dict, unpacks it and calls the underlying functions with the necessary # arguments. def _handle_payload_edit(self, item): self._edit(item['filename'], item['line_number']) def _handle_payload_exit(self, item): self._keep_kernel_on_exit = item['keepkernel'] self.exit_requested.emit(self) def _handle_payload_next_input(self, item): self.input_buffer = dedent(item['text'].rstrip()) def _handle_payload_page(self, item): # Since the plain text widget supports only a very small subset of HTML # and we have no control over the HTML source, we only page HTML # payloads in the rich text widget. if item['html'] and self.kind == 'rich': self._page(item['html'], html=True) else: self._page(item['text'], html=False) #------ Trait change handlers -------------------------------------------- def _style_sheet_changed(self): """ Set the style sheets of the underlying widgets. """ self.setStyleSheet(self.style_sheet) if self._control is not None: self._control.document().setDefaultStyleSheet(self.style_sheet) bg_color = self._control.palette().window().color() self._ansi_processor.set_background_color(bg_color) if self._page_control is not None: self._page_control.document().setDefaultStyleSheet(self.style_sheet) def _syntax_style_changed(self): """ Set the style for the syntax highlighter. """ if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter.set_style(self.syntax_style) else: self._highlighter.set_style_sheet(self.style_sheet) #------ Trait default initializers ----------------------------------------- def _banner_default(self): from IPython.core.usage import default_gui_banner return default_gui_banner
{ "repo_name": "sodafree/backend", "path": "build/ipython/build/lib.linux-i686-2.7/IPython/frontend/qt/console/ipython_widget.py", "copies": "3", "size": "24582", "license": "bsd-3-clause", "hash": -8196675060815445000, "line_mean": 41.6031195841, "line_max": 89, "alpha_frac": 0.5474330811, "autogenerated": false, "ratio": 4.583628566101063, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6631061647201062, "avg_score": null, "num_lines": null }
"""A FrontendWidget that emulates the interface of the console IPython. This supports the additional functionality provided by the IPython kernel. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from collections import namedtuple import os.path import re from subprocess import Popen import sys import time from textwrap import dedent from IPython.external.qt import QtCore, QtGui from IPython.core.inputsplitter import IPythonInputSplitter from IPython.core.release import version from IPython.core.inputtransformer import ipy_prompt from IPython.utils.traitlets import Bool, Unicode from .frontend_widget import FrontendWidget from . import styles #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- # Default strings to build and display input and output prompts (and separators # in between) default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' default_input_sep = '\n' default_output_sep = '' default_output_sep2 = '' # Base path for most payload sources. zmq_shell_source = 'IPython.kernel.zmq.zmqshell.ZMQInteractiveShell' if sys.platform.startswith('win'): default_editor = 'notepad' else: default_editor = '' #----------------------------------------------------------------------------- # IPythonWidget class #----------------------------------------------------------------------------- class IPythonWidget(FrontendWidget): """ A FrontendWidget for an IPython kernel. """ # If set, the 'custom_edit_requested(str, int)' signal will be emitted when # an editor is needed for a file. This overrides 'editor' and 'editor_line' # settings. custom_edit = Bool(False) custom_edit_requested = QtCore.Signal(object, object) editor = Unicode(default_editor, config=True, help=""" A command for invoking a system text editor. If the string contains a {filename} format specifier, it will be used. Otherwise, the filename will be appended to the end the command. """) editor_line = Unicode(config=True, help=""" The editor command to use when a specific line number is requested. The string should contain two format specifiers: {line} and {filename}. If this parameter is not specified, the line number option to the %edit magic will be ignored. """) style_sheet = Unicode(config=True, help=""" A CSS stylesheet. The stylesheet can contain classes for: 1. Qt: QPlainTextEdit, QFrame, QWidget, etc 2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) 3. IPython: .error, .in-prompt, .out-prompt, etc """) syntax_style = Unicode(config=True, help=""" If not empty, use this Pygments style for syntax highlighting. Otherwise, the style sheet is queried for Pygments style information. """) # Prompts. in_prompt = Unicode(default_in_prompt, config=True) out_prompt = Unicode(default_out_prompt, config=True) input_sep = Unicode(default_input_sep, config=True) output_sep = Unicode(default_output_sep, config=True) output_sep2 = Unicode(default_output_sep2, config=True) # FrontendWidget protected class variables. _input_splitter_class = IPythonInputSplitter _prompt_transformer = IPythonInputSplitter(physical_line_transforms=[ipy_prompt()], logical_line_transforms=[], python_line_transforms=[], ) # IPythonWidget protected class variables. _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number']) _payload_source_edit = 'edit' _payload_source_exit = 'ask_exit' _payload_source_next_input = 'set_next_input' _payload_source_page = 'page' _retrying_history_request = False _starting = False #------------------------------------------------------------------------- # 'object' interface #------------------------------------------------------------------------- def __init__(self, *args, **kw): super(IPythonWidget, self).__init__(*args, **kw) # IPythonWidget protected variables. self._payload_handlers = { self._payload_source_edit: self._handle_payload_edit, self._payload_source_exit: self._handle_payload_exit, self._payload_source_page: self._handle_payload_page, self._payload_source_next_input: self._handle_payload_next_input} self._previous_prompt_obj = None self._keep_kernel_on_exit = None # Initialize widget styling. if self.style_sheet: self._style_sheet_changed() self._syntax_style_changed() else: self.set_default_style() self._guiref_loaded = False #------------------------------------------------------------------------- # 'BaseFrontendMixin' abstract interface #------------------------------------------------------------------------- def _handle_complete_reply(self, rep): """ Reimplemented to support IPython's improved completion machinery. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): content = rep['content'] matches = content['matches'] start = content['cursor_start'] end = content['cursor_end'] start = max(start, 0) end = max(end, start) # Move the control's cursor to the desired end point cursor_pos = self._get_input_buffer_cursor_pos() if end < cursor_pos: cursor.movePosition(QtGui.QTextCursor.Left, n=(cursor_pos - end)) elif end > cursor_pos: cursor.movePosition(QtGui.QTextCursor.Right, n=(end - cursor_pos)) # This line actually applies the move to control's cursor self._control.setTextCursor(cursor) offset = end - start # Move the local cursor object to the start of the match and # complete. cursor.movePosition(QtGui.QTextCursor.Left, n=offset) self._complete_with_items(cursor, matches) def _handle_execute_reply(self, msg): """ Reimplemented to support prompt requests. """ msg_id = msg['parent_header'].get('msg_id') info = self._request_info['execute'].get(msg_id) if info and info.kind == 'prompt': content = msg['content'] if content['status'] == 'aborted': self._show_interpreter_prompt() else: number = content['execution_count'] + 1 self._show_interpreter_prompt(number) self._request_info['execute'].pop(msg_id) else: super(IPythonWidget, self)._handle_execute_reply(msg) def _handle_history_reply(self, msg): """ Implemented to handle history tail replies, which are only supported by the IPython kernel. """ content = msg['content'] if 'history' not in content: self.log.error("History request failed: %r" % content) if content.get('status', '') == 'aborted' and \ not self._retrying_history_request: # a *different* action caused this request to be aborted, so # we should try again. self.log.error("Retrying aborted history request") # prevent multiple retries of aborted requests: self._retrying_history_request = True # wait out the kernel's queue flush, which is currently timed # at 0.1s time.sleep(0.25) self.kernel_client.shell_channel.history( hist_access_type='tail', n=1000) else: self._retrying_history_request = False return # reset retry flag self._retrying_history_request = False history_items = content['history'] self.log.debug( "Received history reply with %i entries", len(history_items)) items = [] last_cell = u"" for _, _, cell in history_items: cell = cell.rstrip() if cell != last_cell: items.append(cell) last_cell = cell self._set_history(items) def _insert_other_input(self, cursor, content): """Insert function for input from other frontends""" cursor.beginEditBlock() start = cursor.position() n = content.get('execution_count', 0) cursor.insertText('\n') self._insert_html(cursor, self._make_in_prompt(n)) cursor.insertText(content['code']) self._highlighter.rehighlightBlock(cursor.block()) cursor.endEditBlock() def _handle_execute_input(self, msg): """Handle an execute_input message""" self.log.debug("execute_input: %s", msg.get('content', '')) if self.include_output(msg): self._append_custom( self._insert_other_input, msg['content'], before_prompt=True) def _handle_execute_result(self, msg): """ Reimplemented for IPython-style "display hook". """ self.log.debug("execute_result: %s", msg.get('content', '')) if self.include_output(msg): self.flush_clearoutput() content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if 'text/plain' in data: self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) text = data['text/plain'] # If the repr is multiline, make sure we start on a new line, # so that its lines are aligned. if "\n" in text and not self.output_sep.endswith("\n"): self._append_plain_text('\n', True) self._append_plain_text(text + self.output_sep2, True) def _handle_display_data(self, msg): """ The base handler for the ``display_data`` message. """ self.log.debug("display: %s", msg.get('content', '')) # For now, we don't display data from other frontends, but we # eventually will as this allows all frontends to monitor the display # data. But we need to figure out how to handle this in the GUI. if self.include_output(msg): self.flush_clearoutput() data = msg['content']['data'] metadata = msg['content']['metadata'] # In the regular IPythonWidget, we simply print the plain text # representation. if 'text/plain' in data: text = data['text/plain'] self._append_plain_text(text, True) # This newline seems to be needed for text and html output. self._append_plain_text(u'\n', True) def _handle_kernel_info_reply(self, rep): """Handle kernel info replies.""" content = rep['content'] if not self._guiref_loaded: if content.get('language') == 'python': self._load_guiref_magic() self._guiref_loaded = True self.kernel_banner = content.get('banner', '') if self._starting: # finish handling started channels self._starting = False super(IPythonWidget, self)._started_channels() def _started_channels(self): """Reimplemented to make a history request and load %guiref.""" self._starting = True # The reply will trigger %guiref load provided language=='python' self.kernel_client.kernel_info() self.kernel_client.shell_channel.history(hist_access_type='tail', n=1000) def _load_guiref_magic(self): """Load %guiref magic.""" self.kernel_client.shell_channel.execute('\n'.join([ "try:", " _usage", "except:", " from IPython.core import usage as _usage", " get_ipython().register_magic_function(_usage.page_guiref, 'line', 'guiref')", " del _usage", ]), silent=True) #------------------------------------------------------------------------- # 'ConsoleWidget' public interface #------------------------------------------------------------------------- #------------------------------------------------------------------------- # 'FrontendWidget' public interface #------------------------------------------------------------------------- def execute_file(self, path, hidden=False): """ Reimplemented to use the 'run' magic. """ # Use forward slashes on Windows to avoid escaping each separator. if sys.platform == 'win32': path = os.path.normpath(path).replace('\\', '/') # Perhaps we should not be using %run directly, but while we # are, it is necessary to quote or escape filenames containing spaces # or quotes. # In earlier code here, to minimize escaping, we sometimes quoted the # filename with single quotes. But to do this, this code must be # platform-aware, because run uses shlex rather than python string # parsing, so that: # * In Win: single quotes can be used in the filename without quoting, # and we cannot use single quotes to quote the filename. # * In *nix: we can escape double quotes in a double quoted filename, # but can't escape single quotes in a single quoted filename. # So to keep this code non-platform-specific and simple, we now only # use double quotes to quote filenames, and escape when needed: if ' ' in path or "'" in path or '"' in path: path = '"%s"' % path.replace('"', '\\"') self.execute('%%run %s' % path, hidden=hidden) #------------------------------------------------------------------------- # 'FrontendWidget' protected interface #------------------------------------------------------------------------- def _process_execute_error(self, msg): """ Reimplemented for IPython-style traceback formatting. """ content = msg['content'] traceback = '\n'.join(content['traceback']) + '\n' if False: # FIXME: For now, tracebacks come as plain text, so we can't use # the html renderer yet. Once we refactor ultratb to produce # properly styled tracebacks, this branch should be the default traceback = traceback.replace(' ', '&nbsp;') traceback = traceback.replace('\n', '<br/>') ename = content['ename'] ename_styled = '<span class="error">%s</span>' % ename traceback = traceback.replace(ename, ename_styled) self._append_html(traceback) else: # This is the fallback for now, using plain text with ansi escapes self._append_plain_text(traceback) def _process_execute_payload(self, item): """ Reimplemented to dispatch payloads to handler methods. """ handler = self._payload_handlers.get(item['source']) if handler is None: # We have no handler for this type of payload, simply ignore it return False else: handler(item) return True def _show_interpreter_prompt(self, number=None): """ Reimplemented for IPython-style prompts. """ # If a number was not specified, make a prompt number request. if number is None: msg_id = self.kernel_client.shell_channel.execute('', silent=True) info = self._ExecutionRequest(msg_id, 'prompt') self._request_info['execute'][msg_id] = info return # Show a new prompt and save information about it so that it can be # updated later if the prompt number turns out to be wrong. self._prompt_sep = self.input_sep self._show_prompt(self._make_in_prompt(number), html=True) block = self._control.document().lastBlock() length = len(self._prompt) self._previous_prompt_obj = self._PromptBlock(block, length, number) # Update continuation prompt to reflect (possibly) new prompt length. self._set_continuation_prompt( self._make_continuation_prompt(self._prompt), html=True) def _show_interpreter_prompt_for_reply(self, msg): """ Reimplemented for IPython-style prompts. """ # Update the old prompt number if necessary. content = msg['content'] # abort replies do not have any keys: if content['status'] == 'aborted': if self._previous_prompt_obj: previous_prompt_number = self._previous_prompt_obj.number else: previous_prompt_number = 0 else: previous_prompt_number = content['execution_count'] if self._previous_prompt_obj and \ self._previous_prompt_obj.number != previous_prompt_number: block = self._previous_prompt_obj.block # Make sure the prompt block has not been erased. if block.isValid() and block.text(): # Remove the old prompt and insert a new prompt. cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, self._previous_prompt_obj.length) prompt = self._make_in_prompt(previous_prompt_number) self._prompt = self._insert_html_fetching_plain_text( cursor, prompt) # When the HTML is inserted, Qt blows away the syntax # highlighting for the line, so we need to rehighlight it. self._highlighter.rehighlightBlock(cursor.block()) self._previous_prompt_obj = None # Show a new prompt with the kernel's estimated prompt number. self._show_interpreter_prompt(previous_prompt_number + 1) #------------------------------------------------------------------------- # 'IPythonWidget' interface #------------------------------------------------------------------------- def set_default_style(self, colors='lightbg'): """ Sets the widget style to the class defaults. Parameters ---------- colors : str, optional (default lightbg) Whether to use the default IPython light background or dark background or B&W style. """ colors = colors.lower() if colors == 'lightbg': self.style_sheet = styles.default_light_style_sheet self.syntax_style = styles.default_light_syntax_style elif colors == 'linux': self.style_sheet = styles.default_dark_style_sheet self.syntax_style = styles.default_dark_syntax_style elif colors == 'nocolor': self.style_sheet = styles.default_bw_style_sheet self.syntax_style = styles.default_bw_syntax_style else: raise KeyError("No such color scheme: %s" % colors) #------------------------------------------------------------------------- # 'IPythonWidget' protected interface #------------------------------------------------------------------------- def _edit(self, filename, line=None): """ Opens a Python script for editing. Parameters ---------- filename : str A path to a local system file. line : int, optional A line of interest in the file. """ if self.custom_edit: self.custom_edit_requested.emit(filename, line) elif not self.editor: self._append_plain_text('No default editor available.\n' 'Specify a GUI text editor in the `IPythonWidget.editor` ' 'configurable to enable the %edit magic') else: try: filename = '"%s"' % filename if line and self.editor_line: command = self.editor_line.format(filename=filename, line=line) else: try: command = self.editor.format() except KeyError: command = self.editor.format(filename=filename) else: command += ' ' + filename except KeyError: self._append_plain_text('Invalid editor command.\n') else: try: Popen(command, shell=True) except OSError: msg = 'Opening editor with command "%s" failed.\n' self._append_plain_text(msg % command) def _make_in_prompt(self, number): """ Given a prompt number, returns an HTML In prompt. """ try: body = self.in_prompt % number except TypeError: # allow in_prompt to leave out number, e.g. '>>> ' from xml.sax.saxutils import escape body = escape(self.in_prompt) return '<span class="in-prompt">%s</span>' % body def _make_continuation_prompt(self, prompt): """ Given a plain text version of an In prompt, returns an HTML continuation prompt. """ end_chars = '...: ' space_count = len(prompt.lstrip('\n')) - len(end_chars) body = '&nbsp;' * space_count + end_chars return '<span class="in-prompt">%s</span>' % body def _make_out_prompt(self, number): """ Given a prompt number, returns an HTML Out prompt. """ try: body = self.out_prompt % number except TypeError: # allow out_prompt to leave out number, e.g. '<<< ' from xml.sax.saxutils import escape body = escape(self.out_prompt) return '<span class="out-prompt">%s</span>' % body #------ Payload handlers -------------------------------------------------- # Payload handlers with a generic interface: each takes the opaque payload # dict, unpacks it and calls the underlying functions with the necessary # arguments. def _handle_payload_edit(self, item): self._edit(item['filename'], item['line_number']) def _handle_payload_exit(self, item): self._keep_kernel_on_exit = item['keepkernel'] self.exit_requested.emit(self) def _handle_payload_next_input(self, item): self.input_buffer = item['text'] def _handle_payload_page(self, item): # Since the plain text widget supports only a very small subset of HTML # and we have no control over the HTML source, we only page HTML # payloads in the rich text widget. data = item['data'] if 'text/html' in data and self.kind == 'rich': self._page(data['text/html'], html=True) else: self._page(data['text/plain'], html=False) #------ Trait change handlers -------------------------------------------- def _style_sheet_changed(self): """ Set the style sheets of the underlying widgets. """ self.setStyleSheet(self.style_sheet) if self._control is not None: self._control.document().setDefaultStyleSheet(self.style_sheet) bg_color = self._control.palette().window().color() self._ansi_processor.set_background_color(bg_color) if self._page_control is not None: self._page_control.document().setDefaultStyleSheet( self.style_sheet) def _syntax_style_changed(self): """ Set the style for the syntax highlighter. """ if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter.set_style(self.syntax_style) else: self._highlighter.set_style_sheet(self.style_sheet) #------ Trait default initializers --------------------------------------- def _banner_default(self): return "IPython QtConsole {version}\n".format(version=version)
{ "repo_name": "mattvonrocketstein/smash", "path": "smashlib/ipy3x/qt/console/ipython_widget.py", "copies": "1", "size": "25124", "license": "mit", "hash": 5788763887735892000, "line_mean": 40.6650082919, "line_max": 94, "alpha_frac": 0.5451759274, "autogenerated": false, "ratio": 4.605682859761687, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005148034890828437, "num_lines": 603 }
"""A FrontendWidget that emulates the interface of the console IPython. This supports the additional functionality provided by the IPython kernel. """ #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports from collections import namedtuple import os.path import re from subprocess import Popen import sys import time from textwrap import dedent # System library imports from IPython.external.qt import QtCore, QtGui # Local imports from IPython.core.inputsplitter import IPythonInputSplitter from IPython.core.inputtransformer import ipy_prompt from IPython.utils.traitlets import Bool, Unicode from .frontend_widget import FrontendWidget from . import styles #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- # Default strings to build and display input and output prompts (and separators # in between) default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' default_input_sep = '\n' default_output_sep = '' default_output_sep2 = '' # Base path for most payload sources. zmq_shell_source = 'IPython.kernel.zmq.zmqshell.ZMQInteractiveShell' if sys.platform.startswith('win'): default_editor = 'notepad' else: default_editor = '' #----------------------------------------------------------------------------- # IPythonWidget class #----------------------------------------------------------------------------- class IPythonWidget(FrontendWidget): """ A FrontendWidget for an IPython kernel. """ # If set, the 'custom_edit_requested(str, int)' signal will be emitted when # an editor is needed for a file. This overrides 'editor' and 'editor_line' # settings. custom_edit = Bool(False) custom_edit_requested = QtCore.Signal(object, object) editor = Unicode(default_editor, config=True, help=""" A command for invoking a system text editor. If the string contains a {filename} format specifier, it will be used. Otherwise, the filename will be appended to the end the command. """) editor_line = Unicode(config=True, help=""" The editor command to use when a specific line number is requested. The string should contain two format specifiers: {line} and {filename}. If this parameter is not specified, the line number option to the %edit magic will be ignored. """) style_sheet = Unicode(config=True, help=""" A CSS stylesheet. The stylesheet can contain classes for: 1. Qt: QPlainTextEdit, QFrame, QWidget, etc 2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) 3. IPython: .error, .in-prompt, .out-prompt, etc """) syntax_style = Unicode(config=True, help=""" If not empty, use this Pygments style for syntax highlighting. Otherwise, the style sheet is queried for Pygments style information. """) # Prompts. in_prompt = Unicode(default_in_prompt, config=True) out_prompt = Unicode(default_out_prompt, config=True) input_sep = Unicode(default_input_sep, config=True) output_sep = Unicode(default_output_sep, config=True) output_sep2 = Unicode(default_output_sep2, config=True) # FrontendWidget protected class variables. _input_splitter_class = IPythonInputSplitter _prompt_transformer = IPythonInputSplitter(physical_line_transforms=[ipy_prompt()], logical_line_transforms=[], python_line_transforms=[], ) # IPythonWidget protected class variables. _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number']) _payload_source_edit = 'edit_magic' _payload_source_exit = 'ask_exit' _payload_source_next_input = 'set_next_input' _payload_source_page = 'page' _retrying_history_request = False #--------------------------------------------------------------------------- # 'object' interface #--------------------------------------------------------------------------- def __init__(self, *args, **kw): super(IPythonWidget, self).__init__(*args, **kw) # IPythonWidget protected variables. self._payload_handlers = { self._payload_source_edit : self._handle_payload_edit, self._payload_source_exit : self._handle_payload_exit, self._payload_source_page : self._handle_payload_page, self._payload_source_next_input : self._handle_payload_next_input } self._previous_prompt_obj = None self._keep_kernel_on_exit = None # Initialize widget styling. if self.style_sheet: self._style_sheet_changed() self._syntax_style_changed() else: self.set_default_style() self._guiref_loaded = False #--------------------------------------------------------------------------- # 'BaseFrontendMixin' abstract interface #--------------------------------------------------------------------------- def _handle_complete_reply(self, rep): """ Reimplemented to support IPython's improved completion machinery. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): matches = rep['content']['matches'] text = rep['content']['matched_text'] offset = len(text) # Clean up matches with period and path separators if the matched # text has not been transformed. This is done by truncating all # but the last component and then suitably decreasing the offset # between the current cursor position and the start of completion. if len(matches) > 1 and matches[0][:offset] == text: parts = re.split(r'[./\\]', text) sep_count = len(parts) - 1 if sep_count: chop_length = sum(map(len, parts[:sep_count])) + sep_count matches = [ match[chop_length:] for match in matches ] offset -= chop_length # Move the cursor to the start of the match and complete. cursor.movePosition(QtGui.QTextCursor.Left, n=offset) self._complete_with_items(cursor, matches) def _handle_execute_reply(self, msg): """ Reimplemented to support prompt requests. """ msg_id = msg['parent_header'].get('msg_id') info = self._request_info['execute'].get(msg_id) if info and info.kind == 'prompt': content = msg['content'] if content['status'] == 'aborted': self._show_interpreter_prompt() else: number = content['execution_count'] + 1 self._show_interpreter_prompt(number) self._request_info['execute'].pop(msg_id) else: super(IPythonWidget, self)._handle_execute_reply(msg) def _handle_history_reply(self, msg): """ Implemented to handle history tail replies, which are only supported by the IPython kernel. """ content = msg['content'] if 'history' not in content: self.log.error("History request failed: %r"%content) if content.get('status', '') == 'aborted' and \ not self._retrying_history_request: # a *different* action caused this request to be aborted, so # we should try again. self.log.error("Retrying aborted history request") # prevent multiple retries of aborted requests: self._retrying_history_request = True # wait out the kernel's queue flush, which is currently timed at 0.1s time.sleep(0.25) self.kernel_client.shell_channel.history(hist_access_type='tail',n=1000) else: self._retrying_history_request = False return # reset retry flag self._retrying_history_request = False history_items = content['history'] self.log.debug("Received history reply with %i entries", len(history_items)) items = [] last_cell = u"" for _, _, cell in history_items: cell = cell.rstrip() if cell != last_cell: items.append(cell) last_cell = cell self._set_history(items) def _handle_pyout(self, msg): """ Reimplemented for IPython-style "display hook". """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): self.flush_clearoutput() content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if 'text/html' in data: self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) html = data['text/html'] self._append_plain_text('\n', True) self._append_html(html + self.output_sep2, True) elif 'text/plain' in data: self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) text = data['text/plain'] # If the repr is multiline, make sure we start on a new line, # so that its lines are aligned. if "\n" in text and not self.output_sep.endswith("\n"): self._append_plain_text('\n', True) self._append_plain_text(text + self.output_sep2, True) def _handle_display_data(self, msg): """ The base handler for the ``display_data`` message. """ self.log.debug("display: %s", msg.get('content', '')) # For now, we don't display data from other frontends, but we # eventually will as this allows all frontends to monitor the display # data. But we need to figure out how to handle this in the GUI. if not self._hidden and self._is_from_this_session(msg): self.flush_clearoutput() source = msg['content']['source'] data = msg['content']['data'] metadata = msg['content']['metadata'] # In the regular IPythonWidget, we simply print the plain text # representation. if 'text/html' in data: html = data['text/html'] self._append_html(html, True) elif 'text/plain' in data: text = data['text/plain'] self._append_plain_text(text, True) # This newline seems to be needed for text and html output. self._append_plain_text(u'\n', True) def _handle_kernel_info_reply(self, rep): """ Handle kernel info replies. """ if not self._guiref_loaded: if rep['content'].get('language') == 'python': self._load_guiref_magic() self._guiref_loaded = True def _started_channels(self): """Reimplemented to make a history request and load %guiref.""" super(IPythonWidget, self)._started_channels() # The reply will trigger %guiref load provided language=='python' self.kernel_client.kernel_info() self.kernel_client.shell_channel.history(hist_access_type='tail', n=1000) def _started_kernel(self): """Load %guiref when the kernel starts (if channels are also started). Principally triggered by kernel restart. """ if self.kernel_client.shell_channel is not None: self._load_guiref_magic() def _load_guiref_magic(self): """Load %guiref magic.""" self.kernel_client.shell_channel.execute('\n'.join([ "try:", " _usage", "except:", " from IPython.core import usage as _usage", " get_ipython().register_magic_function(_usage.page_guiref, 'line', 'guiref')", " del _usage", ]), silent=True) #--------------------------------------------------------------------------- # 'ConsoleWidget' public interface #--------------------------------------------------------------------------- #--------------------------------------------------------------------------- # 'FrontendWidget' public interface #--------------------------------------------------------------------------- def execute_file(self, path, hidden=False): """ Reimplemented to use the 'run' magic. """ # Use forward slashes on Windows to avoid escaping each separator. if sys.platform == 'win32': path = os.path.normpath(path).replace('\\', '/') # Perhaps we should not be using %run directly, but while we # are, it is necessary to quote or escape filenames containing spaces # or quotes. # In earlier code here, to minimize escaping, we sometimes quoted the # filename with single quotes. But to do this, this code must be # platform-aware, because run uses shlex rather than python string # parsing, so that: # * In Win: single quotes can be used in the filename without quoting, # and we cannot use single quotes to quote the filename. # * In *nix: we can escape double quotes in a double quoted filename, # but can't escape single quotes in a single quoted filename. # So to keep this code non-platform-specific and simple, we now only # use double quotes to quote filenames, and escape when needed: if ' ' in path or "'" in path or '"' in path: path = '"%s"' % path.replace('"', '\\"') self.execute('%%run %s' % path, hidden=hidden) #--------------------------------------------------------------------------- # 'FrontendWidget' protected interface #--------------------------------------------------------------------------- def _complete(self): """ Reimplemented to support IPython's improved completion machinery. """ # We let the kernel split the input line, so we *always* send an empty # text field. Readline-based frontends do get a real text field which # they can use. text = '' # Send the completion request to the kernel msg_id = self.kernel_client.shell_channel.complete( text, # text self._get_input_buffer_cursor_line(), # line self._get_input_buffer_cursor_column(), # cursor_pos self.input_buffer) # block pos = self._get_cursor().position() info = self._CompletionRequest(msg_id, pos) self._request_info['complete'] = info def _process_execute_error(self, msg): """ Reimplemented for IPython-style traceback formatting. """ content = msg['content'] traceback = '\n'.join(content['traceback']) + '\n' if False: # FIXME: For now, tracebacks come as plain text, so we can't use # the html renderer yet. Once we refactor ultratb to produce # properly styled tracebacks, this branch should be the default traceback = traceback.replace(' ', '&nbsp;') traceback = traceback.replace('\n', '<br/>') ename = content['ename'] ename_styled = '<span class="error">%s</span>' % ename traceback = traceback.replace(ename, ename_styled) self._append_html(traceback) else: # This is the fallback for now, using plain text with ansi escapes self._append_plain_text(traceback) def _process_execute_payload(self, item): """ Reimplemented to dispatch payloads to handler methods. """ handler = self._payload_handlers.get(item['source']) if handler is None: # We have no handler for this type of payload, simply ignore it return False else: handler(item) return True def _show_interpreter_prompt(self, number=None): """ Reimplemented for IPython-style prompts. """ # If a number was not specified, make a prompt number request. if number is None: msg_id = self.kernel_client.shell_channel.execute('', silent=True) info = self._ExecutionRequest(msg_id, 'prompt') self._request_info['execute'][msg_id] = info return # Show a new prompt and save information about it so that it can be # updated later if the prompt number turns out to be wrong. self._prompt_sep = self.input_sep self._show_prompt(self._make_in_prompt(number), html=True) block = self._control.document().lastBlock() length = len(self._prompt) self._previous_prompt_obj = self._PromptBlock(block, length, number) # Update continuation prompt to reflect (possibly) new prompt length. self._set_continuation_prompt( self._make_continuation_prompt(self._prompt), html=True) def _show_interpreter_prompt_for_reply(self, msg): """ Reimplemented for IPython-style prompts. """ # Update the old prompt number if necessary. content = msg['content'] # abort replies do not have any keys: if content['status'] == 'aborted': if self._previous_prompt_obj: previous_prompt_number = self._previous_prompt_obj.number else: previous_prompt_number = 0 else: previous_prompt_number = content['execution_count'] if self._previous_prompt_obj and \ self._previous_prompt_obj.number != previous_prompt_number: block = self._previous_prompt_obj.block # Make sure the prompt block has not been erased. if block.isValid() and block.text(): # Remove the old prompt and insert a new prompt. cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, self._previous_prompt_obj.length) prompt = self._make_in_prompt(previous_prompt_number) self._prompt = self._insert_html_fetching_plain_text( cursor, prompt) # When the HTML is inserted, Qt blows away the syntax # highlighting for the line, so we need to rehighlight it. self._highlighter.rehighlightBlock(cursor.block()) self._previous_prompt_obj = None # Show a new prompt with the kernel's estimated prompt number. self._show_interpreter_prompt(previous_prompt_number + 1) #--------------------------------------------------------------------------- # 'IPythonWidget' interface #--------------------------------------------------------------------------- def set_default_style(self, colors='lightbg'): """ Sets the widget style to the class defaults. Parameters ---------- colors : str, optional (default lightbg) Whether to use the default IPython light background or dark background or B&W style. """ colors = colors.lower() if colors=='lightbg': self.style_sheet = styles.default_light_style_sheet self.syntax_style = styles.default_light_syntax_style elif colors=='linux': self.style_sheet = styles.default_dark_style_sheet self.syntax_style = styles.default_dark_syntax_style elif colors=='nocolor': self.style_sheet = styles.default_bw_style_sheet self.syntax_style = styles.default_bw_syntax_style else: raise KeyError("No such color scheme: %s"%colors) #--------------------------------------------------------------------------- # 'IPythonWidget' protected interface #--------------------------------------------------------------------------- def _edit(self, filename, line=None): """ Opens a Python script for editing. Parameters ---------- filename : str A path to a local system file. line : int, optional A line of interest in the file. """ if self.custom_edit: self.custom_edit_requested.emit(filename, line) elif not self.editor: self._append_plain_text('No default editor available.\n' 'Specify a GUI text editor in the `IPythonWidget.editor` ' 'configurable to enable the %edit magic') else: try: filename = '"%s"' % filename if line and self.editor_line: command = self.editor_line.format(filename=filename, line=line) else: try: command = self.editor.format() except KeyError: command = self.editor.format(filename=filename) else: command += ' ' + filename except KeyError: self._append_plain_text('Invalid editor command.\n') else: try: Popen(command, shell=True) except OSError: msg = 'Opening editor with command "%s" failed.\n' self._append_plain_text(msg % command) def _make_in_prompt(self, number): """ Given a prompt number, returns an HTML In prompt. """ try: body = self.in_prompt % number except TypeError: # allow in_prompt to leave out number, e.g. '>>> ' body = self.in_prompt return '<span class="in-prompt">%s</span>' % body def _make_continuation_prompt(self, prompt): """ Given a plain text version of an In prompt, returns an HTML continuation prompt. """ end_chars = '...: ' space_count = len(prompt.lstrip('\n')) - len(end_chars) body = '&nbsp;' * space_count + end_chars return '<span class="in-prompt">%s</span>' % body def _make_out_prompt(self, number): """ Given a prompt number, returns an HTML Out prompt. """ body = self.out_prompt % number return '<span class="out-prompt">%s</span>' % body #------ Payload handlers -------------------------------------------------- # Payload handlers with a generic interface: each takes the opaque payload # dict, unpacks it and calls the underlying functions with the necessary # arguments. def _handle_payload_edit(self, item): self._edit(item['filename'], item['line_number']) def _handle_payload_exit(self, item): self._keep_kernel_on_exit = item['keepkernel'] self.exit_requested.emit(self) def _handle_payload_next_input(self, item): self.input_buffer = item['text'] def _handle_payload_page(self, item): # Since the plain text widget supports only a very small subset of HTML # and we have no control over the HTML source, we only page HTML # payloads in the rich text widget. if item['html'] and self.kind == 'rich': self._page(item['html'], html=True) else: self._page(item['text'], html=False) #------ Trait change handlers -------------------------------------------- def _style_sheet_changed(self): """ Set the style sheets of the underlying widgets. """ self.setStyleSheet(self.style_sheet) if self._control is not None: self._control.document().setDefaultStyleSheet(self.style_sheet) bg_color = self._control.palette().window().color() self._ansi_processor.set_background_color(bg_color) if self._page_control is not None: self._page_control.document().setDefaultStyleSheet(self.style_sheet) def _syntax_style_changed(self): """ Set the style for the syntax highlighter. """ if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter.set_style(self.syntax_style) else: self._highlighter.set_style_sheet(self.style_sheet) #------ Trait default initializers ----------------------------------------- def _banner_default(self): from IPython.core.usage import default_gui_banner return default_gui_banner
{ "repo_name": "poojavade/Genomics_Docker", "path": "Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/ipython-2.2.0-py2.7.egg/IPython/qt/console/ipython_widget.py", "copies": "5", "size": "25459", "license": "apache-2.0", "hash": 981220151527484800, "line_mean": 41.2205638474, "line_max": 94, "alpha_frac": 0.5430692486, "autogenerated": false, "ratio": 4.613809351214208, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.003608871252814598, "num_lines": 603 }
#!/afs/andrew.cmu.edu/usr6/ericgan/11411-proj/env11411/bin/python # # ask.py # # Runs the utility for generating questions from article text. # # Usage: ./ask.py article_file.htm N # where article_file.htm is the HTML file containing the article HTML content # and N is an integer specifying the number of questions to output. # # The algorithm iterates over each reasonable sentence in the article. A # reasonable sentence is defined by the combination of several metrics, such # as a minimum length, presence of a verb, and appropriate ending punctuation. # For each reasonable sentence, it turns it into a question using the # ConstructQuestion class from sent_2_q.py, and scores each generated question # using a probabalistic language model. The N highest-scoring questions are # then written to standard out. # # Error 501: Not Yet Implemented # # Aaron Anderson # with # Eric Gan # Rachel Kobayashi # ### IMPORTS ### from ask.q_scorer import QuestionScorer from ask.sent_2_q import ConstructQuestion from util.article_parser import MyHTMLParser import util.qutil as qutil import nltk import traceback import sys ### CONSTANTS ### # Usage string usage = """Usage: ./ask.py article_file.htm N where article_file.htm is the HTML file containing the article HTML content and N is an integer specifying the number of questions to output. """ ### FUNCTIONS ### # Checks for the presence and right number of command line # arguments, and returns the article filename and number of # questions to generate as a tuple (filename, n) # If there are not the right number of arguments, the function # prints the usage message and exits the program. def getInputs(): args = sys.argv[1:] if len(args) < 2: sys.exit(usage); n = int(args[1]) return (args[0], n) ### MAIN ### if __name__ == "__main__": # Add the path to the nltk data nltk.data.path.append('/afs/andrew.cmu.edu/usr6/ericgan/nltk_data') # Get the arguments from the command line (articleFilename, N) = getInputs() # Attempt to open the article file try: articleFd = open(articleFilename, 'r') except IOError: sys.stderr.write("Could not find article file: %s\n" % (articleFilename)); # Read text of the article and turn sentences into questions try: parser = MyHTMLParser() text = articleFd.read() parser.feed(text) # Retrieve the list of sentences within the article from the parser sentenceList = parser.grabTextSentenceList() sentenceList = filter(qutil.isSentence, sentenceList) # Instantiate a QuestionScorer and generate a (question,score) pair # for each sentence in the sentenceList scorer = QuestionScorer() questions = [] for sent in sentenceList: try: constructor = ConstructQuestion(sent) q = constructor.out if q == '': # Unable to successfully generate a question; discard continue except Exception, msg: sys.stderr.write('WARNING: Exception in constructing question!\n') sys.stderr.write('Please track this down and figure out what went wrong\n') # sys.stderr.write(str(msg) + '\n') traceback.print_exc(file=sys.stderr) continue # Successfully constructed a question q qToks = nltk.word_tokenize(q.strip()) s = scorer.score(qToks) questions.append((q,s,sent)) # Sort the questions by score in descending order (so highest score # questions are first questions.sort(key = lambda x: x[1], reverse=True) # Output the first N questions (these have the highest score) for i in xrange(N): # # TODO: remove. Prints corresponding sentence for reference only # print questions[i][2] # Print corresponding generated question print questions[i][0] # print '' except IOError, msg: sys.stderr.write("An I/O error occurred while processing the article. Details:\n") # sys.stderr.write(str(msg) + '\n') traceback.print_exc(file=sys.stderr) finally : # Cleanup articleFd.close()
{ "repo_name": "ercgn/11411-proj", "path": "src/ask.py", "copies": "1", "size": "4372", "license": "mit", "hash": -2388185602545212000, "line_mean": 33.4251968504, "line_max": 91, "alpha_frac": 0.6468435499, "autogenerated": false, "ratio": 4.093632958801498, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5240476508701498, "avg_score": null, "num_lines": null }
#!/afs/crc.nd.edu/x86_64_linux/python/3.4.0/gcc-4.8.0/bin/python3 ''' reactive_flux.py - Calculates the normalized reactive flux, k(t), from a set of GROMACS simulations started at the maximum of the free energy barrier. Currently supports bimolecular reactions. ''' import os import numpy as np import math import sys import time def heavyside(arg, i=1, rdz=1): if i == 0: if rdz >= 0: return 1.0 else: return 0.0 if arg >= 0: return 1.0 if arg < 0: return 0.0 def list_divide(list1, list2): final_list = [] for i in range(0, len(list1)): if list2[i] == 0: final_list.append(0) else: final_list.append(list1[i]/list2[i]) return final_list def list_subtract(list1, list2): final_list = [] for i in range(0, len(list1)): final_list.append(list1[i] - list2[i]) return final_list def minimage(x, y, z): if x > boxx/2.0: x -= boxx elif x < -boxx/2.0: x += boxx if y > boxy/2.0: y -= boxy elif y < -boxy/2.0: y += boxy if z > boxz/2.0: z -= boxz elif z < -boxz/2.0: z += boxz return [x, y, z] def covariance(A, B): '''Calculates the covariance between two data sets.''' # Calculate the mean of A and B, respectively muA = np.mean(A) muB = np.mean(B) # Calculate covariance. cov = 0 N = len(A) for eA, eB in zip(A, B): cov += ((eA-muA)*(eB-muB))/N return cov def chi(backwards, tsloc): '''Checks if the backwards trajectory recrosses the TS.''' chilist = [] recrossed = False for value in backwards: if recrossed == True: chilist.append(0) else: this_dist = float(value.split()[1]) if this_dist > tsloc: chilist.append(0) recrossed = True else: chilist.append(1) return chilist # Check if we want a special RF function runtype = '' if len(sys.argv) == 2: runtype = sys.argv[1] print(runtype) if len(sys.argv) == 3: runtype = sys.argv[1] print(runtype) ## Data structure initialization num_frames = 600 num_simulations = 2000 ktnum = [0 for i in range(0, num_frames+1)] ktnum2 = [0 for i in range(0, num_frames+1)] ktden = [0 for i in range(0, num_frames+1)] timelist = np.linspace(0.000, 3.000, num_frames).tolist() lastnums = [] lastdens = [] # Get box size. boxlines = open('1/nvt1.gro', 'r').readlines() box = boxlines[-1].split() boxx = float(box[0]) boxy = float(box[1]) boxz = float(box[2]) print("Detected box {0}, {1}, {2}".format(boxx, boxy, boxz)) tslocs = [] if runtype == '': print("Calculating the Bennett-Chandler transmission coefficient.") for sim in range (1, num_simulations+1): sys.stdout.write("\rAnalyzing simulation {0}/{1}...".format(sim, num_simulations)) sys.stdout.flush() for i in range(0,2): if i == 0: # forwards with open("{0}/distanceu.xvg".format(sim), "r") as f: udistfile = f.readlines() with open("{0}/distancel.xvg".format(sim), "r") as f: ldistfile = f.readlines() with open("{0}/velocityu.xvg".format(sim), "r") as f: uvelofile = f.readlines() with open("{0}/velocityl.xvg".format(sim), "r") as f: lvelofile = f.readlines() with open("{0}/dist.xvg".format(sim), "r") as f: distfile = f.readlines() elif i == 1: # reverse with open("{0}/distanceur.xvg".format(sim), "r") as f: udistfile = f.readlines() with open("{0}/distancelr.xvg".format(sim), "r") as f: ldistfile = f.readlines() with open("{0}/velocityur.xvg".format(sim), "r") as f: uvelofile = f.readlines() with open("{0}/velocitylr.xvg".format(sim), "r") as f: lvelofile = f.readlines() with open("{0}/distr.xvg".format(sim), "r") as f: distfile = f.readlines() # Get r tsloc = float(distfile[15].split()[1]) tslocs.append(tsloc) # Get COM of U, L UCOM = float(udistfile[24].split()[1]), float(udistfile[24].split()[2]), float(udistfile[24].split()[3]) LCOM = float(ldistfile[24].split()[1]), float(ldistfile[24].split()[2]), float(ldistfile[24].split()[3]) # Get COV of U, L UCOV = float(uvelofile[24].split()[1]), float(uvelofile[24].split()[2]), float(uvelofile[24].split()[3]) LCOV = float(lvelofile[24].split()[1]), float(lvelofile[24].split()[2]), float(lvelofile[24].split()[3]) # Calculate dx, dy, dz dx, dy, dz = minimage(UCOM[0]-LCOM[0], UCOM[1]-LCOM[1], UCOM[2]-LCOM[2]) # Calculate dvx, dvy, dvz dvx = UCOV[0]-LCOV[0] dvy = UCOV[1]-LCOV[1] dvz = UCOV[2]-LCOV[2] rdotzero = (dx*dvx + dy*dvy + dz*dvz)/(dx**2+dy**2+dz**2)**0.5 #print('New Rdotzero: {0}'.format(rdotzero)) #rdotzero = (distance2-tsloc)/0.005 #print('Old Rdotzero (finite difference): {0}'.format(rdotzero)) hs_rdotzero = heavyside(rdotzero) # And loop over all distances: i = 0 for line in distfile[15:]: this_line = line.split() distance = float(this_line[1]) hs_rt_ts_loc = heavyside(distance - tsloc, i, rdotzero) # Calculate k(t) for that frame, append to lists ktnum[i] += (rdotzero*hs_rt_ts_loc) ktden[i] += (rdotzero*hs_rdotzero) i += 1 print("Analysis finished. Producing final reactive flux function, kbc(t).") # Produce k(t) from numerator and denominator lists kt = list_divide(ktnum, ktden) print("Transmission Coefficient Estimate: {0}".format(np.mean(kt[-200:]))) print("Saving data.") save_file = open("data", 'w') for frame in range(0,num_frames-1): save_file.write("{0} {1}\n".format(timelist[frame], kt[frame])) save_file.close() #with open('tcoeff', 'a') as tcfile: # tcfile.write(str(np.mean(kt[-200:]))) # tcfile.write('\n') if runtype == 'bc2': print("Calculating the Bennett-Chandler 2 transmission coefficient.") for sim in range (1, num_simulations+1): sys.stdout.write("\rAnalyzing simulation {0}/{1}...".format(sim, num_simulations)) sys.stdout.flush() with open("{0}/distanceu.xvg".format(sim), "r") as f: udistfile = f.readlines() with open("{0}/distancel.xvg".format(sim), "r") as f: ldistfile = f.readlines() with open("{0}/velocityu.xvg".format(sim), "r") as f: uvelofile = f.readlines() with open("{0}/velocityl.xvg".format(sim), "r") as f: lvelofile = f.readlines() with open("{0}/dist.xvg".format(sim), "r") as f: distfile = f.readlines() with open("{0}/distr.xvg".format(sim), "r") as f: distrfile = f.readlines() # Check to see if the trajectory started at the right location. # If so, extract rdot(0): tsloc = float(distfile[15].split()[1]) # Get COM of U, L UCOM = float(udistfile[24].split()[1]), float(udistfile[24].split()[2]), float(udistfile[24].split()[3]) LCOM = float(ldistfile[24].split()[1]), float(ldistfile[24].split()[2]), float(ldistfile[24].split()[3]) # Get COV of U, L UCOV = float(uvelofile[24].split()[1]), float(uvelofile[24].split()[2]), float(uvelofile[24].split()[3]) LCOV = float(lvelofile[24].split()[1]), float(lvelofile[24].split()[2]), float(lvelofile[24].split()[3]) # Calculate dx, dy, dz dx, dy, dz = minimage(UCOM[0]-LCOM[0], UCOM[1]-LCOM[1], UCOM[2]-LCOM[2]) # Calculate dvx, dvy, dvz dvx = UCOV[0]-LCOV[0] dvy = UCOV[1]-LCOV[1] dvz = UCOV[2]-LCOV[2] rdotzero = (dx*dvx + dy*dvy + dz*dvz)/(dx**2+dy**2+dz**2)**0.5 hs_rdotzero = heavyside(rdotzero) # And loop over all distances: i = 0 for fline, bline in zip(distfile[15:], distrfile[15:]): this_fline = fline.split() fdistance = float(this_fline[1]) this_bline = bline.split() bdistance = float(this_bline[1]) hs_rt_ts_loc = heavyside(fdistance - tsloc, i, rdz=rdotzero) hs_lt_ts_loc = heavyside(tsloc - bdistance, i, rdz=rdotzero) # Calculate k(t) for that frame, append to lists ktnum[i] += rdotzero*hs_rt_ts_loc*hs_lt_ts_loc ktden[i] += rdotzero*hs_rdotzero i += 1 # Save last frame of numerator and denominator to a list lastnums.append(rdotzero*hs_rt_ts_loc*hs_lt_ts_loc) lastdens.append(rdotzero*hs_rdotzero) print("Analysis finished. Producing final reactive flux function, kbc2(t).") # Produce k(t) from numerator and denominator lists kt = list_divide(ktnum, ktden) # Calculate transmission coefficient (last frame) tc = np.mean(kt[-1:]) # Calculate error bars sigmaK = (((np.std(lastnums)/ktnum[-1])**2) + ((np.std(lastdens)/ktden[-1])**2)-2*covariance(lastnums, lastdens)/(ktnum[-1]*ktden[-1]))**(1/2) sigmafile = open('sigma', 'w') sigmafile.write(str(sigmaK)) sigmafile.close() print("Transmission Coefficient Estimate: {0}".format(tc)) print("Saving data.") save_file = open("databc2", 'w') for frame in range(0,num_frames-1): save_file.write("{0} {1}\n".format(timelist[frame], kt[frame])) save_file.close() num_file = open('databc2num', 'w') for frame in range(0, num_frames-1): num_file.write("{0} {1}\n".format(timelist[frame], ktnum[frame])) num_file.close() den_file = open('databc2den', 'w') for frame in range(0, num_frames-1): den_file.write("{0} {1}\n".format(timelist[frame], ktden[frame])) den_file.close() if runtype == 'pf': print("Calculating the postive flux (PF) transmission coefficient.") for sim in range (1, num_simulations+1): sys.stdout.write("\rAnalyzing simulation {0}/{1}...".format(sim, num_simulations)) sys.stdout.flush() with open("{0}/distanceu.xvg".format(sim), "r") as f: udistfile = f.readlines() with open("{0}/distancel.xvg".format(sim), "r") as f: ldistfile = f.readlines() with open("{0}/velocityu.xvg".format(sim), "r") as f: uvelofile = f.readlines() with open("{0}/velocityl.xvg".format(sim), "r") as f: lvelofile = f.readlines() with open("{0}/dist.xvg".format(sim), "r") as f: distfile = f.readlines() with open("{0}/distr.xvg".format(sim), "r") as f: distrfile = f.readlines() # Check to see if the trajectory started at the right location. # If so, extract rdot(0): # Check to see if the trajectory started at the right location. # If so, extract rdot(0): tsloc = float(distfile[15].split()[1]) # Get COM of U, L UCOM = float(udistfile[24].split()[1]), float(udistfile[24].split()[2]), float(udistfile[24].split()[3]) LCOM = float(ldistfile[24].split()[1]), float(ldistfile[24].split()[2]), float(ldistfile[24].split()[3]) # Get COV of U, L UCOV = float(uvelofile[24].split()[1]), float(uvelofile[24].split()[2]), float(uvelofile[24].split()[3]) LCOV = float(lvelofile[24].split()[1]), float(lvelofile[24].split()[2]), float(lvelofile[24].split()[3]) # Calculate dx, dy, dz dx, dy, dz = minimage(UCOM[0]-LCOM[0], UCOM[1]-LCOM[1], UCOM[2]-LCOM[2]) # Calculate dvx, dvy, dvz dvx = UCOV[0]-LCOV[0] dvy = UCOV[1]-LCOV[1] dvz = UCOV[2]-LCOV[2] rdotzero = (dx*dvx + dy*dvy + dz*dvz)/(dx**2+dy**2+dz**2)**0.5 hs_rdotzero = heavyside(rdotzero) chilist = chi(backwards, tsloc) # And loop over all distances: i = 0 for fline, bline in zip(distfile[15:], distrfile[15:]): this_fline = fline.split() fdistance = float(this_fline[1]) this_bline = bline.split() bdistance = float(this_bline[1]) hs_rt_ts_loc = heavyside(fdistance - tsloc, i, rdz=rdotzero) hs_lt_ts_loc = heavyside(bdistance - tsloc, i, rdz=rdotzero) # Calculate k(t) for that frame, append to lists ktnum[i] += (rdotzero*hs_rdotzero*hs_rt_ts_loc) ktnum2[i] += (rdotzero*hs_rdotzero*hs_lt_ts_loc) ktden[i] += (rdotzero*hs_rdotzero) i += 1 print("Analysis finished. Producing final reactive flux function, kpf(t).") # Produce k(t) from numerator and denominator lists kt1 = list_divide(ktnum, ktden) kt2 = list_divide(ktnum2, ktden) kt = list_subtract(kt1, kt2) print("Transmission Coefficient Estimate: {0}".format(np.mean(kt[-200:]))) print("Saving data.") save_file = open("datapf", 'w') for frame in range(0,num_frames-1): save_file.write("{0} {1}\n".format(timelist[frame], kt[frame])) rdotzeros = [] if runtype == 'epf': print("Calculating the transmission coefficient via the effective positive flux (EPF) algorithm [RECOMMENDED].") for sim in range (1, num_simulations+1): sys.stdout.write("\rAnalyzing simulation {0}/{1}...".format(sim, num_simulations)) sys.stdout.flush() with open("{0}/distanceu.xvg".format(sim), "r") as f: udistfile = f.readlines() with open("{0}/distancel.xvg".format(sim), "r") as f: ldistfile = f.readlines() with open("{0}/velocityu.xvg".format(sim), "r") as f: uvelofile = f.readlines() with open("{0}/velocityl.xvg".format(sim), "r") as f: lvelofile = f.readlines() with open("{0}/dist.xvg".format(sim), "r") as f: distfile = f.readlines() with open("{0}/distr.xvg".format(sim), "r") as f: distrfile = f.readlines() # Check to see if the trajectory started at the right location. # If so, extract rdot(0): tsloc = float(distfile[15].split()[1]) # Get COM of U, L UCOM = float(udistfile[24].split()[1]), float(udistfile[24].split()[2]), float(udistfile[24].split()[3]) LCOM = float(ldistfile[24].split()[1]), float(ldistfile[24].split()[2]), float(ldistfile[24].split()[3]) # Get COV of U, L UCOV = float(uvelofile[24].split()[1]), float(uvelofile[24].split()[2]), float(uvelofile[24].split()[3]) LCOV = float(lvelofile[24].split()[1]), float(lvelofile[24].split()[2]), float(lvelofile[24].split()[3]) # Calculate dx, dy, dz dx, dy, dz = minimage(UCOM[0]-LCOM[0], UCOM[1]-LCOM[1], UCOM[2]-LCOM[2]) # Calculate dvx, dvy, dvz dvx = UCOV[0]-LCOV[0] dvy = UCOV[1]-LCOV[1] dvz = UCOV[2]-LCOV[2] # Calculate rdotzero and its heaviside rdotzero = (dx*dvx + dy*dvy + dz*dvz)/(dx**2+dy**2+dz**2)**0.5 hs_rdotzero = heavyside(rdotzero) rdotzeros.append(rdotzero*hs_rdotzero) # Calculate the CHI function. (see van erp paper/powerpoint) chilist = chi(distrfile[15:], tsloc) # And loop over all distances: i = 0 for fline in distfile[15:]: this_fline = fline.split() fdistance = float(this_fline[1]) hs_rt_ts_loc = heavyside(fdistance - tsloc, i, rdz=rdotzero) # Calculate k(t) for that frame, append to lists ktnum[i] += rdotzero*hs_rdotzero*chilist[i]*hs_rt_ts_loc ktden[i] += rdotzero*hs_rdotzero i += 1 # Save last frame of numerator and denominator to a list lastnums.append(rdotzero*hs_rdotzero*chilist[i-1]*hs_rt_ts_loc) lastdens.append(rdotzero*hs_rdotzero) print("Analysis finished.") # Produce k(t) from numerator and denominator lists kt = list_divide(ktnum,ktden) # Calculate error bars sigmaA = np.std(lastnums) sigmaB = np.std(lastdens) A = ktnum[-1]/num_simulations B = ktden[-1]/num_simulations print("A: {0}".format(A)) print("B: {0}".format(B)) print("sigA: {0}".format(sigmaA)) print("sigB: {0}".format(sigmaB)) sigmaK = kt[-1]*((sigmaA/A)**2 + (sigmaB/B)**2 - (2*covariance(lastnums,lastdens)/(A*B)))**(0.5) sigmaK = sigmaK/(num_simulations**0.5) sigmafile = open('sigma', 'w') sigmafile.write(str(sigmaK)) sigmafile.close() print("ERROR: {0}".format(sigmaK)) print("Transmission Coefficient: {0}".format(kt[-1])) print("Saving data.") save_file = open("transmissioncoefficient", 'w') for frame in range(0, num_frames-1): save_file.write("{0} {1}\n".format(timelist[frame], kt[frame])) save_file.close() print("wrote.") print("AVERAGE rdotzerohsrdotzero: {0}".format(np.mean(rdotzeros))) #num_file = open('databc2num', 'w') #for frame in range(0, num_frames-1): # num_file.write("{0} {1}\n".format(timelist[frame], ktnum[frame])) #num_file.close() #den_file = open('databc2den', 'w') #for frame in range(0, num_frames-1): # den_file.write("{0} {1}\n".format(timelist[frame], ktden[frame])) #den_file.close()
{ "repo_name": "hsidky/MolSimScripts", "path": "reactive_flux.py", "copies": "1", "size": "15340", "license": "mit", "hash": -8684718712658205000, "line_mean": 33.4719101124, "line_max": 143, "alpha_frac": 0.6468709257, "autogenerated": false, "ratio": 2.506126449926483, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3652997375626483, "avg_score": null, "num_lines": null }
#!/afs/cs.wisc.edu/u/r/c/rchat/honeyencryption/honeyvenv/bin/python import os, sys import string from Crypto.Random import random A = string.ascii_uppercase fact_map = [1, 2, 6, 24, 120, 720, # 1, 2, 3, 4, 5, 6, 5040, 40320, 362880, 3628800, 39916800, # 7, 8, 9, 10, 11 479001600 # 12 ] class DTE_random: punct = "!@#%&*_+=~" All = string.ascii_letters + string.digits + punct must_set = [punct, string.digits, string.ascii_uppercase, string.ascii_lowercase] def generate_and_encode_password(self, size=10): N = [random.randint(0,4294967295) for i in range(size)] P = [s[N[i]%len(s)] for i, s in enumerate(self.must_set)] P.extend(self.All[n%len(self.All)] for n in N[len(self.must_set):]) n = random.randint(0, fact_map[size-1]) password = decode2string(n, P) N.append(n) return password, N def decode_password(self, N): P = [s[N[i]%len(s)] for i, s in enumerate(self.must_set)] P.extend(self.All[n%len(self.All)] for n in N[len(self.must_set):-1]) n = N[-1] password = decode2string(n, P) return password def generate_random_password(self, size=10 ): """ Generates random password of given size it ensures - 1 uppercase 1 lowercase 1 digit 1 punc """ get_rand = lambda L, c: [random.choice(L) for i in range(c)] P = get_rand(punct, 1) P.extend( get_rand(string.digits, 1)) P.extend( get_rand(string.ascii_uppercase, 1)) P.extend( get_rand(string.ascii_lowercase, 1)) P.extend([random.choice(self.All) for i in range(size - len(P))]) n = random.randint(0, fact_map[size-1]) return n, decode2string(n, P) def permute(n): return ''.join([random.choice(A) for i in range(n)]) if __name__=="__main__": d = DTE_random() p, encoding = d.generate_and_encode_password(size=12) #print p, encoding print d.decode_password(encoding)
{ "repo_name": "rchatterjee/nocrack", "path": "test_r/permute_map.py", "copies": "1", "size": "2112", "license": "mit", "hash": -1603963206845356800, "line_mean": 30.0588235294, "line_max": 85, "alpha_frac": 0.5667613636, "autogenerated": false, "ratio": 3.0922401171303076, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9006536608116893, "avg_score": 0.03049297452268299, "num_lines": 68 }
# After a few requests, comments_data.content is the generic New York Times error page, but # comments_data does not have a 404 response or anything. It's a valid request, but NY Times # can't process it for whatever reason. The rate limit is 30 calls/second and 5000/day, so # that's not the issue. See if you can get it to work, I guess. # # I used simplejson, which you can install with pip, because it gives better error messages, # but you can just replace simplejson with json and it should work the same. # # This version is very error-tolerant. It can deal with invalid JSON and stores the results # for each day separately to guard against crashes. We then have to combine ~600 text files, # but this shouldn't be too hard, and is in my opinion worth it since the NY Times is so much # trouble. import requests, time, simplejson, sys from datetime import date, datetime, timedelta def perdelta(start, end, delta): curr = start while curr < end: yield curr curr += delta # Scrape 300 comments per day from Nov. 1, 2014 to Oct. 31, 2015 for da in perdelta(date(2015, 2, 21), date(2015, 11, 1), timedelta(days=1)): comments = [] print da skip = False gotany = True for i in range(12): # collect 25*12=300 comments if not skip: success = False count = 0 url = ('http://api.nytimes.com/svc/community/v3/user-content/' + 'by-date.json?api-key=KEY&date=' + str(da) + '&offset=' + str(25*i)) while not success: comments_data = requests.get(url) try: data = simplejson.loads(comments_data.content) success = True # go to the next offset for d in data['results']['comments']: comments.append(d) time.sleep(2) except: print 'error on {}'.format(str(da)) print url count += 1 if count > 3: success = True # not really skip = True # just skip to the next day if i == 0: gotany = False # if we didn't get any comments from that day time.sleep(2) if gotany: filestr = 'comments {}.json'.format(str(da)) with open(filestr, 'w') as f: simplejson.dump(comments, f) # Short script to combine all the JSON lists into one allcomments = [] for d in perdelta(date(2014, 1, 1), date(2015, 12, 31), timedelta(days=1)): try: with open('comments {}.json'.format(str(d))) as f: c = simplejson.load(f) allcomments.extend(c) except: pass
{ "repo_name": "CS109-comment/NYTimes-Comment-Popularity-Prediction", "path": "scrape.py", "copies": "1", "size": "2796", "license": "mit", "hash": -8105923910805024000, "line_mean": 40.7462686567, "line_max": 93, "alpha_frac": 0.5733190272, "autogenerated": false, "ratio": 4.081751824817518, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.007367950897156962, "num_lines": 67 }
"""After analysis with WiFeS, this suite of routines can extract a star optimally and calculate its radial velocity. WARNING - this code is still not properly documented or complete. Any contributions welcome! example lines of code... Executing from the code directory, e.g. with Margaret's output directory: rv_process_dir('PROCESSED_DATA_DIRECTORY', outdir =/priv/mulga1/mstream/wifes/wifes/tools') fn = 'T2m3wr-20140617.144009-0167.p11.fits' flux,sig,wave = read_and_find_star_p11(fn) """ from __future__ import print_function try: import pyfits except: import astropy.io.fits as pyfits import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import scipy.optimize as op import pdb import glob import pickle from readcol import readcol from scipy.interpolate import InterpolatedUnivariateSpline from mpl_toolkits.mplot3d import Axes3D from astropy.modeling import models, fitting plt.ion() def find_nearest(array,value): idx = (np.abs(array-value)).argmin() return array[idx] def onclick(event): global ix, iy ix, iy = event.xdata, event.ydata # print 'x = %d, y = %d'%( # ix, iy) # assign global variable to access outside of function global coords coords.append((ix, iy)) # Disconnect after 2 clicks if len(coords) == 2: fig.canvas.mpl_disconnect(cid) plt.close(1) return coords = [] def read_and_find_star_p11(fn, manual_click=False, npix=7, subtract_sky=True,sky_rad=2): """Read in a cube and find the star. Return a postage stamp around the star and the coordinates within the stamp NB This didn't really work as the details of flux calibration doesn't easily enable optimal extraction. This function should probably be REMOVED. """ a = pyfits.open(fn) #Assume Stellar mode. flux = a[0].data[:,:,13:] sig = a[1].data[:,:,13:] image = np.median(flux,axis=0) maxpx = np.unravel_index(np.argmax(image[1:-1,1:-1]),image[1:-1,1:-1].shape) maxpx = (maxpx[0]+1,maxpx[1]+1) plt.clf() plt.imshow(image,interpolation='nearest') plt.plot(maxpx[1],maxpx[0],'wx') if subtract_sky: xy = np.meshgrid(range(image.shape[1]),range(image.shape[0])) dist = np.sqrt((xy[0]-maxpx[1])**2.0 + (xy[1]-maxpx[0])**2.0) sky = np.where( (xy[0] > 0) & (xy[1] > 0) & (xy[0] < image.shape[1]-1) & (xy[1] < image.shape[0]-1) & (dist > sky_rad) & (dist < image.shape[1])) for i in range(flux.shape[0]): flux[i,:,:] -= np.median(flux[i,sky[0],sky[1]]) ymin = np.min([np.max([maxpx[0]-3,0]),image.shape[0]-npix]) xmin = np.min([np.max([maxpx[1]-3,0]),image.shape[1]-npix]) flux_stamp = flux[:,ymin:ymin+npix,xmin:xmin+npix] sig_stamp = sig[:,ymin:ymin+npix,xmin:xmin+npix] wave = a[0].header['CRVAL3'] + np.arange(flux.shape[0])*a[0].header['CDELT3'] return flux_stamp,sig_stamp,wave def read_and_find_star_p08(fn, manual_click=False, npix=7, subtract_sky=True, sky_rad=2, fig_fn='', fig_title=None, do_median_subtraction=False, arm=None,min_slit_i=0,): """Read in a cube and find the star. Return a postage stamp around the star and the wavelength scale NB This didn't really work as the details of flux calibration doesn't easily enable optimal extraction. Note: This may give unexpected results when more than a single star is within the IFU. Parameters ---------- fn: string filename npix: int Number of pixels to extract """ a = pyfits.open(fn) Obj_name = a[0].header['OBJNAME'] Obs_date = a[0].header['DATE-OBS'].split('T')[0] RA = a[0].header['RA'] DEC = a[0].header['DEC'] # Determine the spectrograph mode # ccd_sec has form [x_min:x_max, y_min:y_max] y_min = int(a[0].header["CCDSEC"].split(",")[-1].split(":")[0]) # Using Full Frame if y_min == 1: flux = np.array([a[i].data for i in range(1,26)]) # Stellar mode (i.e. half frame) else: flux = np.array([a[i].data for i in range(1,13)]) wave = a[1].header['CRVAL1'] + np.arange(flux.shape[2])*a[1].header['CDELT1'] image = np.median(flux,axis=2) if do_median_subtraction: image = np.log10(image) image -= np.median(image) #!!! 1->7 is a HACK - because WiFeS seems to often fail on the edge pixels !!! plt.clf() global fig fig = plt.figure(1) plt.imshow(image,interpolation='nearest') # Set title if fig_title is not None: plt.title(fig_title) if manual_click == True: global coords # Call click func global cid cid = fig.canvas.mpl_connect('button_press_event', onclick) plt.show(1) maxpx = (int(round(np.min([coords[0][1], coords[1][1]]))), int(round(np.min([coords[0][0], coords[1][0]])))) coords = [] else: maxpx = np.unravel_index(np.argmax(image[:,10:-10]),image[:,10:-10].shape) maxpx = (maxpx[0],maxpx[1]+10) # Plotting image plt.close("all") fig, axes = plt.subplots(2,2) ax_im, ax_y, ax_x, _ = axes.flatten() _.set_visible(False) im_cmap = ax_im.imshow(image,interpolation='nearest') cb = fig.colorbar(im_cmap, ax=ax_im, fraction=0.0155, pad=0.0) ax_im.plot(maxpx[1],maxpx[0],'wx') fig.suptitle(str(Obj_name) + '_' + str(Obs_date) + '_(' + str(RA) + ',' + str(DEC) + ')_' + arm) # Plotting X and Y distributions ax_y.plot(np.log10(np.sum(image[:,min_slit_i:], axis=1)), np.arange(image.shape[0]), "r.-") ax_y.set_ylim(image.shape[0],0) #ax_y.set_xscale('log') ax_x.plot(np.arange(image.shape[1]), np.log10(np.sum(image, axis=0)), ".-") #ax_x.set_yscale('log') # Set aspect the same asp_im = np.abs(float(np.diff(ax_im.get_xlim())[0]) / np.diff(ax_im.get_ylim())[0]) asp_x = float(np.diff(ax_x.get_xlim())[0]) / np.diff(ax_x.get_ylim())[0] asp_y = float(np.diff(ax_y.get_xlim())[0]) / -np.diff(ax_y.get_ylim())[0] ax_x.set_aspect(asp_x/asp_im) ax_y.set_aspect(asp_y/asp_im) ax_x.set_xlabel('x pixel') ax_x.set_ylabel(r'$\log_{10}$(x counts)') ax_im.set_ylabel('y pixel') ax_y.set_xlabel(r'$\log_{10}$(y counts)') cb.ax.tick_params(labelsize="xx-small") ax_im.tick_params(axis='both', which='major', labelsize="xx-small") ax_x.tick_params(axis='both', which='major', labelsize="xx-small") ax_y.tick_params(axis='both', which='major', labelsize="xx-small") # Plot sum along y axis #ax_y.plot(np.sum(maxpx[0], axis=0), np.arange(maxpx.shape[0]), ".-") #ax_x.plot(np.arange(maxpx.shape[1]), np.sum(maxpx[0], axis=0), ".-") # Sky Subtraction if subtract_sky: xy = np.meshgrid(range(image.shape[1]),range(image.shape[0])) dist = np.sqrt((xy[0]-maxpx[1])**2.0 + (xy[1]-maxpx[0])**2.0) sky = np.where( (xy[0] > 0) & (xy[1] > 0) & (xy[0] < image.shape[1]-1) & (xy[1] < image.shape[0]-1) & (dist > sky_rad) & (dist < image.shape[1])) for i in range(flux.shape[2]): flux[:,:,i] -= np.median(flux[sky[0],sky[1],i]) ymin = np.min([np.max([maxpx[0]-npix//2,0]),image.shape[0]-npix]) xmin = np.min([np.max([maxpx[1]-npix//2,0]),image.shape[1]-npix]) flux_stamp = flux[ymin:ymin+npix,xmin:xmin+npix,:] # Offset mins so plotted lines are at edge of pixels xminp = xmin - 0.5 yminp = ymin - 0.5 # Plot vertical bounds ax_im.plot([xminp, xminp], [yminp+npix, yminp], c="r") ax_im.plot([xminp+npix, xminp+npix], [yminp+npix, yminp], c="r") # Plot horizontal bounds ax_im.plot([xminp, xminp+npix], [yminp+npix, yminp+npix], c="r") ax_im.plot([xminp, xminp+npix], [yminp, yminp], c="r") if len(fig_fn)>0: #plt.gcf().set_size_inches(5*asp_im, 5/asp_im) plt.savefig(fig_fn, bbox_inches='tight') return flux_stamp,wave def weighted_extract_spectrum(flux_stamp, readout_var=11.0): """Optimally extract the spectrum based on a constant weighting Based on a p08 file axis ordering. Readout variance is roughly 11 in the p08 extracted spectra Parameters ---------- flux_stamp: numpy array nx x ny x nwave IFU image as a function of wavelength readout_var: float (optional) Readout variance in extracted spectrum in DN. TODO: 1) Look for and remove bad pix/cosmic rays. 2) Remove dodgy constant for readout_var. """ #Find the median flux over all wavelengths, limiting to be >0 flux_med = np.maximum(np.median(flux_stamp,axis=2),0) pixel_var = flux_med + readout_var weights = flux_med/pixel_var n_spaxels = np.prod(weights.shape) #Form a weighted average, then multiply by n_spaxels to get a sum spectrum = n_spaxels * np.array( [np.sum(flux_stamp[:,:,i]*weights)/np.sum(weights) for i in range(flux_stamp.shape[2])]) spectrum = np.array([ np.sum(flux_stamp[:,:,i]*weights) for i in range(flux_stamp.shape[2])]) #Old calculation of sigma. Lets be a little more readable! sig = np.array([np.sqrt(np.sum((np.maximum(flux_stamp[:,:,i],0)+readout_var)*weights**2)) for i in range(flux_stamp.shape[2])]) #The variance of each pixel is flux_stamp + readout_var, with flux_stamp being an estimate #of flux per pixel, which should not be less than zero. #var = [np.sum((np.maximum(flux_stamp[:,:,i],0)+readout_var)*weights**2)/np.sum(weights)**2 for i in range(flux_stamp.shape[2])] #sig = n_spaxels * np.sqrt(np.array(var)) return spectrum,sig def conv_ambre_spect(ambre_dir,ambre_conv_dir): """Take all the AMBRE spectra from a directory, convolve and re-sample by a factor of 10, then save to a new directory""" infns = glob.glob(ambre_dir + '/*fits') for infn in infns: data = pyfits.getdata(infn) data = np.convolve(data,np.ones(10)/10., 'same') conv_data = data[10*np.arange(90000,dtype='int')].astype('float32') ix_start = infn.rfind('/') + 1 ix_end = infn.rfind('.') outfn = infn[ix_start:ix_end] + 'conv.fits' pyfits.writeto(ambre_conv_dir + '/' + outfn,conv_data, clobber=True) def conv_tlusty_spect(tlusty_dir,tlusty_conv_dir): """ Take all Tlusty spectra from a directory, convole to 0.1A, then save to a new directory Currently resampling onto a wavelength grid of 0.1A also, from 3000 to 12000A to match AMBRE spectra, note Tlusty only covers 3000A to 10000A also mostly matching filenames """ infns = glob.glob(tlusty_dir + '/*.vis.7') for ii,infn in enumerate(infns): indata = readcol(infn) wav = indata[:,0] data = indata[:,1] cdata = np.convolve(data,np.ones(10)/10.0,'same') intwav = 0.1*np.arange(90000)+3000.0 icdata = np.interp(intwav,wav,cdata) n1 = infn.split('/')[-1].split('BG')[1].split('g') n2 = 'g+'+str(float(n1[1].split('v')[0])/100.0) n1 = 'p'+str(int(n1[0])/1) outname = tlusty_conv_dir+'/'+n1 + ':'+n2+':m0.0:t01:z+0.00:a+0.00.TLUSTYconv.fits' pyfits.writeto(outname,icdata,clobber=True) print('convolving '+ str(ii+1) +' out of ' + str(len(infns))) def conv_phoenix_spect(pho_dir,pho_conv_dir): """ Take all phoenix spectra from a directory, convolve to 0.1A, then save to a new directory Currently resampling onto a wavelength grid of 0.1A also, from 3000 to 12000A to match AMBRE spectra also mostly matching filenames """ infns = glob.glob(pho_dir + '/*.fits') for ii,infn in enumerate(infns): data = pyfits.getdata(infn) wav = pyfits.getdata('WAVE_PHOENIX-ACES-AGSS-COND-2011.fits') ##go from vacuum to air wavelengths wav = wav/(1.0+2.735182E-4+131.4182/wav**2+2.76249e8/wav**4) cdata = np.convolve(data,np.ones(10)/10.0,'same') intwav = 0.1*np.arange(90000)+3000.0 icdata = np.interp(intwav,wav,cdata) n1 = infn.split('/')[-1].split('lte')[1].split('-') n2 = 'g'+n1[1] n1 = 'p'+n1[0] outname = pho_conv_dir+'/'+n1 + ':'+n2+':m0.0:t01:z+0.00:a+0.00.PHOENIXconv.fits' pyfits.writeto(outname,icdata,clobber=True) print('convolving '+ str(ii+1) +' out of ' + str(len(infns))) def make_wifes_p08_template(fn, out_dir,rv=0.0): """From a p08 file, create a template spectrum for future cross-correlation. The template is interpolated onto a 0.1 Angstrom grid (to match higher resolution templates. Parameters ---------- ddir: string Data directory for the p08 file fn: string p08 fits filename out_dir: string Output directory """ flux_stamp,wave = read_and_find_star_p08(fn) heliocentric_correction = pyfits.getheader(fn)['RADVEL'] star = pyfits.getheader(fn)['OBJECT'] spectrum,sig = weighted_extract_spectrum(flux_stamp) dell_template = 0.1 wave_template=np.arange(90000)*dell_template + 3000 spectrum_interp = np.interp(wave_template,wave*(1 - (rv - heliocentric_correction)/2.998e5),spectrum) outfn = out_dir + star + ':' + fn.split('/')[-1] pyfits.writeto(outfn,spectrum_interp,clobber=True) def rv_fit_mlnlike(shift,modft,data,errors,gaussian_offset): """Return minus the logarithm of the likelihood of the model fitting the data Parameters ---------- shift: float Shift in pixels modft: array-like Real numpy Fourier transform of the model spectrum. data: array-like spectral data. errors: array-like uncertainties in spectral data gaussian_offset: float Offset to Gaussian uncertainty distribution """ shifted_mod = np.fft.irfft(modft * np.exp(-2j * np.pi * np.arange(len(modft))/len(data) * shift)) return -np.sum(np.log(np.exp(-(data - shifted_mod)**2/2.0/errors**2) + gaussian_offset)) def rv_shift_binary(shift1, shift2, alpha, modft1, modft2): """Shift two templates and add them, to model a binary star""" data_len = (len(modft1)-1)*2 shifted_mod1 = np.fft.irfft(modft1 * np.exp(-2j * np.pi * np.arange(len(modft1))/data_len * shift1)) shifted_mod2 = np.fft.irfft(modft2 * np.exp(-2j * np.pi * np.arange(len(modft2))/data_len * shift2)) return (shifted_mod1 + alpha*shifted_mod2)/(1.0 + alpha) def make_fake_binary(spect,wave,sig, template_fns, flux_ratio, rv0, rv1): """Make a fake binary in order to test todcor etc!""" # (wave_log, spect_int, sig_int, template_ints) = \ # interpolate_spectra_onto_log_grid(spect,wave,sig, template_fns) wave_templates = [] spect_templates = [] for template_fn in template_fns: dd = np.loadtxt(template_fn) wave_templates.append(dd[:,0]) spect_templates.append(dd[:,1]) wave_templates = np.array(wave_templates) spect_templates = np.array(spect_templates) c_light = 3e5 fake_binary = np.interp(wave_templates[0]*(1 - rv0/c_light),wave_templates[0], spect_templates[0]) + \ np.interp(wave_templates[0]*(1 - rv1/c_light),wave_templates[1], spect_templates[1])*flux_ratio #fake_binary = np.interp(wave_log*(1 - rv0/c_light),wave_log, template_ints[0]) + \ # np.interp(wave_log*(1 - rv1/c_light),wave_log, template_ints[1])*flux_ratio #Un-continuum-subtract #binspect = fake_binary + 1 #return binspect, wave_log, np.ones(len(binspect))*0.01 return fake_binary, wave_templates[0], np.ones(len(wave_templates[0]))*0.01 def interpolate_spectra_onto_log_grid(spect,wave,sig, template_dir,bad_intervals=[],\ smooth_distance=201,convolve_template=True, nwave_log=int(1e4), \ subtract_smoothed=True, interp_k=1): """Interpolate both the target and template spectra onto a common wavelength grid""" #Create our logarithmic wavelength scale with the same min and max wavelengths as the #target spectrum, and nwave_log wavelengths. wave_log = np.min(wave)*np.exp( np.log(np.max(wave)/np.min(wave))/\ nwave_log*np.arange(nwave_log)) #Interpolate the target spectrum onto this scale #spect_int = np.interp(wave_log,wave,spect) #sig_int = np.interp(wave_log,wave,sig) spl = InterpolatedUnivariateSpline(wave, spect, k=interp_k) spect_int = spl(wave_log) spl = InterpolatedUnivariateSpline(wave, sig, k=interp_k) sig_int = spl(wave_log) #Normalise sig_int /= np.median(spect_int) spect_int /= np.median(spect_int) #Remove bad intervals for interval in bad_intervals: wlo = np.where(wave_log > interval[0])[0] if len(wlo)==0: continue whi = np.where(wave_log > interval[1])[0] if len(whi)==0: whi = [len(wave_log)-1] whi = whi[0] wlo = wlo[0] spect_int[wlo:whi] = spect_int[wlo] + np.arange(whi-wlo,dtype='float')/(whi-wlo)*(spect_int[whi] - spect_int[wlo]) sig_int[wlo:whi]=1 if subtract_smoothed: #Subtract smoothed spectrum spect_int -= spect_int[0] + np.arange(len(spect_int))/(len(spect_int)-1.0)*(spect_int[-1]-spect_int[0]) spect_int -= np.convolve(spect_int,np.ones(smooth_distance)/smooth_distance,'same') #Now we find the interpolated template spectra, template_ints template_fns = template_dir template_ints = np.zeros( (len(template_fns),len(wave_log)) ) for i,template_fn in enumerate(template_fns): try: #Try loading a reduced WiFeS file first... if template_fn.find("p08") >= len(template_fn) - 8: print('Using raw wifes p08 file') flux,wave_template=read_and_find_star_p08(template_fn) spect_template,dummy = weighted_extract_spectrum(flux) dell_template = np.mean(wave_template[1:]-wave_template[:-1]) #Try loading pickled RV standards elif template_fn.find('pkl') >= len(template_fn)-4: print('Using pickled Standards') template_file = open(template_fn, 'r') wave_template, spect_template = pickle.load(template_file) dell_template = np.mean(wave_template[1:]-wave_template[:-1]) #Next try a template text file (wavelength and flux in 2 columns) elif template_fn.find('txt') >= len(template_fn)-4: print('Using text file input') dd = np.loadtxt(template_fn) dell_template = np.mean(dd[1:,0]-dd[:-1,0]) wave_template = dd[:,0] spect_template = dd[:,1] #Finally try the Ambre convolved spectral format. elif template_fn.find('fit') >= len(template_fn)-4: print('Using ambre models (fits with fixed wavelength grid)') spect_template = pyfits.getdata(template_fn) dell_template = 0.1 wave_template=np.arange(90000)*dell_template + 3000 else: print('Invalid rv standard or model file: ' + template_fn) raise UserWarning except: print('Error loading model spectrum') raise UserWarning if convolve_template: #Amount of subsampling in the template template_subsamp = int((wave[1]-wave[0])/dell_template) #Make sure it is an odd number to prevent shifting... template_subsamp = np.maximum((template_subsamp//2)*2 - 1,1) spect_template = np.convolve(np.convolve(spect_template,np.ones(template_subsamp)/template_subsamp,'same'),\ np.ones(2*template_subsamp+1)/(2*template_subsamp+1),'same') #Interpolate onto the log wavelength grid. #template_int = np.interp(wave_log,wave_template,spect_template) spl = InterpolatedUnivariateSpline(wave_template,spect_template, k=interp_k) template_int = spl(wave_log) #Normalise template_int /= np.median(template_int) #Remove bad intervals for interval in bad_intervals: wlo = np.where(wave_log > interval[0])[0] if len(wlo)==0: continue whi = np.where(wave_log > interval[1])[0] if len(whi)==0: whi = [len(wave_log)-1] whi = whi[0] wlo = wlo[0] template_int[wlo:whi] = template_int[wlo] + np.arange(whi-wlo, dtype='float')/(whi-wlo)*(template_int[whi] - template_int[wlo]) if subtract_smoothed: #Subtract smoothed spectrum template_int -= template_int[0] + np.arange(len(template_int))/(len(template_int)-1.0)*(template_int[-1]-template_int[0]) template_int -= np.convolve(template_int,np.ones(smooth_distance)/smooth_distance,'same') template_ints[i,:] = template_int return wave_log, spect_int, sig_int, template_ints def calc_rv_template(spect,wave,sig, template_dir,bad_intervals,smooth_distance=101, \ gaussian_offset=1e-4,nwave_log=1e4,oversamp=1,fig_fn='',convolve_template=True,\ starnumber=0, plotit=False, save_figures=False, save_dir='./', heliocentric_correction=0.): """Compute a radial velocity based on an best fitting template spectrum. Teff is estimated at the same time. Parameters ---------- spect: array-like The reduced WiFeS spectrum wave: array-like The wavelengths corresponding to the reduced WiFeS spectrum template_conv_dir: string The directory containing template spectra convolved to 0.1 Angstrom resolution bad_intervals: List of wavelength intervals where e.g. telluric absorption is bad. smooth_distance: float Distance to smooth for "continuum" correction oversamp: float Oversampling of the input wavelength scale. The slit is assumed 2 pixels wide. gaussian_offset: float Offset for the likelihood function from a Gaussian normalised to 1. Returns ------- rv: float Radial velocity in km/s rv_sig: float Uncertainty in radial velocity (NB assumes good model fit) temp: int Temperature of model spectrum used for cross-correlation. """ if isinstance(template_dir, list): template_fns = template_dir else: template_fns = glob.glob(template_dir) #ADD IN HELIOCENTRIC CORRECTION SOMEWHERE: #Make the Heliocentric correction... #rv += h['RADVEL'] #Interpolate the target and template spectra. (wave_log, spect_int, sig_int, template_ints) = interpolate_spectra_onto_log_grid(spect,wave,sig, template_fns,bad_intervals=bad_intervals, smooth_distance=smooth_distance,convolve_template=convolve_template, nwave_log=nwave_log) #Do a cross-correlation to the nearest "spectral pixel" for each template drv = np.log(wave_log[1]/wave_log[0])*2.998e5 rvs = np.zeros(len(template_fns)) peaks = np.zeros(len(template_fns)) for i,template_fn in enumerate(template_fns): template_int = template_ints[i] if save_figures == True: plt.clf() plt.plot(wave_log, template_int, label='template') plt.plot(wave_log, spect_int, label='spectrum') plt.title('Template no.'+str(i+1)) plt.savefig(save_dir + 'spectrum_vs_template_' + template_fns[i].split('/')[-1].split('.fits')[0] + '.png') plt.clf() cor = np.correlate(spect_int,template_int,'same') ##here it's a good idea to limit where the peak Xcorrelation can be, only search for a peak within 1000 of rv=0 ## that's and RV range of -778 to 778 for the default spacings in the code peaks[i] = np.max(cor[int(nwave_log/2)-100:int(nwave_log/2)+100])/np.sqrt(np.sum(np.abs(template_int)**2)) rvs[i] = (np.argmax(cor[int(nwave_log/2)-100:int(nwave_log/2)+100])-100)*drv if starnumber == 0: print('Correlating Template ' + str(i+1)+' out of ' + str(len(template_fns))) if starnumber >0 : print('Correlating Template ' + str(i+1)+' out of ' + str(len(template_fns)) +' for star '+str(starnumber)) this_rvs = drv*(np.arange(2*smooth_distance)-smooth_distance) correlation = cor[int(nwave_log/2)-100:int(nwave_log/2)+100]/np.sqrt(np.sum(np.abs(template_int)**2)) best_ind = np.argmax(correlation) print("best RV for template "+str(i+1)+" is "+str(this_rvs[best_ind+1] + heliocentric_correction)) if save_figures == True: plt.clf() plt.plot(this_rvs[1:-1], correlation/np.max(correlation)) plt.title('Correlation_with_template_no.'+str(i+1)) plt.savefig(save_dir + 'Correlation_with_template_no' + str(i+1) + '.png') plt.clf() #Find the best cross-correlation. ix = np.argmax(peaks) print("BEST TEMPLATE:"+template_fns[ix].split('/')[-1]) #Recompute and plot the best cross-correlation template_int = template_ints[ix,:] cor = np.correlate(spect_int,template_int,'same') plt.clf() plt.plot(drv*(np.arange(2*smooth_distance)-smooth_distance), cor[int(nwave_log/2)-smooth_distance:int(nwave_log/2)+smooth_distance]) ##store the figure data for later use outsave = np.array([drv*(np.arange(2*smooth_distance)-smooth_distance),cor[int(nwave_log/2)-smooth_distance:int(nwave_log/2)+smooth_distance]]) saveoutname = fig_fn.split('.png')[0] + "_figdat.pkl" pickle.dump(outsave,open(saveoutname,"wb")) plt.xlabel('Velocity (km/s)') plt.ylabel('X Correlation') #plt.show() fn_ix = template_fns[ix].rfind('/') #Dodgy! Need a better way to find a name for the template. fn_ix_delta = template_fns[ix][fn_ix:].find(':') if fn_ix_delta>0: name = template_fns[ix][fn_ix+1:fn_ix+fn_ix_delta] name_string=name #A little messy !!! if name[0]=='p': name = name[1:] name_string = 'T = ' + name + ' K' name_string = template_fns[ix][fn_ix+1:] #pdb.set_trace() #Fit for a precise RV... note that minimize (rather than minimize_scalar) failed more #often for spectra that were not good matches. modft = np.fft.rfft(template_int) #res = op.minimize(rv_fit_mlnlike,rvs[ix]/drv,args=(modft,spect_int,sig_int,gaussian_offset)) #x = res.x[0] #res = op.minimize_scalar(rv_fit_mlnlike,args=(modft,spect_int,sig_int,gaussian_offset),bounds=((rvs[ix]-1)/drv,(rvs[ix]+1)/drv)) #x = res.x #fval = res.fun x,fval,ierr,numfunc = op.fminbound(rv_fit_mlnlike,rvs[ix]/drv-5/drv,rvs[ix]/drv+5/drv,args=(modft,spect_int,sig_int,gaussian_offset),full_output=True) rv = x*drv rv += heliocentric_correction ##best model shifted_mod = np.fft.irfft(modft * np.exp(-2j * np.pi * np.arange(len(modft))/len(spect_int) * x)) #pdb.set_trace() fplus = rv_fit_mlnlike(x+0.5,modft,spect_int,sig_int,gaussian_offset) fminus = rv_fit_mlnlike(x-0.5,modft,spect_int,sig_int,gaussian_offset) hess_inv = 0.5**2/(fplus + fminus - 2*fval) if (hess_inv < 0) | (fplus < fval) | (fminus < fval): #If you get here, then there is a problem with the input spectrum or fitting. #raise UserWarning print("WARNING: Radial velocity fit did not work - trying again with wider range for: " + fig_fn) x,fval,ierr,numfunc = op.fminbound(rv_fit_mlnlike,rvs[ix]/drv-10/drv,rvs[ix]/drv+10/drv,args=(modft,spect_int,sig_int,gaussian_offset),full_output=True) rv = x*drv #print("RV ="+str(rv)+", fval ="+str(fval)) fplus = rv_fit_mlnlike(x+0.5,modft,spect_int,sig_int,gaussian_offset) #print("fplus ="+str(fplus)) fminus = rv_fit_mlnlike(x-0.5,modft,spect_int,sig_int,gaussian_offset) #print("fminus ="+str(fminus)) hess_inv = 0.5**2/(fplus + fminus - 2*fval) #print("hess_inv ="+str(hess_inv)) #import pdb #pdb.set_trace() if (hess_inv < 0) | (fplus < fval) | (fminus < fval): print("WARNING: Radial velocity fit did not work, giving up with NaN uncertainty") rv_sig = np.sqrt(hess_inv*nwave_log/len(spect)/oversamp)*drv plt.title('RV, RV_sigma:' + str(rv) + ',' +str(rv_sig)) plt.savefig(save_dir + 'Best_correlation_temp_' + template_fns[ix].split('/')[-1] + '.png') plt.title(name_string + ', RV = {0:4.1f}+/-{1:4.1f} km/s'.format(rv,rv_sig)) if len(fig_fn) > 0: plt.savefig(fig_fn) plt.clf() plt.plot(wave_log,spect_int) plt.plot(wave_log,shifted_mod) plt.xlim([6400.0,6700.0]) plt.title(name_string + ', RV = {0:4.1f}+/-{1:4.1f} km/s'.format(rv,rv_sig)) if len(fig_fn) > 0: fig_fn_new = fig_fn.split('_xcor.png')[0] + 'fitplot.png' plt.savefig(fig_fn_new) #again save the figure data for use later in making nicer plots with IDL outsave = np.array([wave_log,spect_int,shifted_mod]) saveoutname = fig_fn.split('_xcor.png')[0] + 'fitplot_figdat.pkl' pickle.dump(outsave,open(saveoutname,"wb")) # pdb.set_trace() return rv,rv_sig,template_fns[ix].split('/')[-1] def calc_rv_todcor(spect,wave,sig, template_fns,bad_intervals=[],fig_fn='',\ smooth_distance=201,convolve_template=True, alpha=0.3,\ nwave_log=int(1e4),ncor=1000, return_fitted=False,jd=0.0,out_fn='',\ heliocentric_correction=0, plotit=False, window_divisor=20): """Compute a radial velocity based on an best fitting template spectrum. Teff is estimated at the same time. Parameters ---------- spect: array-like The reduced WiFeS spectrum wave: array-like The wavelengths corresponding to the reduced WiFeS spectrum template_fns: string Spectral template for star 1 and star 2 that can be read in by np.loadtxt bad_intervals: List of wavelength intervals where e.g. telluric absorption is bad. For todcor, These can only be smoothed over. smooth_distance: float Distance to smooth for "continuum" correction Returns ------- rv1: float Radial velocity of star 1 in km/s rv_sig1: float Uncertainty in radial velocity (NB assumes good model fit) rv2: float Radial velocity of star 1 in km/s rv_sig2: float Uncertainty in radial velocity (NB assumes good model fit) corpeak: float Correlation peak """ (wave_log, spect_int, sig_int, template_ints) = \ interpolate_spectra_onto_log_grid(spect,wave,sig, template_fns,\ bad_intervals=bad_intervals, smooth_distance=smooth_distance, \ convolve_template=convolve_template, nwave_log=nwave_log) rvs = np.zeros(len(template_fns)) peaks = np.zeros(len(template_fns)) drv = np.log(wave_log[1]/wave_log[0])*2.998e5 #*** Next (hopefully with two templates only!) we continue and apply the TODCOR algorithm. window_width = nwave_log//window_divisor ramp = np.arange(1,window_width+1,dtype=float)/window_width window = np.ones(nwave_log) window[:window_width] *= ramp window[-window_width:] *= ramp[::-1] template_ints[0] *= window template_ints[1] *= window spect_int *= window norm1 = np.sqrt(np.sum(template_ints[0]**2)) norm2 = np.sqrt(np.sum(template_ints[1]**2)) norm_tgt = np.sqrt(np.sum(spect_int**2)) #pdb.set_trace() c1 = np.fft.irfft(np.conj(np.fft.rfft(template_ints[0]/norm1))*np.fft.rfft(spect_int/norm_tgt)) c1 = np.roll(c1,ncor//2)[:ncor] c2 = np.fft.irfft(np.conj(np.fft.rfft(template_ints[1]/norm2))*np.fft.rfft(spect_int/norm_tgt)) c2 = np.roll(c2,ncor//2)[:ncor] #Unclear which way around this line should be. ix_c12 sign was corrected in order to #give the right result with simulated data. c12 = np.fft.irfft(np.fft.rfft(template_ints[1]/norm2)*np.conj(np.fft.rfft(template_ints[0]/norm1))) c12 = np.roll(c12,ncor//2)[:ncor] ix = np.arange(ncor).astype(int) xy = np.meshgrid(ix,ix) #Correct the flux ratio for the RMS spectral variation. Is this needed??? alpha_norm = alpha * norm2/norm1 ix_c12 = np.minimum(np.maximum(xy[0]-xy[1]+ncor//2,0),ncor-1) #!!!This was the old line !!! #ix_c12 = np.minimum(np.maximum(xy[1]-xy[0]+ncor//2,0),ncor-1) #XXX New (temporary?) line XXX todcor = (c1[xy[0]] + alpha_norm*c2[xy[1]])/np.sqrt(1 + 2*alpha_norm*c12[ix_c12] + alpha_norm**2) print("Max correlation: {0:5.2f}".format(np.max(todcor))) #print(alpha_norm) #plt.plot(drv*(np.arange(nwave_log)-nwave_log//2),np.roll(c1,nwave_log//2)) #Figure like TODCOR paper: #fig = plt.figure() #ax = fig.gca(projection='3d') #ax.plot_surface(xy[0],xy[1],todcor) plt.clf() plt.imshow(todcor, cmap=cm.gray,interpolation='nearest',extent=[-drv*ncor/2,drv*ncor/2,-drv*ncor/2,drv*ncor/2]) xym = np.unravel_index(np.argmax(todcor), todcor.shape) old_fit = False if (old_fit): hw_fit = 1 #2 if (xym[0]< hw_fit) | (xym[1]< hw_fit) | (xym[0]>= ncor-hw_fit) | (xym[1]>= ncor-hw_fit): print("Error: TODCOR peak to close to edge!") raise UserWarning ix_fit = np.arange(-hw_fit, hw_fit + 1).astype(int) xy_fit = np.meshgrid(ix_fit,ix_fit) p_init = models.Gaussian2D(amplitude=np.max(todcor),x_mean=0, y_mean=0, x_stddev = 50.0/drv, y_stddev = 50.0/drv) fit_p = fitting.LevMarLSQFitter() p = fit_p(p_init, xy_fit[0], xy_fit[1], todcor[xym[0]-hw_fit:xym[0]+hw_fit+1, xym[1]-hw_fit:xym[1]+hw_fit+1]) rv_x = drv*((p.parameters[1] + xym[1]) - ncor//2) rv_y = drv*((p.parameters[2] + xym[0]) - ncor//2) else: pix = todcor[xym[0]-1:xym[0]+2, xym[1]] xym_frac0 = (pix[2] - pix[0])/(2*pix[1] - pix[0] - pix[2])/2 pix = todcor[xym[0], xym[1]-1:xym[1]+2] xym_frac1 = (pix[2] - pix[0])/(2*pix[1] - pix[0] - pix[2])/2 rv_x = drv*((xym_frac1 + xym[1]) - ncor//2) rv_y = drv*((xym_frac0 + xym[0]) - ncor//2) model_spect = rv_shift_binary(rv_x/drv, rv_y/drv, alpha, np.fft.rfft(template_ints[0]), np.fft.rfft(template_ints[1])) if plotit: (wave_log, spect_int_norm, sig_int, template_int_norm) = \ interpolate_spectra_onto_log_grid(spect,wave,sig, template_fns,\ bad_intervals=bad_intervals, smooth_distance=smooth_distance, \ convolve_template=convolve_template, nwave_log=nwave_log, \ subtract_smoothed=False) model_spect_norm = rv_shift_binary(rv_x/drv, rv_y/drv, alpha, \ np.fft.rfft(template_int_norm[0]), np.fft.rfft(template_int_norm[1])) model_spect_prim = rv_shift_binary(rv_x/drv, rv_y/drv, 0, \ np.fft.rfft(template_int_norm[0]), np.fft.rfft(template_int_norm[1])) model_spect_sec = rv_shift_binary(rv_x/drv, rv_y/drv, 1e6, \ np.fft.rfft(template_int_norm[0]), np.fft.rfft(template_int_norm[1])) #--- Old divisors as a dodgy attempt to deal with non-normalised # data... --- #ss = np.ones(5e2)/5e2 #model_ss = np.convolve(model_spect_norm, ss, mode='same') #spect_ss = np.convolve(spect_int_norm, ss, mode='same') #plt.plot(wave_log, model_spect_norm/model_ss, label='Joint Model') #plt.plot(wave_log, model_spect_prim/model_ss/(1+alpha), label='Primary') #plt.plot(wave_log, model_spect_sec/model_ss*alpha/(1+alpha), label='Secondary') #plt.plot(wave_log, spect_int_norm/spect_ss, label='Data') plt.clf() plt.plot(wave_log, model_spect_norm, label='Joint Model') plt.plot(wave_log, model_spect_prim/(1+alpha), label='Primary') plt.plot(wave_log, model_spect_sec*alpha/(1+alpha), label='Secondary') plt.plot(wave_log, spect_int_norm, label='Data') plt.legend() plt.axis([3810, 5610, 0, 1.45]) plt.xlabel(r'Wavelength ($\AA$)') plt.ylabel('Flux (normalised)') plt.draw() #pdb.set_trace() #XXX #Compute theoretical RV uncertainties from the "Q" factors... errors = [] for i,template_int in enumerate(template_ints): if (i==0): ti = template_int/(1 + alpha) else: ti = template_int*alpha/(1 + alpha) model_spect_deriv = (ti[1:]-ti[:-1])/(wave_log[1:]-wave_log[:-1]) wave2_on_s = (0.5*(wave_log[1:]+wave_log[:-1]))**2/(0.5*(ti[1:]+ti[:-1]+2)) q_factor = np.sqrt(np.mean(wave2_on_s*model_spect_deriv**2)) photon_rv_error = 3e5/q_factor*np.median(sig_int)/np.sqrt(len(spect)) errors.append(photon_rv_error) print("Q factor: {:5.2f}".format(q_factor)) #plt.clf() #plt.plot(template_int) #plt.pause(.01) #import pdb; pdb.set_trace() #ISSUES: #1) Error (below) not computed. #errors = np.sqrt(np.diag(fit_p.fit_info['cov_x'])) if len(out_fn)>0: outfile = open(out_fn, 'a') outfile.write('{0:12.4f}, {1:8.2f}, {2:8.2f}, {3:8.2f}, {4:8.2f}, {5:8.3f}\n'. format(jd, rv_x + heliocentric_correction, errors[0], rv_y + heliocentric_correction, errors[1], np.max(todcor))) outfile.close() if return_fitted: return wave_log, spect_int, model_spect else: return rv_x, errors[0], rv_y, errors[1], np.max(todcor) def rv_process_dir(ddir,template_conv_dir='./ambre_conv/',standards_dir='',outfn='rvs.txt',texfn='rvs.tex',outdir='',mask_ha_emission=False): """Process all files in a directory for radial velocities. Parameters ---------- dir: string Directory in which to process the WiFeS reduced spectra template_conf_dir: string Directory containing template spectra convolved to WiFeS resolution outfn: string Output filename""" if len(standards_dir)>0: print("WARNING: Feature not implemented yet") raise UserWarning fns = glob.glob(ddir + '/*p08.fits' ) #Uncomment to test individual stars in a data-set #pdb.set_trace() #fns = fns[32:33] # If an out directory isn't given, use the data directory. if len(outdir)==0: outdir=ddir outfile = open(outdir + '/' + outfn,'w') outfile.write('#name,filename,ra,dec,bmsplt,mjd,rv,sig_rv,teff \n') texfile = open(outdir + '/' + texfn,'w') for iii,fn in enumerate(fns): ##pdb.set_trace() h = pyfits.getheader(fn) flux,wave = read_and_find_star_p08(fn,fig_fn=outdir + '/'+ h['OBJNAME'] + '.' + h['OBSID'] + '_star.png') if h['BEAMSPLT']=='RT560': bad_intervals = ([0,5500],[6860,7020],) else: bad_intervals = ([6862,7020],) ##Maybe here decide if the star is e.g. a young K/M dwarf with lots of H-alpha emission and ##bad_interval out that section of spectrum this also works to remove Ae/Be emission which causes issues #pdb.set_trace() if mask_ha_emission == True: simple_spec = np.sum(np.sum(flux,axis=0),axis=0) harng = np.where((wave > 6560.0) & (wave < 6565.0))[0] crng = np.where((wave > 6500.0) & (wave < 6520.0))[0] cmed = np.median(simple_spec[crng]) hamed = np.median(simple_spec[harng]) scmed = np.std(simple_spec[crng])*1.253/len(crng) #pdb.set_trace() if hamed > 5.0*scmed+cmed: bad_intervals = bad_intervals+([6550,6580],) print('Removing H-alpha line due to emission') ##pdb.set_trace() spectrum,sig = weighted_extract_spectrum(flux) specfn = outdir + '/' + fn[fn.rfind('/')+1:] + '.spec.csv' specfile = open(specfn,'w') for i in range(len(spectrum)): specfile.write('{0:6.2f},{1:6.1f},{2:6.1f}\n'.format(wave[i],spectrum[i],sig[i])) specfile.close() rv,rv_sig,name = calc_rv_template(spectrum,wave,sig,template_conv_dir, bad_intervals,\ fig_fn=outdir + '/' + h['OBJNAME'] + '.' + h['OBSID'] + '_xcor.png',starnumber=iii+1) outfile.write(h['OBJNAME'] + ','+fn +','+ h['RA'] + ','+ h['DEC'] + ',' + h['BEAMSPLT'] + \ ',{0:10.3f},{1:5.1f},{2:5.1f},'.format(h['MJD-OBS'],rv,rv_sig)+name + ' \n') texfile.write(h['OBJNAME'] + ' & '+ h['RA'] + ' & '+ h['DEC'] + ' & ' + h['BEAMSPLT'] + \ ' & {0:10.3f} & {1:5.1f} $\pm$ {2:5.1f} & '.format(h['MJD-OBS'],rv,rv_sig,name) + name + '\\\\ \n') outfile.close() texfile.close()
{ "repo_name": "PyWiFeS/tools", "path": "process_stellar.py", "copies": "1", "size": "40891", "license": "mit", "hash": 3939160163785085400, "line_mean": 41.5062370062, "line_max": 233, "alpha_frac": 0.6053165733, "autogenerated": false, "ratio": 3.008682216172467, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8957204450974772, "avg_score": 0.03135886769953898, "num_lines": 962 }
# After closing time, the store manager would like to know how much business was # transacted during the day. Modify the CashRegister class to enable this functionality. # Supply methods getSalesTotal and getSalesCount to get the total amount of all sales # and the number of sales. Supply a method resetSales that resets any counters and # totals so that the next day’s sales start from zero. class CashRegister(): def __init__(self): self._items = [] self._sales = [] def add_item(self, item): self._items.append(item) def clear(self): self._sales.append(self._items) print(self._sales) self._items[:] = [] def get_sales_count(self): return len(self._sales) def get_sales_total(self): total = 0 for sale in self._sales: for item in sale: total += item.get_price() return total def reset_sales(self): self._sales[:] = [] def get_count(self): return len(self._items) def get_total(self): total = 0 for item_object in self._items: total += item_object.get_price() return total def display_items(self): output = [] for item_object in self._items: output.append("{} - {}".format(item_object.get_name(), item_object.get_price())) return "\n".join(output)
{ "repo_name": "futurepr0n/Books-solutions", "path": "Python-For-Everyone-Horstmann/Chapter9-Objects-and-Classes/P9_21.py", "copies": "1", "size": "1395", "license": "mit", "hash": -7918992486969193000, "line_mean": 28.6382978723, "line_max": 92, "alpha_frac": 0.6008614501, "autogenerated": false, "ratio": 3.991404011461318, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5092265461561318, "avg_score": null, "num_lines": null }
## After considerable work, Alyssa P. Hacker delivers her finished system. ## Several years later, after she has forgotten all about it, she gets a ## frenzied call from an irate user, Lem E. Tweakit. It seems that Lem has ## noticed that the formula for parallel resistors can be written in two ## algebraically equivalent ways: ## ## R_1 * R_2 1 ## ----------- and ------------------- ## R_1 + R_2 1 / R_1 + 1 / R_2 ## ## He has written the following two programs, each of which computes the ## parallel-resistors formula differently: ## ## (define (par1 r1 r2) ## (div-interval (mul-interval r1 r2) ## (add-interval r1 r2))) ## (define (par2 r1 r2) ## (let ((one (make-interval 1 1))) ## (div-interval one ## (add-interval (div-interval one r1) ## (div-interval one r2))))) ## ## Lem complains that Alyssa's program gives different answers for the two ## ways of computing. This is a serious complaint. ## ## The solution of exercise 2.14 ## Demonstrate that Lem is right. Investigate the behavior of the system ## on a variety of arithmetic expressions. Make some intervals A and B, ## and use them in computing the expressions A / A and A / B. You will get ## the most insight by using intervals whose width is a small percentage of ## the center value. Examine the results of the computation in center- ## percent form (see exercise 2.12). ## ## -------- (above from SICP) ## import sys import math ## Check the python version ## Write different code for different python version if sys.version_info[0] < 3: # Use new type class __metaclass__ = type infty = float('inf') # Define functions to detect nan and infty value def isnan(a): """Check whether a is nan.""" return a != a def isinf(a): """Check whether a is infty.""" return (a == infty or a == -infty) else: infty = math.inf isnan = math.isnan isinf = math.isinf ## Define the interval class. class Interval: """Here we define a interval class with 2 attributes: center and percent, which is a little different from that in exercise 2.11. To construct the instance of this class, only 2 arguments (@center and @percent) are needed, and the contructor will automatically compute the other attributes. But you can also construct the instance from a number (an interval with the same bounds) or from a pair of its lower and upper bounds. - From center and percent: Interval(5, 20) produces interval [4, 6] - From bounds: Interval.from_bounds(-4, 7) produces interval [-4, 7] - From number: Interval.from_number(100) produces interval [100, 100] Interval.from_number(math.inf) produces interval [inf, inf] """ __slots__ = ('__center', '__percent') # The initialization with two parameters: center and percent. # Still allowed initialization with bounds or a number. def __init__(self, center, percent): """Initialize the interval class. You must supply the center and the percent of this interval. The percent parameter must be positive. Only int and float type is allowed here. """ if not (isinstance(center, (int, float)) and \ isinstance(percent, (int, float))): raise TypeError("cannot initialize interval with parameters " "in wrong type: %s, %s" % \ (type(center).__name__, \ type(percent).__name__)) if isnan(center) or isnan(percent): raise ValueError("nan value of parameters occurs: %r, %r" % \ (center, percent)) self.__center = center self.__percent = percent self.__update() @classmethod def from_bound(self, lb, ub): """Initialize the interval class. You must supply the lower and upper bounds of this interval. Your lower_bound is not allowed to be larger than upper_bound, and you cannot construct an interval whose center == 0, with positive width, such as [-5, 5], because there does not exist such an interval in (center, percent) form. You cannot construct an interval whose one bound is finite while the other is infinite because of the same reason. """ if not (isinstance(lb, (int, float)) and \ isinstance(ub, (int, float))): raise TypeError("cannot initialize interval with bounds " "in wrong type: %s, %s" % \ (type(lb).__name__, type(ub).__name__)) if isnan(lb) or isnan(ub): raise ValueError("nan value of bounds occurs: %r, %r" % \ (lb, ub)) if lb > ub: raise ValueError("lower bound is larger than upper bound: " "%r > %r" % (lb, ub)) if lb + ub == 0 and lb != 0: raise ValueError("finite non-zero bounds: %r, %r " "and zero center." % (lb, ub)) if (isinf(lb) and not isinf(ub)) or \ (isinf(ub) and not isinf(lb)): raise ValueError("one bound is finite while the other is " "infinite: %r, %r" % (lb, ub)) # In this case, the upper bound is +inf and the lower bound is # -inf, which means the interval is R := (-inf, +inf). Here we # simply set the center zero because operation `ub + lb` # returns nan. if ub == infty and lb == -infty: return Interval(0, infty) elif ub == lb == 0: return Interval(0, 0) center = (ub + lb) / 2.0 percent = abs(50.0 * (ub - lb) / center) if isnan(percent): percent = 0 return Interval(center, percent) @classmethod def from_number(self, number): """Initialize the interval class. You must supply the number. Here we create an interval instance whose lower bound equals its upper bound. """ if not isinstance(number, (int, float)): raise TypeError("cannot initialize interval with bounds " "in wrong type: %s" % type(number).__name__) return Interval(number, 0) @property def center(interval): return interval.__center @center.setter def center(interval, nc): if not isinstance(nc, (int, float)): raise TypeError("cannot initialize interval with parameters " "in wrong type: %s" % type(nc).__name__) interval.__center = nc interval.__update() @property def percent(interval): return interval.__percent @percent.setter def percent(interval, np): if not isinstance(np, (int, float)): raise TypeError("cannot initialize interval with parameters " "in wrong type: %s" % type(np).__name__) interval.__percent = np interval.__update() @property def width(interval): if isinf(interval.__center): return 0 if isinf(interval.__percent): return infty return abs(interval.__center * interval.__percent) / 100.0 @property def lb(interval): return interval.__center - interval.width @property def ub(interval): return interval.__center + interval.width def __update(self): """Update attributes in Interval class. Here all these attributes have float datatype """ if self.__percent < 0: raise ValueError("parameter percent must be positive.") if self.__center == 0: self.__percent = 0 elif isinf(self.__center): if isinf(self.__percent): raise ValueError("cannot construct interval with " "infinite center and infinite percent.") self.__percent = 0 else: if isinf(self.__percent): self.__center = 0 @property def bounds(interval): return interval.lb, interval.ub def __repr__(self): """Print method""" # Print all attributes of this interval ostr = "Interval \t[%s, %s]\n" % \ (self.lower_bound, self.upper_bound) + \ "center \t%s\npercent \t%s\nwidth \t%s" % \ (self.center, self.percent, self.width) return ostr def __repr__(self): """Print method""" # Print all attributes of this interval return 'Interval \t[%s, %s]\n' % \ (self.lb, self.ub) + \ "center \t%s\npercent \t%s\nwidth \t%s" % \ (self.center, self.percent, self.width) def __eq__(self, itv): """Equality determination""" # Only two intervals with completely the same attributes are # equal. The attributes of an interval are determined by the two # independent attributes named @center and @percent. if isinstance(itv, Interval): return (self.center == itv.center and \ self.percent == itv.percent) else: return False def __add__(self, addend): """Interval Addition""" if isinstance(addend, Interval): nc = self.center + addend.center np = (self.percent * abs(self.center) \ + addend.percent * abs(addend.center)) \ / (1.0 * abs(self.center + addend.center)) return Interval(nc, np) elif isinstance(addend, (int, float)): nc = self.center + addend np = abs(self.center / nc) * self.percent return Interval(nc, np) return NotImplemented def __radd__(self, other): """Right addition""" if isinstance(other, (int, float)): return self.__add__(other) return NotImplemented def __sub__(self, minuend): """Interval subtraction""" if isinstance(minuend, Interval): nc = self.center - minuend.center np = (self.percent * abs(self.center) \ + minuend.percent * abs(minuend.center)) \ / (1.0 * abs(self.center - minuend.center)) return Interval(nc, np) elif isinstance(minuend, (int, float)): nc = self.center - minuend np = abs(self.center / nc) * self.percent return Interval(nc, np) return NotImplemented def __rsub__(self, other): """Right subtraction""" if isinstance(other, (int, float)): return self.__mul__(-1).__add__(other) return NotImplemented def __mul__(self, multiplier): """Interval multiplication""" if isinstance(multiplier, Interval): if multiplier.percent >= 100 and \ multiplier.percent > self.percent: nc = (1 + self.percent / 100.0) * \ self.center * multiplier.center return Interval(nc, multiplier.percent) elif multiplier.percent < 100 and self.percent < 100: nc = (1 + self.percent * multiplier.percent / 10000.0) * \ self.center * multiplier.center np = (10000.0 * (self.percent + multiplier.percent)) / \ (10000.0 + (self.percent * multiplier.percent)) return Interval(nc, np) else: nc = (1 + multiplier.percent / 100.0) * \ self.center * multiplier.center return Interval(nc, self.percent) elif isinstance(multiplier, (int, float)): return Interval(self.center * multiplier, \ self.percent) return NotImplemented def __rmul__(self, other): """Right subtraction""" if isinstance(other, (int, float)): return self.__mul__(other) return NotImplemented def _rdiv(self, other): """An interval divides a real number""" # Notice that zero cannot be denominator and one interval spans # zero if and only if its percent >= 100 if isinstance(other, (int, float)): if self.percent >= 100: raise ZeroDivisionError("the dividend interval spans " "zero") nc = 10000.0 * other / \ ((10000.0 - self.percent ** 2) * self.center) return Interval(nc, self.percent) return NotImplemented def _div(self, itv): """An interval divides another interval""" return self.__mul__(1 / itv) # Here we check the current python version. If the current Python # environment is Python 3.x, we need to overload __rtruediv__ and # __truediv__ instead of __rdiv__ and __div__. However, in Python 2.x, # __rdiv__ and __div__ need to be overloaded to implement division # overloading. # # The old Python 2 `/` operator is replaced by the Python 3 behaviour # with the `from __future__` import, but here we do not import it. # In Python 3, all numeric division with operator `/` results in a # float result while it does not do that in Python 2. if sys.version_info[0] >= 3: __rtruediv__ = _rdiv __truediv__ = _div else: __rdiv__ = _rdiv __div__ = _div def par1(r1, r2): """The formula to compute parallel resistance""" return (r1 * r2) / (r1 + r2) def par2(r1, r2): """The formula to compute parallel resistance""" return (1 / ((1 / r1) + (1 / r2)))
{ "repo_name": "perryleo/sicp", "path": "chapter_02/python/sicpc2e14.py", "copies": "1", "size": "13925", "license": "mit", "hash": -7639819949231243000, "line_mean": 36.9427792916, "line_max": 75, "alpha_frac": 0.5537522442, "autogenerated": false, "ratio": 4.2727830622890455, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.010080160014163606, "num_lines": 367 }
## After debugging her program, Alyssa shows it to a potential user, who ## complains that her program solves the wrong problem. He wants a program ## that can deal with numbers represented as a center value and an ## additive tolerance; for example, he wants to work with intervals such ## as `3.5 +- 0.15` rather than [3.35, 3.65]. Alyssa returns to her desk ## and fixes this problem by supplying an alternate constructor and ## alternate selectors: ## ## (define (make-center-width c w) ## (make-interval (- c w) (+ c w))) ## (define (center i) ## (/ (+ (lower-bound i) (upper-bound i)) 2)) ## (define (width i) ## (/ (- (upper-bound i) (lower-bound i)) 2)) ## ## Unfortunately, most of Alyssa's users are engineers. Real engineering ## situations usually involve measurements with only a small uncertainty, ## measured as the ratio of the width of the interval to the midpoint of ## the interval. Engineers usually specify percentage tolerances on the ## parameters of devices, as in the resistor specifications given earlier. ## ## The solution of exercise 2.12 ## Define a constructor make-center-percent that takes a center and a ## percentage tolerance and produces the desired interval. You must also ## define a selector percent that produces the percentage tolerance for a ## given interval. The center selector is the same as the one shown above. ## ## -------- (above from SICP) ## import sys import math ## Check the python version ## Write different code for different python version if sys.version_info[0] < 3: # Use new type class __metaclass__ = type infty = float('inf') # Define functions to detect nan and infty value def isnan(a): """Check whether a is nan.""" return a != a def isinf(a): """Check whether a is infty.""" return (a == infty or a == -infty) else: infty = math.inf isnan = math.isnan isinf = math.isinf ## Define the interval class. class Interval: """Here we define a interval class with 2 attributes: center and percent, which is a little different from that in exercise 2.11. To construct the instance of this class, only 2 arguments (@center and @percent) are needed, and the contructor will automatically compute the other attributes. But you can also construct the instance from a number (an interval with the same bounds) or from a pair of its lower and upper bounds. - From center and percent: Interval(5, 20) produces interval [4, 6] - From bounds: Interval.from_bounds(-4, 7) produces interval [-4, 7] - From number: Interval.from_number(100) produces interval [100, 100] Interval.from_number(math.inf) produces interval [inf, inf] """ __slots__ = ('__center', '__percent') # The initialization with two parameters: center and percent. # Still allowed initialization with bounds or a number. def __init__(self, center, percent): """Initialize the interval class. You must supply the center and the percent of this interval. The percent parameter must be positive. Only int and float type is allowed here. """ if not (isinstance(center, (int, float)) and \ isinstance(percent, (int, float))): raise TypeError("cannot initialize interval with parameters " "in wrong type: %s, %s" % \ (type(center).__name__, \ type(percent).__name__)) if isnan(center) or isnan(percent): raise ValueError("nan value of parameters occurs: %r, %r" % \ (center, percent)) self.__center = center self.__percent = percent self.__update() @classmethod def from_bound(self, lb, ub): """Initialize the interval class. You must supply the lower and upper bounds of this interval. Your lower_bound is not allowed to be larger than upper_bound, and you cannot construct an interval whose center == 0, with positive width, such as [-5, 5], because there does not exist such an interval in (center, percent) form. You cannot construct an interval whose one bound is finite while the other is infinite because of the same reason. """ if not (isinstance(lb, (int, float)) and \ isinstance(ub, (int, float))): raise TypeError("cannot initialize interval with bounds " "in wrong type: %s, %s" % \ (type(lb).__name__, type(ub).__name__)) if isnan(lb) or isnan(ub): raise ValueError("nan value of bounds occurs: %r, %r" % \ (lb, ub)) if lb > ub: raise ValueError("lower bound is larger than upper bound: " "%r > %r" % (lb, ub)) if lb + ub == 0 and lb != 0: raise ValueError("finite non-zero bounds: %r, %r " "and zero center." % (lb, ub)) if (isinf(lb) and not isinf(ub)) or \ (isinf(ub) and not isinf(lb)): raise ValueError("one bound is finite while the other is " "infinite: %r, %r" % (lb, ub)) # In this case, the upper bound is +inf and the lower bound is # -inf, which means the interval is R := (-inf, +inf). Here we # simply set the center zero because operation `ub + lb` # returns nan. if ub == infty and lb == -infty: return Interval(0, infty) elif ub == lb == 0: return Interval(0, 0) center = (ub + lb) / 2.0 percent = abs(50.0 * (ub - lb) / center) if isnan(percent): percent = 0 return Interval(center, percent) @classmethod def from_number(self, number): """Initialize the interval class. You must supply the number. Here we create an interval instance whose lower bound equals its upper bound. """ if not isinstance(number, (int, float)): raise TypeError("cannot initialize interval with bounds " "in wrong type: %s" % type(number).__name__) return Interval(number, 0) @property def center(interval): return interval.__center @center.setter def center(interval, nc): if not isinstance(nc, (int, float)): raise TypeError("cannot initialize interval with parameters " "in wrong type: %s" % type(nc).__name__) interval.__center = nc interval.__update() @property def percent(interval): return interval.__percent @percent.setter def percent(interval, np): if not isinstance(np, (int, float)): raise TypeError("cannot initialize interval with parameters " "in wrong type: %s" % type(np).__name__) interval.__percent = np interval.__update() @property def width(interval): if isinf(interval.__center): return 0 if isinf(interval.__percent): return infty return abs(interval.__center * interval.__percent) / 100.0 @property def lb(interval): return interval.__center - interval.width @property def ub(interval): return interval.__center + interval.width def __update(self): """Update attributes in Interval class. Here all these attributes have float datatype """ if self.__percent < 0: raise ValueError("parameter percent must be positive.") if self.__center == 0: self.__percent = 0 elif isinf(self.__center): if isinf(self.__percent): raise ValueError("cannot construct interval with " "infinite center and infinite percent.") self.__percent = 0 else: if isinf(self.__percent): self.__center = 0 @property def bounds(interval): return interval.lb, interval.ub def __repr__(self): """Print method""" # Print all attributes of this interval ostr = "Interval \t[%s, %s]\n" % \ (self.lower_bound, self.upper_bound) + \ "center \t%s\npercent \t%s\nwidth \t%s" % \ (self.center, self.percent, self.width) return ostr def __repr__(self): """Print method""" # Print all attributes of this interval return 'Interval \t[%s, %s]\n' % \ (self.lb, self.ub) + \ "center \t%s\npercent \t%s\nwidth \t%s" % \ (self.center, self.percent, self.width) def __eq__(self, itv): """Equality determination""" # Only two intervals with completely the same attributes are # equal. The attributes of an interval are determined by the two # independent attributes named @center and @percent. if isinstance(itv, Interval): return (self.center == itv.center and \ self.percent == itv.percent) else: return False def __add__(self, addend): """Interval Addition""" if isinstance(addend, Interval): nc = self.center + addend.center np = (self.percent * abs(self.center) \ + addend.percent * abs(addend.center)) \ / (1.0 * abs(self.center + addend.center)) return Interval(nc, np) elif isinstance(addend, (int, float)): nc = self.center + addend np = abs(self.center / nc) * self.percent return Interval(nc, np) return NotImplemented def __radd__(self, other): """Right addition""" if isinstance(other, (int, float)): return self.__add__(other) return NotImplemented def __sub__(self, minuend): """Interval subtraction""" if isinstance(minuend, Interval): nc = self.center - minuend.center np = (self.percent * abs(self.center) \ + minuend.percent * abs(minuend.center)) \ / (1.0 * abs(self.center - minuend.center)) return Interval(nc, np) elif isinstance(minuend, (int, float)): nc = self.center - minuend np = abs(self.center / nc) * self.percent return Interval(nc, np) return NotImplemented def __rsub__(self, other): """Right subtraction""" if isinstance(other, (int, float)): return self.__mul__(-1).__add__(other) return NotImplemented def __mul__(self, multiplier): """Interval multiplication""" if isinstance(multiplier, Interval): if multiplier.percent >= 100 and \ multiplier.percent > self.percent: nc = (1 + self.percent / 100.0) * \ self.center * multiplier.center return Interval(nc, multiplier.percent) elif multiplier.percent < 100 and self.percent < 100: nc = (1 + self.percent * multiplier.percent / 10000.0) * \ self.center * multiplier.center np = (10000.0 * (self.percent + multiplier.percent)) / \ (10000.0 + (self.percent * multiplier.percent)) return Interval(nc, np) else: nc = (1 + multiplier.percent / 100.0) * \ self.center * multiplier.center return Interval(nc, self.percent) elif isinstance(multiplier, (int, float)): return Interval(self.center * multiplier, \ self.percent) return NotImplemented def __rmul__(self, other): """Right subtraction""" if isinstance(other, (int, float)): return self.__mul__(other) return NotImplemented def _rdiv(self, other): """An interval divides a real number""" # Notice that zero cannot be denominator and one interval spans # zero if and only if its percent >= 100 if isinstance(other, (int, float)): if self.percent >= 100: raise ZeroDivisionError("the dividend interval spans " "zero") nc = 10000.0 * other / \ ((10000.0 - self.percent ** 2) * self.center) return Interval(nc, self.percent) return NotImplemented def _div(self, itv): """An interval divides another interval""" return self.__mul__(1 / itv) # Here we check the current python version. If the current Python # environment is Python 3.x, we need to overload __rtruediv__ and # __truediv__ instead of __rdiv__ and __div__. However, in Python 2.x, # __rdiv__ and __div__ need to be overloaded to implement division # overloading. # # The old Python 2 `/` operator is replaced by the Python 3 behaviour # with the `from __future__` import, but here we do not import it. # In Python 3, all numeric division with operator `/` results in a # float result while it does not do that in Python 2. if sys.version_info[0] >= 3: __rtruediv__ = _rdiv __truediv__ = _div else: __rdiv__ = _rdiv __div__ = _div
{ "repo_name": "perryleo/sicp", "path": "chapter_02/python/sicpc2e12.py", "copies": "1", "size": "13571", "license": "mit", "hash": 5214915938270938000, "line_mean": 37.4447592068, "line_max": 74, "alpha_frac": 0.5638493847, "autogenerated": false, "ratio": 4.351074062199423, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.009898584284224786, "num_lines": 353 }
"""After downloaded, spider parse the response from which items are extracted and then items are processed by the ItemProcessor. """ from threaded_spider.basic.util import load_object from threaded_spider.http import Request from threaded_spider.core.item import BaseItem from threaded_spider import logger class Extracter(object): def __init__(self, crawler): itemproc_cls = load_object(crawler.settings.get('ITEM_PROCESSOR')) self.itemproc = itemproc_cls.from_crawler(crawler) self.crawler = crawler self.active_response = [] def attach_spider(self, spider): self.itemproc.attach_spider(spider) def detach_spider(self): self.itemproc.detach_spider() def has_pending_response(self): return len(self.active_response) def enter_extracter(self, response, request, spider): try: self.active_response.append(response) spider_output = self.call_spider(response, request, spider) for item in spider_output: if isinstance(item, Request): self.crawler.engine.schedule_later(item, spider) elif isinstance(item, BaseItem): self.itemproc.process_item(item) elif item is None: pass else: logger.error(format='Spider must return request, BaseItem or None,' ' got %(type)r in %(request)s', spider=spider, request=request) finally: self.active_response.remove(response) def call_spider(self, response, request, spider): parse_response = request.callback or spider.parse parsed_resp = parse_response(response) for item in parsed_resp: yield item
{ "repo_name": "aware-why/multithreaded_crawler", "path": "threaded_spider/core/extracter.py", "copies": "1", "size": "1923", "license": "bsd-2-clause", "hash": 7413406374297488000, "line_mean": 35.7450980392, "line_max": 87, "alpha_frac": 0.5865834633, "autogenerated": false, "ratio": 4.567695961995249, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.02557789791985122, "num_lines": 51 }
# After getting soundtest2.py and soundtest4.py working, I decided to # test my knowledge by writing a soundtest using the audio callback # method from scratch. It worked almost without a hitch! from sdl2 import * from ctypes import * from math import sin, pi SAMPLES_PER_SECOND = 44100 FREQUENCY = 440 SQUARE_WAVE_PERIOD = int(SAMPLES_PER_SECOND/FREQUENCY) HALF_SQUARE_WAVE_PERIOD = int(SQUARE_WAVE_PERIOD/2) SDL_Init(SDL_INIT_AUDIO) class Sound: def __init__(self): self.phase = 0 self.running_sample_index = 0 self.v = 0 def callback(self, notused, stream, length): for i in range(length): #self.running_sample_index += 1 #if self.running_sample_index % HALF_SQUARE_WAVE_PERIOD == 0: #self.phase += 1 #sample = 127 if self.phase % 2 else -127 sample = int(127 * sin(self.v*2*pi/SAMPLES_PER_SECOND)) self.v += FREQUENCY stream[i] = c_ubyte(sample) s = Sound() sdl_callback = SDL_AudioCallback(s.callback) spec = SDL_AudioSpec(freq=SAMPLES_PER_SECOND, aformat=AUDIO_S8, channels=1, samples=0, callback=sdl_callback) devid = SDL_OpenAudioDevice(None, 0, spec, spec, 0) SDL_PauseAudioDevice(devid, 0) input('Press Enter to exit')
{ "repo_name": "MageJohn/CHIP8", "path": "soundtests/soundtest5.py", "copies": "1", "size": "1351", "license": "mit", "hash": 3667050183018947600, "line_mean": 29.7045454545, "line_max": 73, "alpha_frac": 0.621761658, "autogenerated": false, "ratio": 3.3606965174129355, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9449490615271463, "avg_score": 0.006593512028294638, "num_lines": 44 }
"""after http://groups.google.com/group/pyglet-users/web/twistedpyglet.tgz, info about that and a proposal to add something like this to pyglet upstream in http://markmail.org/message/tm6r3cyhrp3dns4r that work added carbon support for mac, here am doing the same for win32. """ # System imports import sys, pyglet import ctypes from pyglet.app import windows, BaseEventLoop from pyglet.window.win32 import _user32, types, constants class Win32EventLoopOverride(pyglet.app.win32.Win32EventLoop): def pump(self): self._setup() self._timer_proc = types.TIMERPROC(self._timer_func) self._timer = timer = _user32.SetTimer(0, 0, 0, self._timer_proc) self._polling = False self._allow_polling = True msg = types.MSG() self.dispatch_event('on_enter') while not self.has_exit: if self._polling: while _user32.PeekMessageW(ctypes.byref(msg), 0, 0, 0, constants.PM_REMOVE): _user32.TranslateMessage(ctypes.byref(msg)) _user32.DispatchMessageW(ctypes.byref(msg)) self._timer_func(0, 0, timer, 0) yield 1 #to make a non-blocking version XXX else: _user32.GetMessageW(ctypes.byref(msg), 0, 0, 0) _user32.TranslateMessage(ctypes.byref(msg)) _user32.DispatchMessageW(ctypes.byref(msg)) # Manual idle event msg_types = \ _user32.GetQueueStatus(constants.QS_ALLINPUT) & 0xffff0000 if (msg.message != constants.WM_TIMER and not msg_types & ~(constants.QS_TIMER<<16)): self._timer_func(0, 0, timer, 0) yield 2 #to make a non-blocking version XXX def enable(): pyglet.app.event_loop = Win32EventLoopOverride()
{ "repo_name": "antont/tundra", "path": "src/Application/PythonScriptModule/proto/pollable_pyglet_app.py", "copies": "1", "size": "1920", "license": "apache-2.0", "hash": -5840771771676902000, "line_mean": 37.4, "line_max": 78, "alpha_frac": 0.5927083333, "autogenerated": false, "ratio": 3.855421686746988, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4948130020046988, "avg_score": null, "num_lines": null }
AFTER_INSTALL_PREFIX = """ def after_install(options, home_dir): import platform import subprocess import sys import os.path abs_home_dir = os.path.abspath(home_dir) if sys.platform == "win32": pip_path = os.path.join(abs_home_dir, "Scripts", "pip") pth_path = os.path.join( abs_home_dir, "Lib", "site-packages", "vootstrap.pth" ) else: pip_path = os.path.join(abs_home_dir, "bin", "pip") pth_path = os.path.join( abs_home_dir, "lib", py_version, "site-packages", "vootstrap.pth" ) """ AFTER_INSTALL_REQUIREMENTS = """ requirements = os.path.join(home_dir, "requirements.txt") if os.path.exists(requirements): subprocess.call( [pip_path, "install" , "-r", "requirements.txt", "--upgrade"]) """ def AFTER_INSTALL_PATH(path): return """ paths = [os.path.join(abs_home_dir, p) for p in %s] with open(pth_path, "w") as pth: pth.write("\\n".join(paths)) """ % str(path) ADJUST_OPTIONS_ARGS = """ try: args[0] = "." except IndexError: args.append(".") """
{ "repo_name": "tonyczeh/vootstrap", "path": "vootstrap/snippits.py", "copies": "1", "size": "1214", "license": "mit", "hash": 7194768501673692000, "line_mean": 22.8039215686, "line_max": 74, "alpha_frac": 0.5280065898, "autogenerated": false, "ratio": 3.3535911602209945, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9381597750020995, "avg_score": 0, "num_lines": 51 }
"""After obtaining all the desired embeddings, stacks them and applies supervised learning to nominate nodes whose nomination_attr_type value is unknown. Optionally uses leave-one-out cross-validation to nominate the known nodes as well. Usage: python3 nominate.py [path] The directory [path] must include a file params.py containing all necessary parameters.""" import sys import embed import imp import itertools from sklearn.preprocessing import Imputer, StandardScaler from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.decomposition import PCA from kde import TwoClassKDE from attr_vn import * def main(): path = sys.argv[1].strip('/') pm = imp.load_source('params', path + '/params.py') attr_filename = path + '/' + pm.attr_filename if (pm.rng_seed is not None): np.random.seed(pm.rng_seed) # partition attribute types into text/discrete (str dtype) or numeric text_attr_types, num_attr_types = [], [] for (attr_type, dtype) in pm.predictor_attr_types.items(): if (attr_type != pm.nomination_attr_type): if (dtype is str): text_attr_types.append(attr_type) else: num_attr_types.append(attr_type) attr_types = text_attr_types + num_attr_types # all predictor attribute types # get data frame of numeric features if pm.verbose: print("Gathering numeric features...") start_time = time.time() num_df = pd.read_csv(attr_filename, sep = ';') num_df = num_df[np.vectorize(lambda t : t in set(num_attr_types))(num_df['attributeType'])] num_df = num_df.pivot(index = 'node', columns = 'attributeType', values = 'attributeVal') num_df = num_df.convert_objects(convert_numeric = True) if pm.verbose: print(time_format(time.time() - start_time)) # stack feature vectors, projecting to sphere if desired if pm.verbose: print("\nStacking feature vectors...") start_time = time.time() mats = [] # get embedding features (context_features, text_attr_features_by_type) = embed.main() embedding_mats = [] if pm.use_context: if pm.sphere_context: normalize_mat_rows(context_features) embedding_mats.append(context_features) for attr_type in text_attr_types: if pm.sphere_content: normalize_mat_rows(text_attr_features_by_type[attr_type]) embedding_mats.append(text_attr_features_by_type[attr_type]) if (len(text_attr_types) > 0): mats += embedding_mats if (len(num_attr_types) > 0): # impute missing numeric data (using naive mean or median of the known values) imputer = Imputer(strategy = pm.imputation) mats.append(imputer.fit_transform(num_df)) mat = np.hstack(mats) if pm.verbose: print(time_format(time.time() - start_time)) # standard-scale the columns mat = StandardScaler().fit_transform(mat) # perform PCA on features, if desired if pm.use_pca: ncomps = mat.shape[1] if (pm.max_eig_pca is None) else min(pm.max_eig_pca, mat.shape[1]) pca = PCA(n_components = ncomps, whiten = pm.whiten) if pm.verbose: print("\nPerforming PCA on feature matrix...") mat = timeit(pca.fit_transform)(mat) sq_sing_vals = pca.explained_variance_ if (pm.which_elbow > 0): elbows = get_elbows(sq_sing_vals, n = pm.which_elbow, thresh = 0.0) k = elbows[min(len(elbows), pm.which_elbow) - 1] else: k = len(sq_sing_vals) mat = mat[:, :k] # identify seeds n = mat.shape[0] if pm.verbose: print("\nCreating AttributeAnalyzer...") a = timeit(AttributeAnalyzer, pm.verbose)(attr_filename, n, text_attr_types + [pm.nomination_attr_type]) ind = a.get_attribute_indicator(pm.nomination_attr_val, pm.nomination_attr_type) true_seeds, false_seeds = ind[ind == 1].index, ind[ind == 0].index num_true_seeds, num_false_seeds = len(true_seeds), len(false_seeds) training = list(ind[ind >= 0].index) assert ((num_true_seeds > 1) and (num_false_seeds > 1)) # can't handle this otherwise, yet if pm.verbose: print("\n%d total seeds (%d positive, %d negative)" % (num_true_seeds + num_false_seeds, num_true_seeds, num_false_seeds)) # construct classifier if (pm.classifier == 'logreg'): clf = LogisticRegression() elif (pm.classifier == 'naive_bayes'): clf = GaussianNB() elif (pm.classifier == 'randfor'): clf = RandomForestClassifier(n_estimators = pm.num_trees, n_jobs = pm.n_jobs) elif (pm.classifier == 'boost'): clf = AdaBoostClassifier(n_estimators = pm.num_trees) elif (pm.classifier == 'kde'): clf = TwoClassKDE() train_in = mat[training] train_out = ind[training] if pm.verbose: print("\nCross-validating to optimize KDE bandwidth...") timeit(clf.fit_with_optimal_bandwidth)(train_in, train_out, gridsize = pm.kde_cv_gridsize, dynamic_range = pm.kde_cv_dynamic_range, cv = pm.kde_cv_folds, verbose = int(pm.verbose), n_jobs = pm.n_jobs) else: raise ValueError("Invalid classifier '%s'." % pm.classifier) # cross-validate if (pm.cv_max > 0): true_seeds_for_cv = list(true_seeds[np.random.permutation(range(num_true_seeds))]) false_seeds_for_cv = list(false_seeds[np.random.permutation(range(num_false_seeds))]) # include equal proportion of positive & negative examples in cross-validation, if possible cv_seeds = list(itertools.islice(filter(None, sum(itertools.zip_longest(true_seeds_for_cv, false_seeds_for_cv), ())), pm.cv_max)) num_cv_seeds = len(cv_seeds) start_time = time.time() cv_probs = np.zeros(num_cv_seeds, dtype = float) num_true = ind[cv_seeds].sum() guess_rate = num_true / num_cv_seeds training_set = set(training) if pm.verbose: print("\nCross-validating %d seeds (%d positive, %d negative) with %s = %s..." % (num_cv_seeds, num_true, num_cv_seeds - num_true, pm.nomination_attr_type, pm.nomination_attr_val)) for (i, seed) in enumerate(cv_seeds): training_set.remove(seed) # remove sample cv_train = list(training_set) train_in = mat[cv_train] train_out = ind[cv_train] clf.fit(train_in, train_out) cv_in = mat[[seed]] cv_probs[i] = clf.predict_proba(cv_in)[0, 1] training_set.add(seed) # add back sample cv_df = pd.DataFrame(columns = ['node', 'prob'] + [pm.nomination_attr_type] + attr_types) cv_df['node'] = cv_seeds cv_df['prob'] = cv_probs for attr_type in [pm.nomination_attr_type] + text_attr_types: attrs_by_node = a.attrs_by_node_by_type[attr_type] cv_df[attr_type] = [str(attrs_by_node[node]) if (len(attrs_by_node[node]) > 0) else '{}' for node in cv_seeds] for attr_type in num_attr_types: vals = num_df[attr_type] cv_df[attr_type] = ['' if np.isnan(vals[node]) else str(vals[node]) for node in cv_seeds] cv_df = cv_df.sort_values(by = 'prob', ascending = False) cumulative_prec = np.cumsum(np.asarray(ind[cv_df['node']])) / np.arange(1.0, num_cv_seeds + 1.0) AP = np.mean(cumulative_prec) # average precision if pm.verbose: print(time_format(time.time() - start_time)) print("\nguess rate = %5f" % guess_rate) print("average precision = %5f" % AP) print("cumulative precisions:") print(cumulative_prec) if pm.save_info: cv_df.to_csv(path + '/%s_%s_cv_nomination.txt' % (pm.nomination_attr_type, pm.nomination_attr_val), index = False, sep = '\t') plt.figure() plt.plot(cumulative_prec, color = 'blue', linewidth = 2) plt.axhline(y = guess_rate, color = 'black', linewidth = 2, linestyle = 'dashed') plt.axvline(x = num_true, color = 'black', linewidth = 2, linestyle = 'dashed') plt.xlabel('rank') plt.ylabel('prec') plt.ylim((0, min(1.0, 1.1 * cumulative_prec.max()))) plt.title('Cumulative precision of cross-validated seeds\nAP = %5f' % AP, fontweight = 'bold') plt.savefig(path + '/%s_%s_cv_prec.png' % (pm.nomination_attr_type, pm.nomination_attr_val)) # nominate the unknown nodes start_time = time.time() if pm.verbose: print("\nNominating unknown nodes...") train_in = mat[training] train_out = ind[training] clf.fit(train_in, train_out) test = list(ind[~(ind >= 0)].index) # complement of seed set test_in = mat[test] test_probs = clf.predict_proba(test_in)[:, 1] if pm.verbose: print(time_format(time.time() - start_time)) nom_df = pd.DataFrame(columns = ['node', 'prob'] + attr_types) nom_df['node'] = test nom_df['prob'] = test_probs for attr_type in text_attr_types: attrs_by_node = a.attrs_by_node_by_type[attr_type] nom_df[attr_type] = [str(attrs_by_node[node]) if (len(attrs_by_node[node]) > 0) else '{}' for node in test] for attr_type in num_attr_types: vals = num_df[attr_type] nom_df[attr_type] = ['' if np.isnan(vals[node]) else str(vals[node]) for node in test] nom_df = nom_df.sort_values(by = 'prob', ascending = False) nom_df[:pm.nominate_max].to_csv(path + '/%s_%s_nomination.out' % (pm.nomination_attr_type, pm.nomination_attr_val), index = False, sep = '\t') if pm.verbose: print("\nSaved results to %s/%s_%s_nomination.out" % (path, pm.nomination_attr_type, pm.nomination_attr_val)) if __name__ == "__main__": main()
{ "repo_name": "jeremander/AttrVN", "path": "nominate.py", "copies": "1", "size": "9874", "license": "apache-2.0", "hash": 154005688270632450, "line_mean": 46.932038835, "line_max": 237, "alpha_frac": 0.6217338465, "autogenerated": false, "ratio": 3.2803986710963455, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44021325175963455, "avg_score": null, "num_lines": null }
# After query_data.py has been run, run this script on the output of query_data.py. # This changes the userids with integers, so that the file can be processed by MATLAB. # Easier to just write another script and pipe the output. # Input: first arg is the output of query_data.py, second is the mappings file. import sys interface_mappings = { '1': '2', '2': '0', '3': '1', '4': '4' } def get_mappings(mappings_file): mappings = {} for line in mappings_file: line = line.strip().split(',') mappings[line[0]] = line[1] return mappings output_file = open(sys.argv[1], 'r') mappings_file = open(sys.argv[2], 'r') user_mappings = get_mappings(mappings_file) print 'userid condition interface order topic actions pages doc_count doc_depth doc_rel_count doc_rel_depth hover_count hover_trec_rel_count hover_trec_nonrel_count hover_depth doc_trec_rel_count doc_trec_nonrel_count doc_clicked_trec_rel_count doc_clicked_trec_nonrel_count query_time system_query_delay session_time document_time serp_lag serp_time p1 p2 p3 p4 p5 p10 p15 p20 p25 p30 p40 p50 rprec total_relevant_docs doc_trec_unjudged_count interface per_page_time' for line in output_file: line = line.strip().split(' ') amtid = line[0] # Changing the AMTID to the mapped user ID integer. line[0] = user_mappings[amtid] line.append(interface_mappings[line[2]]) # Adding in the per_page_time. if float(line[6]) == 0: line.append('0') else: per_page_time = float(line[24]) / float(line[6]) line.append('{0:3.2f}'.format(per_page_time)) print ' '.join(line) output_file.close() mappings_file.close()
{ "repo_name": "leifos/treconomics", "path": "snippet_log_parser/query_data_mappings.py", "copies": "1", "size": "1694", "license": "mit", "hash": -8253837747273069000, "line_mean": 32.2156862745, "line_max": 468, "alpha_frac": 0.6729634002, "autogenerated": false, "ratio": 3.1025641025641026, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42755275027641026, "avg_score": null, "num_lines": null }
# after raw klt # filtering import os import math import pdb,glob import numpy as np from scipy.io import loadmat,savemat from scipy.sparse import csr_matrix import matplotlib.pyplot as plt from DataPathclass import * DataPathobj = DataPath(VideoIndex) from parameterClass import * Parameterobj = parameter(dataSource,VideoIndex) def trj_filter(x, y, t, xspeed, yspeed, blob_index, mask, Numsample , fps, minspdth = 15): # DoT fps 23 Johnson 30 transth = 100*fps #transition time (red light time) 100 seconds mask_re = [] x_re = [] y_re = [] t_re = [] xspd = [] yspd = [] speed = np.abs(xspeed)+np.abs(yspeed) print "minimum speed threshold set to be: ",minspdth # lenfile = open('length.txt', 'wb') # spdfile = open('./tempFigs/maxspeed.txt', 'wb') # stoptimefile = open('stoptime.txt', 'wb') for i in range(Numsample): if sum(x[i,:]!=0)>4: # new jay st # chk if trj is long enough # if sum(x[i,:]!=0)>50: # canal # spdfile.write(str(i)+' '+str(max(speed[i,:][x[i,1:]!=0][1:-1]))+'\n') # lenfile.write(str(i)+' '+str(sum(x[i,:]!=0))+'\n') # pdb.set_trace() try: # spdfile.write(str(i)+' '+str(max(speed[i,:][x[i,1:]!=0][1:-1]))+'\n') # print "speed:", max(speed[i,:][x[i,1:]!=0][1:-1]) if max(speed[i,:][x[i,1:]!=0][1:-1])>minspdth: # check if it is a moving point if sum(speed[i,:][x[i,1:]!=0][1:-1] < 3) < transth: # check if it is a stationary point mask_re.append(mask[i]) # ID x_re.append(x[i,:]) y_re.append(y[i,:]) t_re.append(t[i,:])  xspd.append(xspeed[i,:]) yspd.append(yspeed[i,:]) except: pass # spdfile.close() # stoptimefile.close() x_re = np.array(x_re) y_re = np.array(y_re) t_re = np.array(t_re) xspd = np.array(xspd) yspd = np.array(yspd) return mask_re, x_re, y_re, t_re, xspd, yspd def FindAllNanRow(aa): index = range(aa.shape[0]) allNanRowInd = np.array(index)[np.isnan(aa).all(axis = 1)] return allNanRowInd def prepare_input_data(): ## fps for DoT Canal is 23 ## Jay & Johnson is 30 # subSampRate = 6 # since 30 fps may be too large, subsample the images back to 5 FPS matfilepath = DataPathobj.kltpath savePath = DataPathobj.filteredKltPath useBlobCenter = False fps = Parameterobj.fps matfiles = sorted(glob.glob(ParameterObj.kltpath + 'klt_*.mat')) start_position = 0 #already processed 10 files matfiles = matfiles[start_position:] return matfiles,savePath,useBlobCenter,fps if __name__ == '__main__': # def filtering_main_function(fps,dataSource = 'DoT'): matfiles,savePath,useBlobCenter,fps = prepare_input_data() for matidx,matfile in enumerate(matfiles): print "Processing truncation...", str(matidx+1) ptstrj = loadmat(matfile) # mask = ptstrj['mask'][0] mask = ptstrj['trjID'][0] x = csr_matrix(ptstrj['xtracks'], shape=ptstrj['xtracks'].shape).toarray() y = csr_matrix(ptstrj['ytracks'], shape=ptstrj['ytracks'].shape).toarray() t = csr_matrix(ptstrj['Ttracks'], shape=ptstrj['Ttracks'].shape).toarray() if len(t)>0: t[t==np.max(t)]=np.nan Numsample = ptstrj['xtracks'].shape[0] trunclen = ptstrj['xtracks'].shape[1] color = np.array([np.random.randint(0,255) for _ in range(3*int(Numsample))]).reshape(Numsample,3) startPt = np.zeros((Numsample,1)) endPt = np.zeros((Numsample,1)) for tt in range(Numsample): if len(t)>0: startPt[tt] = np.mod( np.nanmin(t[tt,:]), trunclen) #ignore all nans endPt[tt] = np.mod( np.nanmax(t[tt,:]), trunclen) else: startPt[tt] = np.min(np.where(x[tt,:]!=0)) endPt[tt] = np.max(np.where(x[tt,:]!=0)) # xspeed = np.diff(x)*((x!=0)[:,1:]) # wrong! # yspeed = np.diff(y)*((y!=0)[:,1:]) xspeed = np.diff(x) yspeed = np.diff(y) for ii in range(Numsample): if math.isnan(startPt[ii]) or math.isnan(endPt[ii]): xspeed[ii, :] = 0 # discard yspeed[ii, :] = 0 else: xspeed[ii, int(max(startPt[ii]-1,0))] = 0 xspeed[ii, int(min(endPt[ii],trunclen-2))] = 0 yspeed[ii, int(max(startPt[ii]-1,0))] = 0 yspeed[ii, int(min(endPt[ii],trunclen-2))] = 0 print "Num of original samples is " , Numsample minspdth = 10 mask_re, x_re, y_re, t_re, xspd,yspd = trj_filter(x, y, t, xspeed, yspeed, blob_index, mask, Numsample , fps = fps, minspdth = minspdth) # delete all nan rows if x_re!=[]: allnanInd = FindAllNanRow(t_re) if allnanInd != []: print "delete all nan rows!!" print allnanInd del mask_re[allnanInd] del x_re[allnanInd] del y_re[allnanInd] del t_re[allnanInd] del blob_index_re[allnanInd] del xspd[allnanInd] del yspd[allnanInd] else: pass NumGoodsample = len(x_re) print "Num of Good samples is" , NumGoodsample # result = {} # result['trjID'] = mask_re # result['xtracks'] = x_re # result['ytracks'] = y_re # result['Ttracks'] = t_re # result['xspd'] = xspd # result['yspd'] = yspd ptstrj['trjID'] = mask_re ptstrj['xtracks'] = x_re ptstrj['ytracks'] = y_re ptstrj['Ttracks'] = t_re ptstrj['xspd'] = xspd ptstrj['yspd'] = yspd if smooth: savename = os.path.join(savePath,'smooth_len4minSpd'+str(minspdth)+'_'+str(matidx+1).zfill(3)+'.mat') else: savename = os.path.join(savePath,'len4minSpd'+str(minspdth)+'_'+str(matidx+1).zfill(3)) # savemat(savename,result) savemat(savename,ptstrj)
{ "repo_name": "ChengeLi/VehicleTracking", "path": "trj_filter.py", "copies": "1", "size": "6398", "license": "mit", "hash": -5748176884417944000, "line_mean": 36.4093567251, "line_max": 144, "alpha_frac": 0.52290136, "autogenerated": false, "ratio": 3.0447405997144217, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40676419597144214, "avg_score": null, "num_lines": null }
'''After setting up the system. i.e. stating the listener for master and all slaves User runs this program to compute the result. The input is passed to master which then handles everything aterwards.''' import socket from src.graph.graph import Graph from config.servers import servers from config.networkParams import MESSAGE_DELIMITER import src.util.network as network def readInput(): '''First line contains two arguments n = number of vertices m = number of edges in the graph next m line conatins (a,b) reresenting an edge.''' n, m = map(int, raw_input().split(" ")) edges = [] for i in range(0, m): a, b = map(int, raw_input().split(" ")) edges.append((a, b)) return n, m, edges def findMasterIpPort(): for s in servers : if s.role == 'master': return s.IP, s.port #master not found assert False if __name__ == '__main__': n, m, edges = readInput() graph = Graph(n, m, edges) MasterIP, MasterPort = findMasterIpPort() network.sendToIP(MasterIP, MasterPort, "INPUT____________" + MESSAGE_DELIMITER + graph.toString()) # TODO Wait for computation to end # merge all output file if required
{ "repo_name": "abhilak/DGA", "path": "user/run.py", "copies": "2", "size": "1205", "license": "mit", "hash": 1965003393662603800, "line_mean": 30.7105263158, "line_max": 102, "alpha_frac": 0.6564315353, "autogenerated": false, "ratio": 3.6404833836858006, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.006799763145417867, "num_lines": 38 }
#after taking mean, get out multiindex #Trying to understand how to access the content of a multiindex dataframe #Summary, after its grouped you can only access by first dimension, or by entire group, and only with loc? Thats if you Multiindex it but #at end of file I show how to avoid those problems by keeping things flat instead of hierarchical index. import pandas as pd from numpy.random import randn df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar','foo','bar'], #from http://pandas.pydata.org/pandas-docs/stable/groupby.html 'B' : [False,False,True,True,True,True], 'C' : [6,7,8,9,10,11], 'D' : [10,11,12,13,14,15]}) df['bar'] grouped = df.groupby(['A', 'B']) grouped[('foo','two')] grouped.loc['foo'] dfM = grouped.mean() dfM.index.names # ['A','B'] dfM.index #multiIndex (u'bar', u'one'), (u'bar', u'two'), (u'foo', u'one'), (u'foo', u'two') for x in dfM: print x #C, D dfM[('foo','two')] #error dfM['A'] #error dfM.loc['foo'] #works!! dfM.loc['one'] #doesnt work. apparently cant do it with second dimension of index dfM.loc['foo','one'] #works!! #Use Chris Said, Tal Yarkoni's trick of avoiding Multiindex #this works gNoIdx = df.groupby(['A', 'B'], as_index=False) gNoIdx.indices dgM = gNoIdx.mean() dgM.index #flat row names #this also works g = df.groupby(['A', 'B']) dgM = g.mean() dgM = dgM.reset_index() #back into columns dgM.loc[ dgM['A']=='bar', 'C' ] dgM.loc[ dgM['A']=='bar' ]
{ "repo_name": "alexholcombe/spatiotopic-motion", "path": "testAggregate.py", "copies": "1", "size": "1513", "license": "mit", "hash": -2478961247799362000, "line_mean": 36.825, "line_max": 137, "alpha_frac": 0.6226040978, "autogenerated": false, "ratio": 2.9096153846153845, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8828212291264996, "avg_score": 0.04080143823007752, "num_lines": 40 }
# After this module is loaded, perl object can be pickled # The perl objects can even contain python objects that contain # perl objects that contain python objects that... # # You are not supposed to use any functions from this module. # Just use Pickle as usual. # # Copyright 2000-2001 ActiveState import perl perl.require("Storable") perl.callm("VERSION", "Storable", 0.7); storable_thaw = perl.get_ref("Storable::thaw") storable_nfreeze = perl.get_ref("Storable::nfreeze") def perl_restore(frozen): return storable_thaw(frozen) def perl_reduce(o): return (perl_restore, (storable_nfreeze(o),) ) import copy_reg copy_reg.pickle(type(perl.get_ref("$")), perl_reduce, perl_restore) del(copy_reg) from cPickle import dumps, loads # Make the dumps and loads functions available for perl f = perl.get_ref("$Python::Object::pickle_dumps", 1) f.__value__ = dumps; f = perl.get_ref("$Python::Object::pickle_loads", 1) f.__value__ = loads; del(f) perl.eval(""" package Python::Object; sub STORABLE_freeze { my($self, $cloning) = @_; return Python::funcall($pickle_dumps, $self, 1); } sub STORABLE_thaw { my($self, $cloning, $serialized) = @_; my $other = Python::funcall($pickle_loads, $serialized); Python::PyO_transplant($self, $other); return; } """)
{ "repo_name": "UfSoft/python-perl", "path": "extra-packages/pyperl-1.0.1d/perlpickle.py", "copies": "2", "size": "1310", "license": "bsd-3-clause", "hash": -8122245395960017000, "line_mean": 23.2592592593, "line_max": 67, "alpha_frac": 0.6839694656, "autogenerated": false, "ratio": 3.0536130536130535, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47375825192130533, "avg_score": null, "num_lines": null }
"""A FTP_TLS client subclass with additional functionality to handle misconfigured FTP servers. """ from ftplib import FTP_TLS as stdFTP_TLS class FTP_TLS(stdFTP_TLS): """ A FTP_TLS subclass which adds support to force the use of the host address for passive (PASV) connections. This solves the problem of connecting to an misconfigured FTP server behind a firewall that reports its private IP instead of its public IP when issuing a PASV response. Usage example: >>> from ftp_tls import FTP_TLS >>> ftps = FTP_TLS('ftp.python.org') >>> ftps.login() # login anonymously previously securing control channel '230 Guest login ok, access restrictions apply.' >>> ftps.prot_p() # switch to secure data connection '200 Protection level set to P' >>> ftps.use_host_address() # force the use of the host address >>> ftps.dir() # list directory content securely total 2 drwxr-xr-x 8 root wheel 1024 Jan 3 1994 . drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .. '226 Transfer complete.' >>> ftps.quit() '221 Goodbye.' >>> """ force_host_address = False def use_host_address(self, val=True): self.force_host_address = bool(val) def makepasv(self): host, port = stdFTP_TLS.makepasv(self) if self.force_host_address: host = self.sock.getpeername()[0] return host, port
{ "repo_name": "w0uld/ftp_tls", "path": "ftp_tls.py", "copies": "1", "size": "1438", "license": "bsd-3-clause", "hash": 1629430730424927200, "line_mean": 32.4651162791, "line_max": 77, "alpha_frac": 0.6481223922, "autogenerated": false, "ratio": 3.687179487179487, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4835301879379487, "avg_score": null, "num_lines": null }
"""A full binary tree example""" from dbcbet.dbcbet import pre, post, inv, bet, finitize, finitize_method from dbcbet.helpers import state, argument_types def full_tree_invariant(self): return self._leaf() or self._full() def is_full(self): return self._full() def is_leaf(self): return self._leaf() @inv(full_tree_invariant) class FullBinaryTree(object): @finitize_method([1,2,3,4]) def __init__(self, value): self.value = value self.left_subtree = None self.right_subtree = None def leaf(self): return self._leaf() def _leaf(self): return self.left_subtree is None and self.right_subtree is None def full(self): return self._full() def _full(self): return self.left_subtree is not None and self.right_subtree is not None def nodes(self): return 1 if self.leaf() else self.left_subtree.nodes() + self.right_subtree.nodes() @pre(argument_types("examples.FullBinaryTree")) def add_left_subtree(self, left_subtree): self.left_subtree = left_subtree @pre(argument_types("examples.FullBinaryTree")) def add_right_subtree(self, right_subtree): self.right_subtree = right_subtree @pre(argument_types("examples.FullBinaryTree", "examples.FullBinaryTree")) @pre(state(is_leaf)) @post(state(is_full)) def add_subtrees(self, left, right): self.left_subtree = left self.right_subtree = right @pre(state(is_full)) @pre(argument_types("examples.FullBinaryTree")) def replace_left_subtree(self, left_subtree): self.left_subtree = left_subtree @pre(state(is_full)) @pre(argument_types("examples.FullBinaryTree")) def replace_right_subtree(self, right_subtree): self.right_subtree = right_subtree def __str__(self): return self._s("") def __hash__(self): return hash((self.value, self.left_subtree, self.right_subtree)) def __eq__(self, other): partial = True if self.left_subtree is not None and other.left_subtree is not None: partial = partial and (self.left_subtree == other.left_subtree) else: partial = partial and self.left_subtree is None and other.left_subtree is None if self.right_subtree is not None and other.right_subtree is not None: partial = partial and (self.right_subtree == other.right_subtree) else: partial = partial and self.right_subtree is None and other.right_subtree is None partial = partial and (self.value == other.value) return partial def _s(self, pad): ret = "" ret += "\n"+pad ret += " value: " + self.value ret += " # nodes: " + self.nodes() if self.left_subtree: ret += '\n' + pad ret += " left subtree: " + self.left_subtree._s(pad + " ") assert self.right_subtree ret += '\n' + pad ret += " right subtree: " + self.right_subtree._s(pad + " ") ret += "\n" return ret if __name__ == "__main__": bet(FullBinaryTree).run()
{ "repo_name": "ccoakley/dbcbet", "path": "examples/full_binary_tree.py", "copies": "1", "size": "3148", "license": "mit", "hash": -7506400033710649000, "line_mean": 31.1224489796, "line_max": 92, "alpha_frac": 0.6076874206, "autogenerated": false, "ratio": 3.66046511627907, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9733204836265821, "avg_score": 0.006989540122649872, "num_lines": 98 }
"""A full cache system written on top of Django's rudimentary one. Frequently used functions are: cache_set(*keys, **kwargs) cache_get(*keys, **kwargs) cache_delete(*keys, **kwargs) keys.. parameters of general type which are convertable to string or hashable unambiguously. The keys can be of any general type which is convertable to string unambiguously or hashable. Every unknown kwarg is interpreted like two aditional keys: (key, val). Example: cache_set('product', 123, value=product) # is the same as cache_set('product::123', value=product) More info below about parameters. """ # For keyedcache developers: # No additional keyword parameters should be added to the definition of # cache_set, cache_get, cache_delete or cache_key in the future. # Otherwise you must know what are you doing! Any appplication that would use # a new parameter will must check on startup that keyedcache is not older than # a required version !!(Otherwise kwargs unknown by an old version keyedcache # will be used as keys and cache_set/cache_get will use different keys that # would cause serious problems.) from django.conf import settings from django.core.cache import get_cache, InvalidCacheBackendError, DEFAULT_CACHE_ALIAS from django.core.exceptions import ImproperlyConfigured from django.utils.encoding import smart_str from django.utils.log import NullHandler from hashlib import md5 from keyedcache.utils import is_string_like, is_list_or_tuple from warnings import warn import logging import types try: import cPickle as pickle except ImportError: import pickle log = logging.getLogger(__name__) log.setLevel(logging.INFO) log.addHandler(NullHandler()) # The debugging variable CACHED_KEYS is exact only with the the Django # debugging server (or any single worker process server) and without restarting # the server between restarts of the main cache (memcached). # Keys in CACHED_KEYS variable never expire and can eat much memory on long # running servers. Currently it is not confirmed in Satchmo. # If more worker processes are used, the reported values of the following three # variables can skip randomly upwards downwards. CACHED_KEYS = {} CACHE_CALLS = 0 CACHE_HITS = 0 KEY_DELIM = "::" REQUEST_CACHE = {'enabled' : False} cache, cache_alias, CACHE_TIMEOUT, _CACHE_ENABLED = 4 * (None,) def keyedcache_configure(): "Initial configuration (or reconfiguration during tests)." global cache, cache_alias, CACHE_TIMEOUT, _CACHE_ENABLED cache_alias = getattr(settings, 'KEYEDCACHE_ALIAS', DEFAULT_CACHE_ALIAS) try: cache = get_cache(cache_alias) except InvalidCacheBackendError: log.warn("Warning: Could not find backend '%s': uses %s" % (cache_alias, DEFAULT_CACHE_ALIAS)) cache_alias = DEFAULT_CACHE_ALIAS # it is 'default' from django.core.cache import cache CACHE_TIMEOUT = cache.default_timeout if CACHE_TIMEOUT == 0: log.warn("disabling the cache system because TIMEOUT=0") _CACHE_ENABLED = CACHE_TIMEOUT > 0 and not cache.__module__.endswith('dummy') if not cache.key_prefix and (hasattr(settings, 'CACHE_PREFIX') or settings.SITE_ID != 1): if hasattr(settings, 'CACHE_PREFIX'): warn("The setting `CACHE_PREFIX` is obsoleted and is ignored by keyedcache.\n" """Use "CACHES = {'default': {... 'KEY_PREFIX': '...'}}" instead.""") if settings.SITE_ID != 1: hint = ("Use \"CACHES = {'default': {... 'KEY_PREFIX': '...'}}\" in order to\n" "differentiate caches or to explicitely confirm they should be shared.\n" " An easy solution is \"'CACHE_PREFIX': str(settings.SITE_ID)\".") warn("An explicit KEY_PREFIX should be defined if you use multiple sites.\n%s" % hint) if not cache.__module__.split('.')[-1] in ('locmem', 'dummy'): raise ImproperlyConfigured( "Setting KEY_PREFIX is obligatory for production caches. See the previous warning.") keyedcache_configure() class CacheWrapper(object): def __init__(self, val, inprocess=False): self.val = val self.inprocess = inprocess def __str__(self): return str(self.val) def __repr__(self): return repr(self.val) def wrap(cls, obj): if isinstance(obj, cls): return obj else: return cls(obj) wrap = classmethod(wrap) class MethodNotFinishedError(Exception): def __init__(self, f): self.func = f class NotCachedError(Exception): def __init__(self, k): self.key = k class CacheNotRespondingError(Exception): pass def cache_delete(*keys, **kwargs): """ Deletes the object identified by all ``keys`` from the cache. keys: Parameters of general type which are convertable to string or hashable unambiguously. kwargs: children: If it is True more objects starting with these keys are deleted. other kwargs: Unknown key=val is interpreted like two aditional keys: (key, val) If no keys are present, all cached objects are to be deleted. Deleting multiple multiple or all objects is usually not complete if the project is running with multiple worker processes. (It is reliable e.g. with a development server.) """ removed = [] if cache_enabled(): global CACHED_KEYS log.debug('cache_delete') children = kwargs.pop('children', False) if (keys or kwargs): key = cache_key(*keys, **kwargs) if key in CACHED_KEYS: del CACHED_KEYS[key] removed.append(key) cache.delete(key) if children: key = key + KEY_DELIM children = [x for x in CACHED_KEYS.keys() if x.startswith(key)] for k in children: del CACHED_KEYS[k] cache.delete(k) removed.append(k) else: key = "All Keys" deleteneeded = _cache_flush_all() removed = CACHED_KEYS.keys() if deleteneeded: for k in CACHED_KEYS: cache.delete(k) CACHED_KEYS = {} if removed: log.debug("Cache delete: %s", removed) else: log.debug("No cached objects to delete for %s", key) return removed def cache_delete_function(func): return cache_delete(['func', func.__name__, func.__module__], children=True) def cache_enabled(): global _CACHE_ENABLED return _CACHE_ENABLED def cache_enable(state=True): global _CACHE_ENABLED _CACHE_ENABLED=state def _cache_flush_all(): if is_memcached_backend(): cache._cache.flush_all() return False return True def cache_function(length=CACHE_TIMEOUT): """ A variant of the snippet posted by Jeff Wheeler at http://www.djangosnippets.org/snippets/109/ Caches a function, using the function and its arguments as the key, and the return value as the value saved. It passes all arguments on to the function, as it should. The decorator itself takes a length argument, which is the number of seconds the cache will keep the result around. It will put a temp value in the cache while the function is processing. This should not matter in most cases, but if the app is using threads, you won't be able to get the previous value, and will need to wait until the function finishes. If this is not desired behavior, you can remove the first two lines after the ``else``. """ def decorator(func): def inner_func(*args, **kwargs): if not cache_enabled(): value = func(*args, **kwargs) else: try: value = cache_get('func', func.__name__, func.__module__, args, kwargs) except NotCachedError as e: # This will set a temporary value while ``func`` is being # processed. When using threads, this is vital, as otherwise # the function can be called several times before it finishes # and is put into the cache. funcwrapper = CacheWrapper(".".join([func.__module__, func.__name__]), inprocess=True) cache_set(e.key, value=funcwrapper, length=length, skiplog=True) value = func(*args, **kwargs) cache_set(e.key, value=value, length=length) except MethodNotFinishedError as e: value = func(*args, **kwargs) return value return inner_func return decorator def cache_get(*keys, **kwargs): """ Gets the object identified by all ``keys`` from the cache. kwargs: default: Default value used if the object is not in the cache. If the object is not found and ``default`` is not set or is None, the exception ``NotCachedError`` is raised with the attribute ``.key = keys``. other kwargs: Unknown key=val is interpreted like two aditional keys: (key, val) """ if 'default' in kwargs: default_value = kwargs.pop('default') use_default = True else: use_default = False key = cache_key(keys, **kwargs) if not cache_enabled(): raise NotCachedError(key) else: global CACHE_CALLS, CACHE_HITS, REQUEST_CACHE CACHE_CALLS += 1 if CACHE_CALLS == 1: cache_require() obj = None tid = -1 if REQUEST_CACHE['enabled']: tid = cache_get_request_uid() if tid > -1: try: obj = REQUEST_CACHE[tid][key] log.debug('Got from request cache: %s', key) except KeyError: pass if obj == None: obj = cache.get(key) if obj and isinstance(obj, CacheWrapper): CACHE_HITS += 1 CACHED_KEYS[key] = True log.debug('got cached [%i/%i]: %s', CACHE_CALLS, CACHE_HITS, key) if obj.inprocess: raise MethodNotFinishedError(obj.val) cache_set_request(key, obj, uid=tid) return obj.val else: try: del CACHED_KEYS[key] except KeyError: pass if use_default: return default_value raise NotCachedError(key) def cache_set(*keys, **kwargs): """Set the object identified by all ``keys`` into the cache. kwargs: value: The object to be cached. length: Timeout for the object. Default is CACHE_TIMEOUT. skiplog: If it is True the call is never logged. Default is False. other kwargs: Unknown key=val is interpreted like two aditional keys: (key, val) """ if cache_enabled(): global CACHED_KEYS, REQUEST_CACHE obj = kwargs.pop('value') length = kwargs.pop('length', CACHE_TIMEOUT) skiplog = kwargs.pop('skiplog', False) key = cache_key(keys, **kwargs) val = CacheWrapper.wrap(obj) if not skiplog: log.debug('setting cache: %s', key) cache.set(key, val, length) CACHED_KEYS[key] = True if REQUEST_CACHE['enabled']: cache_set_request(key, val) def _hash_or_string(key): if is_string_like(key) or isinstance(key, (int, float)): return smart_str(key) else: try: #if it has a PK, use it. return str(key._get_pk_val()) except AttributeError: return md5_hash(key) def cache_key(*keys, **pairs): """Smart key maker, returns the object itself if a key, else a list delimited by ':', automatically hashing any non-scalar objects.""" if len(keys) == 1 and is_list_or_tuple(keys[0]): keys = keys[0] if pairs: keys = list(keys) for k in sorted(pairs.keys()): keys.extend((k, pairs[k])) key = KEY_DELIM.join([_hash_or_string(x) for x in keys]) return key.replace(" ", ".") def md5_hash(obj): pickled = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL) return md5(pickled).hexdigest() def is_memcached_backend(): try: return cache._cache.__module__.endswith('memcache') except AttributeError: return False def cache_require(): """Error if keyedcache isn't running.""" if cache_enabled(): key = cache_key('require_cache') cache_set(key,value='1') v = cache_get(key, default = '0') if v != '1': raise CacheNotRespondingError() else: log.debug("Cache responding OK") return True def cache_clear_request(uid): """Clears all locally cached elements with that uid""" global REQUEST_CACHE try: del REQUEST_CACHE[uid] log.debug('cleared request cache: %s', uid) except KeyError: pass def cache_use_request_caching(): global REQUEST_CACHE REQUEST_CACHE['enabled'] = True def cache_get_request_uid(): from threaded_multihost import threadlocals return threadlocals.get_thread_variable('request_uid', -1) def cache_set_request(key, val, uid=None): if uid == None: uid = cache_get_request_uid() if uid>-1: global REQUEST_CACHE if not uid in REQUEST_CACHE: REQUEST_CACHE[uid] = {key:val} else: REQUEST_CACHE[uid][key] = val
{ "repo_name": "aronysidoro/django-keyedcache", "path": "keyed/keyedcache/__init__.py", "copies": "1", "size": "13665", "license": "bsd-3-clause", "hash": -7082524250300255000, "line_mean": 32.0072463768, "line_max": 106, "alpha_frac": 0.6110501281, "autogenerated": false, "ratio": 4.082760681207051, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5193810809307051, "avg_score": null, "num_lines": null }
"""A full cache system written on top of Django's rudimentary one.""" from django.conf import settings from django.core.cache import cache from django.utils.encoding import smart_str from django.utils.hashcompat import md5_constructor from keyedcache.utils import is_string_like, is_list_or_tuple import cPickle as pickle import logging import types log = logging.getLogger('keyedcache') CACHED_KEYS = {} CACHE_CALLS = 0 CACHE_HITS = 0 KEY_DELIM = "::" REQUEST_CACHE = {'enabled' : False} try: CACHE_PREFIX = settings.CACHE_PREFIX except AttributeError: CACHE_PREFIX = str(settings.SITE_ID) log.warn("No CACHE_PREFIX found in settings, using SITE_ID. Please update your settings to add a CACHE_PREFIX") try: CACHE_TIMEOUT = settings.CACHE_TIMEOUT except AttributeError: CACHE_TIMEOUT = 0 log.warn("No CACHE_TIMEOUT found in settings, so we used 0, disabling the cache system. Please update your settings to add a CACHE_TIMEOUT and avoid this warning.") _CACHE_ENABLED = CACHE_TIMEOUT > 0 class CacheWrapper(object): def __init__(self, val, inprocess=False): self.val = val self.inprocess = inprocess def __str__(self): return str(self.val) def __repr__(self): return repr(self.val) def wrap(cls, obj): if isinstance(obj, cls): return obj else: return cls(obj) wrap = classmethod(wrap) class MethodNotFinishedError(Exception): def __init__(self, f): self.func = f class NotCachedError(Exception): def __init__(self, k): self.key = k class CacheNotRespondingError(Exception): pass def cache_delete(*keys, **kwargs): removed = [] if cache_enabled(): global CACHED_KEYS log.debug('cache_delete') children = kwargs.pop('children',False) if (keys or kwargs): key = cache_key(*keys, **kwargs) if CACHED_KEYS.has_key(key): del CACHED_KEYS[key] removed.append(key) cache.delete(key) if children: key = key + KEY_DELIM children = [x for x in CACHED_KEYS.keys() if x.startswith(key)] for k in children: del CACHED_KEYS[k] cache.delete(k) removed.append(k) else: key = "All Keys" deleteneeded = _cache_flush_all() removed = CACHED_KEYS.keys() if deleteneeded: for k in CACHED_KEYS: cache.delete(k) CACHED_KEYS = {} if removed: log.debug("Cache delete: %s", removed) else: log.debug("No cached objects to delete for %s", key) return removed def cache_delete_function(func): return cache_delete(['func', func.__name__, func.__module__], children=True) def cache_enabled(): global _CACHE_ENABLED return _CACHE_ENABLED def cache_enable(state=True): global _CACHE_ENABLED _CACHE_ENABLED=state def _cache_flush_all(): if is_memcached_backend(): cache._cache.flush_all() return False return True def cache_function(length=CACHE_TIMEOUT): """ A variant of the snippet posted by Jeff Wheeler at http://www.djangosnippets.org/snippets/109/ Caches a function, using the function and its arguments as the key, and the return value as the value saved. It passes all arguments on to the function, as it should. The decorator itself takes a length argument, which is the number of seconds the cache will keep the result around. It will put a temp value in the cache while the function is processing. This should not matter in most cases, but if the app is using threads, you won't be able to get the previous value, and will need to wait until the function finishes. If this is not desired behavior, you can remove the first two lines after the ``else``. """ def decorator(func): def inner_func(*args, **kwargs): if not cache_enabled(): value = func(*args, **kwargs) else: try: value = cache_get('func', func.__name__, func.__module__, args, kwargs) except NotCachedError, e: # This will set a temporary value while ``func`` is being # processed. When using threads, this is vital, as otherwise # the function can be called several times before it finishes # and is put into the cache. funcwrapper = CacheWrapper(".".join([func.__module__, func.__name__]), inprocess=True) cache_set(e.key, value=funcwrapper, length=length, skiplog=True) value = func(*args, **kwargs) cache_set(e.key, value=value, length=length) except MethodNotFinishedError, e: value = func(*args, **kwargs) return value return inner_func return decorator def cache_get(*keys, **kwargs): if kwargs.has_key('default'): default_value = kwargs.pop('default') use_default = True else: use_default = False key = cache_key(keys, **kwargs) if not cache_enabled(): raise NotCachedError(key) else: global CACHE_CALLS, CACHE_HITS, REQUEST_CACHE CACHE_CALLS += 1 if CACHE_CALLS == 1: cache_require() obj = None tid = -1 if REQUEST_CACHE['enabled']: tid = cache_get_request_uid() if tid > -1: try: obj = REQUEST_CACHE[tid][key] log.debug('Got from request cache: %s', key) except KeyError: pass if obj == None: obj = cache.get(key) if obj and isinstance(obj, CacheWrapper): CACHE_HITS += 1 CACHED_KEYS[key] = True log.debug('got cached [%i/%i]: %s', CACHE_CALLS, CACHE_HITS, key) if obj.inprocess: raise MethodNotFinishedError(obj.val) cache_set_request(key, obj, uid=tid) return obj.val else: try: del CACHED_KEYS[key] except KeyError: pass if use_default: return default_value raise NotCachedError(key) def cache_set(*keys, **kwargs): """Set an object into the cache.""" if cache_enabled(): global CACHED_KEYS, REQUEST_CACHE obj = kwargs.pop('value') length = kwargs.pop('length', CACHE_TIMEOUT) skiplog = kwargs.pop('skiplog', False) key = cache_key(keys, **kwargs) val = CacheWrapper.wrap(obj) if not skiplog: log.debug('setting cache: %s', key) cache.set(key, val, length) CACHED_KEYS[key] = True if REQUEST_CACHE['enabled']: cache_set_request(key, val) def _hash_or_string(key): if is_string_like(key) or isinstance(key, (types.IntType, types.LongType, types.FloatType)): return smart_str(key) else: try: #if it has a PK, use it. return str(key._get_pk_val()) except AttributeError: return md5_hash(key) def cache_contains(*keys, **kwargs): key = cache_key(keys, **kwargs) return CACHED_KEYS.has_key(key) def cache_key(*keys, **pairs): """Smart key maker, returns the object itself if a key, else a list delimited by ':', automatically hashing any non-scalar objects.""" if is_string_like(keys): keys = [keys] if is_list_or_tuple(keys): if len(keys) == 1 and is_list_or_tuple(keys[0]): keys = keys[0] else: keys = [md5_hash(keys)] if pairs: keys = list(keys) klist = pairs.keys() klist.sort() for k in klist: keys.append(k) keys.append(pairs[k]) key = KEY_DELIM.join([_hash_or_string(x) for x in keys]) prefix = CACHE_PREFIX + KEY_DELIM if not key.startswith(prefix): key = prefix+key return key.replace(" ", ".") def md5_hash(obj): pickled = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL) return md5_constructor(pickled).hexdigest() def is_memcached_backend(): try: return cache._cache.__module__.endswith('memcache') except AttributeError: return False def cache_require(): """Error if keyedcache isn't running.""" if cache_enabled(): key = cache_key('require_cache') cache_set(key,value='1') v = cache_get(key, default = '0') if v != '1': raise CacheNotRespondingError() else: log.debug("Cache responding OK") return True def cache_clear_request(uid): """Clears all locally cached elements with that uid""" global REQUEST_CACHE try: del REQUEST_CACHE[uid] log.debug('cleared request cache: %s', uid) except KeyError: pass def cache_use_request_caching(): global REQUEST_CACHE REQUEST_CACHE['enabled'] = True def cache_get_request_uid(): from threaded_multihost import threadlocals return threadlocals.get_thread_variable('request_uid', -1) def cache_set_request(key, val, uid=None): if uid == None: uid = cache_get_request_uid() if uid>-1: global REQUEST_CACHE if not uid in REQUEST_CACHE: REQUEST_CACHE[uid] = {key:val} else: REQUEST_CACHE[uid][key] = val
{ "repo_name": "grengojbo/django-keyedcache", "path": "keyedcache/__init__.py", "copies": "2", "size": "9622", "license": "bsd-3-clause", "hash": -4328778653628159500, "line_mean": 28.2462006079, "line_max": 169, "alpha_frac": 0.5819995843, "autogenerated": false, "ratio": 3.936988543371522, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5518988127671522, "avg_score": null, "num_lines": null }
"""A full cache system written on top of Django's rudimentary one.""" from django.conf import settings from django.core.cache import cache from django.utils.encoding import smart_str import cPickle as pickle import md5 import types import logging from satchmo.utils import is_string_like, is_list_or_tuple log = logging.getLogger('caching') CACHED_KEYS = {} CACHE_CALLS = 0 CACHE_HITS = 0 KEY_DELIM = "::" try: CACHE_PREFIX = settings.CACHE_PREFIX except AttributeError: CACHE_PREFIX = str(settings.SITE_ID) log.warn("No CACHE_PREFIX found in settings, using SITE_ID. Please update your settings to add a CACHE_PREFIX") _CACHE_ENABLED = settings.CACHE_TIMEOUT > 0 class CacheWrapper(object): def __init__(self, val, inprocess=False): self.val = val self.inprocess = inprocess def __str__(self): return str(self.val) def __repr__(self): return repr(self.val) def wrap(cls, obj): if isinstance(obj, cls): return obj else: return cls(obj) wrap = classmethod(wrap) class MethodNotFinishedError(Exception): def __init__(self, f): self.func = f class NotCachedError(Exception): def __init__(self, k): self.key = k class CacheNotRespondingError(Exception): pass def cache_delete(*keys, **kwargs): removed = [] if cache_enabled(): global CACHED_KEYS log.debug('cache_delete') children = kwargs.pop('children',False) if (keys or kwargs): key = cache_key(*keys, **kwargs) if CACHED_KEYS.has_key(key): del CACHED_KEYS[key] removed.append(key) cache.delete(key) if children: key = key + KEY_DELIM children = [x for x in CACHED_KEYS.keys() if x.startswith(key)] for k in children: del CACHED_KEYS[k] cache.delete(k) removed.append(k) else: key = "All Keys" deleteneeded = _cache_flush_all() removed = CACHED_KEYS.keys() if deleteneeded: for k in CACHED_KEYS: cache.delete(k) CACHED_KEYS = {} if removed: log.debug("Cache delete: %s", removed) else: log.debug("No cached objects to delete for %s", key) return removed def cache_delete_function(func): return cache_delete(['func', func.__name__, func.__module__], children=True) def cache_enabled(): global _CACHE_ENABLED return _CACHE_ENABLED def cache_enable(state=True): global _CACHE_ENABLED _CACHE_ENABLED=state def _cache_flush_all(): if is_memcached_backend(): cache._cache.flush_all() return False return True def cache_function(length=settings.CACHE_TIMEOUT): """ A variant of the snippet posted by Jeff Wheeler at http://www.djangosnippets.org/snippets/109/ Caches a function, using the function and its arguments as the key, and the return value as the value saved. It passes all arguments on to the function, as it should. The decorator itself takes a length argument, which is the number of seconds the cache will keep the result around. It will put a temp value in the cache while the function is processing. This should not matter in most cases, but if the app is using threads, you won't be able to get the previous value, and will need to wait until the function finishes. If this is not desired behavior, you can remove the first two lines after the ``else``. """ def decorator(func): def inner_func(*args, **kwargs): if not cache_enabled(): value = func(*args, **kwargs) else: try: value = cache_get('func', func.__name__, func.__module__, args, kwargs) except NotCachedError, e: # This will set a temporary value while ``func`` is being # processed. When using threads, this is vital, as otherwise # the function can be called several times before it finishes # and is put into the cache. funcwrapper = CacheWrapper(".".join([func.__module__, func.__name__]), inprocess=True) cache_set(e.key, value=funcwrapper, length=length, skiplog=True) value = func(*args, **kwargs) cache_set(e.key, value=value, length=length) except MethodNotFinishedError, e: value = func(*args, **kwargs) return value return inner_func return decorator def cache_get(*keys, **kwargs): if kwargs.has_key('default'): default_value = kwargs.pop('default') use_default = True else: use_default = False key = cache_key(keys, **kwargs) if not cache_enabled(): raise NotCachedError(key) else: global CACHE_CALLS, CACHE_HITS CACHE_CALLS += 1 if CACHE_CALLS == 1: cache_require() obj = cache.get(key) if obj and isinstance(obj, CacheWrapper): CACHE_HITS += 1 CACHED_KEYS[key] = True log.debug('got cached [%i/%i]: %s', CACHE_CALLS, CACHE_HITS, key) if obj.inprocess: raise MethodNotFinishedError(obj.val) return obj.val else: try: del CACHED_KEYS[key] except KeyError: pass if use_default: return default_value raise NotCachedError(key) def cache_set(*keys, **kwargs): """Set an object into the cache.""" if cache_enabled(): global CACHED_KEYS obj = kwargs.pop('value') length = kwargs.pop('length', settings.CACHE_TIMEOUT) skiplog = kwargs.pop('skiplog', False) key = cache_key(keys, **kwargs) val = CacheWrapper.wrap(obj) if not skiplog: log.debug('setting cache: %s', key) cache.set(key, val, length) CACHED_KEYS[key] = True def _hash_or_string(key): if is_string_like(key) or isinstance(key, (types.IntType, types.LongType, types.FloatType)): return smart_str(key) else: try: #if it has a PK, use it. return str(key._get_pk_val()) except AttributeError: return md5_hash(key) def cache_contains(*keys, **kwargs): key = cache_key(keys, **kwargs) return CACHED_KEYS.has_key(key) def cache_key(*keys, **pairs): """Smart key maker, returns the object itself if a key, else a list delimited by ':', automatically hashing any non-scalar objects.""" if is_string_like(keys): keys = [keys] if is_list_or_tuple(keys): if len(keys) == 1 and is_list_or_tuple(keys[0]): keys = keys[0] else: keys = [md5_hash(keys)] if pairs: keys = list(keys) klist = pairs.keys() klist.sort() for k in klist: keys.append(k) keys.append(pairs[k]) key = KEY_DELIM.join([_hash_or_string(x) for x in keys]) prefix = CACHE_PREFIX + KEY_DELIM if not key.startswith(prefix): key = prefix+key return key.replace(" ", ".") def md5_hash(obj): pickled = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL) return md5.new(pickled).hexdigest() def is_memcached_backend(): try: return cache._cache.__module__.endswith('memcache') except AttributeError: return False def cache_require(): """Error if caching isn't running.""" if cache_enabled(): key = cache_key('require_cache') cache_set(key,value='1') v = cache_get(key, default = '0') if v != '1': raise CacheNotRespondingError() else: log.debug("Cache responding OK") return True
{ "repo_name": "sankroh/satchmo", "path": "satchmo/caching/__init__.py", "copies": "2", "size": "8134", "license": "bsd-3-clause", "hash": -4469772896283698700, "line_mean": 28.1541218638, "line_max": 116, "alpha_frac": 0.5703221047, "autogenerated": false, "ratio": 3.9872549019607844, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5557577006660784, "avg_score": null, "num_lines": null }