text
stringlengths
12
1.05M
repo_name
stringlengths
5
86
path
stringlengths
4
191
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
12
1.05M
keyword
listlengths
1
23
text_hash
stringlengths
64
64
from django.test import TestCase from django.contrib.auth import get_user_model from experiments.models import Experiment, ENABLED_STATE from experiments.signals import user_enrolled from experiments.utils import participant EXPERIMENT_NAME = 'backgroundcolor' class WatchSignal(object): def __init__(self, signal): self.signal = signal self.called = False def __enter__(self): self.signal.connect(self.signal_handler) return self def __exit__(self, *args): self.signal.disconnect(self.signal_handler) def signal_handler(self, *args, **kwargs): self.called = True class SignalsTestCase(TestCase): def setUp(self): self.experiment = Experiment.objects.create(name=EXPERIMENT_NAME, state=ENABLED_STATE) User = get_user_model() self.user = User.objects.create(username='brian') def test_sends_enroll_signal(self): with WatchSignal(user_enrolled) as signal: participant(user=self.user).enroll(EXPERIMENT_NAME, ['red', 'blue']) self.assertTrue(signal.called) def test_does_not_send_enroll_signal_again(self): participant(user=self.user).enroll(EXPERIMENT_NAME, ['red', 'blue']) with WatchSignal(user_enrolled) as signal: participant(user=self.user).enroll(EXPERIMENT_NAME, ['red', 'blue']) self.assertFalse(signal.called)
squamous/django-experiments
experiments/tests/test_signals.py
Python
mit
1,400
[ "Brian" ]
38a5868a5fd378cf1d32cdb33c871c9ab0a9e6d9a63ea378e5a6eddd3a807659
""" The image module supports basic image loading, rescaling and display operations. """ from __future__ import division import os, warnings import numpy as np from numpy import ma from matplotlib import rcParams import matplotlib.artist as martist from matplotlib.artist import allow_rasterization import matplotlib.colors as mcolors import matplotlib.cm as cm import matplotlib.cbook as cbook # For clarity, names from _image are given explicitly in this module: import matplotlib._image as _image import matplotlib._png as _png # For user convenience, the names from _image are also imported into # the image namespace: from matplotlib._image import * from matplotlib.transforms import BboxBase, Bbox import matplotlib.transforms as mtransforms class _AxesImageBase(martist.Artist, cm.ScalarMappable): zorder = 0 # map interpolation strings to module constants _interpd = { 'none' : _image.NEAREST, # fall back to nearest when not supported 'nearest' : _image.NEAREST, 'bilinear' : _image.BILINEAR, 'bicubic' : _image.BICUBIC, 'spline16' : _image.SPLINE16, 'spline36' : _image.SPLINE36, 'hanning' : _image.HANNING, 'hamming' : _image.HAMMING, 'hermite' : _image.HERMITE, 'kaiser' : _image.KAISER, 'quadric' : _image.QUADRIC, 'catrom' : _image.CATROM, 'gaussian' : _image.GAUSSIAN, 'bessel' : _image.BESSEL, 'mitchell' : _image.MITCHELL, 'sinc' : _image.SINC, 'lanczos' : _image.LANCZOS, 'blackman' : _image.BLACKMAN, } # reverse interp dict _interpdr = dict([ (v,k) for k,v in _interpd.items()]) interpnames = _interpd.keys() def __str__(self): return "AxesImage(%g,%g;%gx%g)" % tuple(self.axes.bbox.bounds) def __init__(self, ax, cmap = None, norm = None, interpolation=None, origin=None, filternorm=1, filterrad=4.0, resample = False, **kwargs ): """ interpolation and cmap default to their rc settings cmap is a colors.Colormap instance norm is a colors.Normalize instance to map luminance to 0-1 extent is data axes (left, right, bottom, top) for making image plots registered with data plots. Default is to label the pixel centers with the zero-based row and column indices. Additional kwargs are matplotlib.artist properties """ martist.Artist.__init__(self) cm.ScalarMappable.__init__(self, norm, cmap) if origin is None: origin = rcParams['image.origin'] self.origin = origin self.set_filternorm(filternorm) self.set_filterrad(filterrad) self._filterrad = filterrad self.set_interpolation(interpolation) self.set_resample(resample) self.axes = ax self._imcache = None # this is an experimental attribute, if True, unsampled image # will be drawn using the affine transform that are # appropriately skewed so that the given position # corresponds to the actual position in the coordinate. -JJL self._image_skew_coordinate = None self.update(kwargs) def get_size(self): """Get the numrows, numcols of the input image""" if self._A is None: raise RuntimeError('You must first set the image array') return self._A.shape[:2] def set_alpha(self, alpha): """ Set the alpha value used for blending - not supported on all backends ACCEPTS: float """ martist.Artist.set_alpha(self, alpha) self._imcache = None def changed(self): """ Call this whenever the mappable is changed so observers can update state """ self._imcache = None self._rgbacache = None cm.ScalarMappable.changed(self) def make_image(self, magnification=1.0): raise RuntimeError('The make_image method must be overridden.') def _get_unsampled_image(self, A, image_extents, viewlim): """ convert numpy array A with given extents ([x1, x2, y1, y2] in data coordinate) into the Image, given the viewlim (should be a bbox instance). Image will be clipped if the extents is significantly larger than the viewlim. """ xmin, xmax, ymin, ymax = image_extents dxintv = xmax-xmin dyintv = ymax-ymin # the viewport scale factor if viewlim.width == 0.0 and dxintv == 0.0: sx = 1.0 else: sx = dxintv/viewlim.width if viewlim.height == 0.0 and dyintv == 0.0: sy = 1.0 else: sy = dyintv/viewlim.height numrows, numcols = A.shape[:2] if sx > 2: x0 = (viewlim.x0-xmin)/dxintv * numcols ix0 = max(0, int(x0 - self._filterrad)) x1 = (viewlim.x1-xmin)/dxintv * numcols ix1 = min(numcols, int(x1 + self._filterrad)) xslice = slice(ix0, ix1) xmin_old = xmin xmin = xmin_old + ix0*dxintv/numcols xmax = xmin_old + ix1*dxintv/numcols dxintv = xmax - xmin sx = dxintv/viewlim.width else: xslice = slice(0, numcols) if sy > 2: y0 = (viewlim.y0-ymin)/dyintv * numrows iy0 = max(0, int(y0 - self._filterrad)) y1 = (viewlim.y1-ymin)/dyintv * numrows iy1 = min(numrows, int(y1 + self._filterrad)) if self.origin == 'upper': yslice = slice(numrows-iy1, numrows-iy0) else: yslice = slice(iy0, iy1) ymin_old = ymin ymin = ymin_old + iy0*dyintv/numrows ymax = ymin_old + iy1*dyintv/numrows dyintv = ymax - ymin sy = dyintv/viewlim.height else: yslice = slice(0, numrows) if xslice != self._oldxslice or yslice != self._oldyslice: self._imcache = None self._oldxslice = xslice self._oldyslice = yslice if self._imcache is None: if self._A.dtype == np.uint8 and self._A.ndim == 3: im = _image.frombyte(self._A[yslice,xslice,:], 0) im.is_grayscale = False else: if self._rgbacache is None: x = self.to_rgba(self._A, bytes=True) self._rgbacache = x else: x = self._rgbacache im = _image.frombyte(x[yslice,xslice,:], 0) if self._A.ndim == 2: im.is_grayscale = self.cmap.is_gray() else: im.is_grayscale = False self._imcache = im if self.origin=='upper': im.flipud_in() else: im = self._imcache return im, xmin, ymin, dxintv, dyintv, sx, sy @staticmethod def _get_rotate_and_skew_transform(x1, y1, x2, y2, x3, y3): """ Retuen a transform that does (x1, y1) -> (x1, y1) (x2, y2) -> (x2, y2) (x2, y1) -> (x3, y3) It was intended to derive a skew transform that preserve the lower-left corner (x1, y1) and top-right corner(x2,y2), but change the the lower-right-corner(x2, y1) to a new position (x3, y3). """ tr1 = mtransforms.Affine2D() tr1.translate(-x1, -y1) x2a, y2a = tr1.transform_point((x2, y2)) x3a, y3a = tr1.transform_point((x3, y3)) inv_mat = 1./(x2a*y3a-y2a*x3a) * np.mat([[y3a, -y2a],[-x3a, x2a]]) a, b = (inv_mat * np.mat([[x2a], [x2a]])).flat c, d = (inv_mat * np.mat([[y2a], [0]])).flat tr2 = mtransforms.Affine2D.from_values(a, c, b, d, 0, 0) tr = (tr1 + tr2 + mtransforms.Affine2D().translate(x1, y1)).inverted().get_affine() return tr def _draw_unsampled_image(self, renderer, gc): """ draw unsampled image. The renderer should support a draw_image method with scale parameter. """ trans = self.get_transform() #axes.transData # convert the coordinates to the intermediate coordinate (ic). # The transformation from the ic to the canvas is a pure # affine transform. # A straight-forward way is to use the non-affine part of the # original transform for conversion to the ic. # firs, convert the image extent to the ic x_llc, x_trc, y_llc, y_trc = self.get_extent() xy = trans.transform_non_affine(np.array([(x_llc, y_llc), (x_trc, y_trc)])) _xx1, _yy1 = xy[0] _xx2, _yy2 = xy[1] extent_in_ic = _xx1, _xx2, _yy1, _yy2 # define trans_ic_to_canvas : unless _image_skew_coordinate is # set, it is simply a affine part of the original transform. if self._image_skew_coordinate: # skew the image when required. x_lrc, y_lrc = self._image_skew_coordinate xy2 = trans.transform_non_affine(np.array([(x_lrc, y_lrc)])) _xx3, _yy3 = xy2[0] tr_rotate_skew = self._get_rotate_and_skew_transform(_xx1, _yy1, _xx2, _yy2, _xx3, _yy3) trans_ic_to_canvas = tr_rotate_skew+trans.get_affine() else: trans_ic_to_canvas = trans.get_affine() # Now, viewLim in the ic. It can be rotated and can be # skewed. Make it big enough. x1, y1, x2, y2 = self.axes.bbox.extents trans_canvas_to_ic = trans_ic_to_canvas.inverted() xy_ = trans_canvas_to_ic.transform(np.array([(x1, y1), (x2, y1), (x2, y2), (x1, y2)])) x1_, x2_ = min(xy_[:,0]), max(xy_[:,0]) y1_, y2_ = min(xy_[:,1]), max(xy_[:,1]) viewLim_in_ic = Bbox.from_extents(x1_, y1_, x2_, y2_) # get the image, sliced if necessary. This is done in the ic. im, xmin, ymin, dxintv, dyintv, sx, sy = \ self._get_unsampled_image(self._A, extent_in_ic, viewLim_in_ic) if im is None: return # I'm not if this check is required. -JJL fc = self.axes.patch.get_facecolor() bg = mcolors.colorConverter.to_rgba(fc, 0) im.set_bg( *bg) # image input dimensions im.reset_matrix() numrows, numcols = im.get_size() im.resize(numcols, numrows) # just to create im.bufOut that # is required by backends. There # may be better solution -JJL im._url = self.get_url() renderer.draw_image(gc, xmin, ymin, im, dxintv, dyintv, trans_ic_to_canvas) def _check_unsampled_image(self, renderer): """ return True if the image is better to be drawn unsampled. The derived class needs to override it. """ return False @allow_rasterization def draw(self, renderer, *args, **kwargs): if not self.get_visible(): return if (self.axes.get_xscale() != 'linear' or self.axes.get_yscale() != 'linear'): warnings.warn("Images are not supported on non-linear axes.") l, b, widthDisplay, heightDisplay = self.axes.bbox.bounds gc = renderer.new_gc() gc.set_clip_rectangle(self.axes.bbox.frozen()) gc.set_clip_path(self.get_clip_path()) gc.set_alpha(self.get_alpha()) if self._check_unsampled_image(renderer): self._draw_unsampled_image(renderer, gc) else: if self._image_skew_coordinate is not None: warnings.warn("Image will not be shown correctly with this backend.") im = self.make_image(renderer.get_image_magnification()) if im is None: return im._url = self.get_url() renderer.draw_image(gc, l, b, im) gc.restore() def contains(self, mouseevent): """ Test whether the mouse event occured within the image. """ if callable(self._contains): return self._contains(self,mouseevent) # TODO: make sure this is consistent with patch and patch # collection on nonlinear transformed coordinates. # TODO: consider returning image coordinates (shouldn't # be too difficult given that the image is rectilinear x, y = mouseevent.xdata, mouseevent.ydata xmin, xmax, ymin, ymax = self.get_extent() if xmin > xmax: xmin,xmax = xmax,xmin if ymin > ymax: ymin,ymax = ymax,ymin #print x, y, xmin, xmax, ymin, ymax if x is not None and y is not None: inside = x>=xmin and x<=xmax and y>=ymin and y<=ymax else: inside = False return inside,{} def write_png(self, fname, noscale=False): """Write the image to png file with fname""" im = self.make_image() if im is None: return if noscale: numrows, numcols = im.get_size() im.reset_matrix() im.set_interpolation(0) im.resize(numcols, numrows) im.flipud_out() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, fname) def set_data(self, A): """ Set the image array ACCEPTS: numpy/PIL Image A """ # check if data is PIL Image without importing Image if hasattr(A,'getpixel'): self._A = pil_to_array(A) else: self._A = cbook.safe_masked_invalid(A) if self._A.dtype != np.uint8 and not np.can_cast(self._A.dtype, np.float): raise TypeError("Image data can not convert to float") if (self._A.ndim not in (2, 3) or (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))): raise TypeError("Invalid dimensions for image data") self._imcache =None self._rgbacache = None self._oldxslice = None self._oldyslice = None def set_array(self, A): """ Retained for backwards compatibility - use set_data instead ACCEPTS: numpy array A or PIL Image""" # This also needs to be here to override the inherited # cm.ScalarMappable.set_array method so it is not invoked # by mistake. self.set_data(A) def get_interpolation(self): """ Return the interpolation method the image uses when resizing. One of 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', or 'none'. """ return self._interpolation def set_interpolation(self, s): """ Set the interpolation method the image uses when resizing. if None, use a value from rc setting. If 'none', the image is shown as is without interpolating. 'none' is only supported in agg, ps and pdf backends and will fall back to 'nearest' mode for other backends. ACCEPTS: ['nearest' | 'bilinear' | 'bicubic' | 'spline16' | 'spline36' | 'hanning' | 'hamming' | 'hermite' | 'kaiser' | 'quadric' | 'catrom' | 'gaussian' | 'bessel' | 'mitchell' | 'sinc' | 'lanczos' | 'none' |] """ if s is None: s = rcParams['image.interpolation'] s = s.lower() if s not in self._interpd: raise ValueError('Illegal interpolation string') self._interpolation = s def set_resample(self, v): """ Set whether or not image resampling is used ACCEPTS: True|False """ if v is None: v = rcParams['image.resample'] self._resample = v def get_resample(self): """Return the image resample boolean""" return self._resample def set_filternorm(self, filternorm): """ Set whether the resize filter norms the weights -- see help for imshow ACCEPTS: 0 or 1 """ if filternorm: self._filternorm = 1 else: self._filternorm = 0 def get_filternorm(self): """Return the filternorm setting""" return self._filternorm def set_filterrad(self, filterrad): """ Set the resize filter radius only applicable to some interpolation schemes -- see help for imshow ACCEPTS: positive float """ r = float(filterrad) assert(r>0) self._filterrad = r def get_filterrad(self): """return the filterrad setting""" return self._filterrad class AxesImage(_AxesImageBase): def __str__(self): return "AxesImage(%g,%g;%gx%g)" % tuple(self.axes.bbox.bounds) def __init__(self, ax, cmap = None, norm = None, interpolation=None, origin=None, extent=None, filternorm=1, filterrad=4.0, resample = False, **kwargs ): """ interpolation and cmap default to their rc settings cmap is a colors.Colormap instance norm is a colors.Normalize instance to map luminance to 0-1 extent is data axes (left, right, bottom, top) for making image plots registered with data plots. Default is to label the pixel centers with the zero-based row and column indices. Additional kwargs are matplotlib.artist properties """ self._extent = extent _AxesImageBase.__init__(self, ax, cmap = cmap, norm = norm, interpolation=interpolation, origin=origin, filternorm=filternorm, filterrad=filterrad, resample = resample, **kwargs ) def make_image(self, magnification=1.0): if self._A is None: raise RuntimeError('You must first set the image array or the image attribute') # image is created in the canvas coordinate. x1, x2, y1, y2 = self.get_extent() trans = self.get_transform() xy = trans.transform(np.array([(x1, y1), (x2, y2), ])) _x1, _y1 = xy[0] _x2, _y2 = xy[1] transformed_viewLim = mtransforms.TransformedBbox(self.axes.viewLim, trans) im, xmin, ymin, dxintv, dyintv, sx, sy = \ self._get_unsampled_image(self._A, [_x1, _x2, _y1, _y2], transformed_viewLim) fc = self.axes.patch.get_facecolor() bg = mcolors.colorConverter.to_rgba(fc, 0) im.set_bg( *bg) # image input dimensions im.reset_matrix() numrows, numcols = im.get_size() if numrows < 1 or numcols < 1: # out of range return None im.set_interpolation(self._interpd[self._interpolation]) im.set_resample(self._resample) # the viewport translation if dxintv == 0.0: tx = 0.0 else: tx = (xmin-transformed_viewLim.x0)/dxintv * numcols if dyintv == 0.0: ty = 0.0 else: ty = (ymin-transformed_viewLim.y0)/dyintv * numrows im.apply_translation(tx, ty) l, b, r, t = self.axes.bbox.extents widthDisplay = (round(r*magnification) + 0.5) - (round(l*magnification) - 0.5) heightDisplay = (round(t*magnification) + 0.5) - (round(b*magnification) - 0.5) # resize viewport to display rx = widthDisplay / numcols ry = heightDisplay / numrows im.apply_scaling(rx*sx, ry*sy) im.resize(int(widthDisplay+0.5), int(heightDisplay+0.5), norm=self._filternorm, radius=self._filterrad) return im def _check_unsampled_image(self, renderer): """ return True if the image is better to be drawn unsampled. """ if self.get_interpolation() == "none": if renderer.option_scale_image(): return True else: warnings.warn("The backend (%s) does not support interpolation='none'. The image will be interpolated with 'nearest` mode." % renderer.__class__) return False def set_extent(self, extent): """ extent is data axes (left, right, bottom, top) for making image plots This updates ax.dataLim, and, if autoscaling, sets viewLim to tightly fit the image, regardless of dataLim. Autoscaling state is not changed, so following this with ax.autoscale_view will redo the autoscaling in accord with dataLim. """ self._extent = extent xmin, xmax, ymin, ymax = extent corners = (xmin, ymin), (xmax, ymax) self.axes.update_datalim(corners) if self.axes._autoscaleXon: self.axes.set_xlim((xmin, xmax), auto=None) if self.axes._autoscaleYon: self.axes.set_ylim((ymin, ymax), auto=None) def get_extent(self): """Get the image extent: left, right, bottom, top""" if self._extent is not None: return self._extent else: sz = self.get_size() #print 'sz', sz numrows, numcols = sz if self.origin == 'upper': return (-0.5, numcols-0.5, numrows-0.5, -0.5) else: return (-0.5, numcols-0.5, -0.5, numrows-0.5) class NonUniformImage(AxesImage): def __init__(self, ax, **kwargs): """ kwargs are identical to those for AxesImage, except that 'interpolation' defaults to 'nearest', and 'bilinear' is the only alternative. """ interp = kwargs.pop('interpolation', 'nearest') AxesImage.__init__(self, ax, **kwargs) self.set_interpolation(interp) def _check_unsampled_image(self, renderer): """ return False. Do not use unsampled image. """ return False def make_image(self, magnification=1.0): if self._A is None: raise RuntimeError('You must first set the image array') x0, y0, v_width, v_height = self.axes.viewLim.bounds l, b, r, t = self.axes.bbox.extents width = (round(r) + 0.5) - (round(l) - 0.5) height = (round(t) + 0.5) - (round(b) - 0.5) width *= magnification height *= magnification im = _image.pcolor(self._Ax, self._Ay, self._A, height, width, (x0, x0+v_width, y0, y0+v_height), self._interpd[self._interpolation]) fc = self.axes.patch.get_facecolor() bg = mcolors.colorConverter.to_rgba(fc, 0) im.set_bg(*bg) im.is_grayscale = self.is_grayscale return im def set_data(self, x, y, A): """ Set the grid for the pixel centers, and the pixel values. *x* and *y* are 1-D ndarrays of lengths N and M, respectively, specifying pixel centers *A* is an (M,N) ndarray or masked array of values to be colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA array. """ x = np.asarray(x,np.float32) y = np.asarray(y,np.float32) A = cbook.safe_masked_invalid(A) if len(x.shape) != 1 or len(y.shape) != 1\ or A.shape[0:2] != (y.shape[0], x.shape[0]): raise TypeError("Axes don't match array shape") if len(A.shape) not in [2, 3]: raise TypeError("Can only plot 2D or 3D data") if len(A.shape) == 3 and A.shape[2] not in [1, 3, 4]: raise TypeError("3D arrays must have three (RGB) or four (RGBA) color components") if len(A.shape) == 3 and A.shape[2] == 1: A.shape = A.shape[0:2] if len(A.shape) == 2: if A.dtype != np.uint8: A = self.to_rgba(A, bytes=True) self.is_grayscale = self.cmap.is_gray() else: A = np.repeat(A[:,:,np.newaxis], 4, 2) A[:,:,3] = 255 self.is_grayscale = True else: if A.dtype != np.uint8: A = (255*A).astype(np.uint8) if A.shape[2] == 3: B = zeros(tuple(list(A.shape[0:2]) + [4]), np.uint8) B[:,:,0:3] = A B[:,:,3] = 255 A = B self.is_grayscale = False self._A = A self._Ax = x self._Ay = y self._imcache = None # I am adding this in accor with _AxesImageBase.set_data -- # examples/pylab_examples/image_nonuniform.py was breaking on # the call to _get_unsampled_image when the oldxslice attr was # accessed - JDH 3/3/2010 self._oldxslice = None self._oldyslice = None def set_array(self, *args): raise NotImplementedError('Method not supported') def set_interpolation(self, s): if s != None and not s in ('nearest','bilinear'): raise NotImplementedError('Only nearest neighbor and bilinear interpolations are supported') AxesImage.set_interpolation(self, s) def get_extent(self): if self._A is None: raise RuntimeError('Must set data first') return self._Ax[0], self._Ax[-1], self._Ay[0], self._Ay[-1] def set_filternorm(self, s): pass def set_filterrad(self, s): pass def set_norm(self, norm): if self._A is not None: raise RuntimeError('Cannot change colors after loading data') cm.ScalarMappable.set_norm(self, norm) def set_cmap(self, cmap): if self._A is not None: raise RuntimeError('Cannot change colors after loading data') cm.ScalarMappable.set_cmap(self, cmap) class PcolorImage(martist.Artist, cm.ScalarMappable): """ Make a pcolor-style plot with an irregular rectangular grid. This uses a variation of the original irregular image code, and it is used by pcolorfast for the corresponding grid type. """ def __init__(self, ax, x=None, y=None, A=None, cmap = None, norm = None, **kwargs ): """ cmap defaults to its rc setting cmap is a colors.Colormap instance norm is a colors.Normalize instance to map luminance to 0-1 Additional kwargs are matplotlib.artist properties """ martist.Artist.__init__(self) cm.ScalarMappable.__init__(self, norm, cmap) self.axes = ax self._rgbacache = None # There is little point in caching the image itself because # it needs to be remade if the bbox or viewlim change, # so caching does help with zoom/pan/resize. self.update(kwargs) self.set_data(x, y, A) def make_image(self, magnification=1.0): if self._A is None: raise RuntimeError('You must first set the image array') fc = self.axes.patch.get_facecolor() bg = mcolors.colorConverter.to_rgba(fc, 0) bg = (np.array(bg)*255).astype(np.uint8) l, b, r, t = self.axes.bbox.extents width = (round(r) + 0.5) - (round(l) - 0.5) height = (round(t) + 0.5) - (round(b) - 0.5) width = width * magnification height = height * magnification if self._rgbacache is None: A = self.to_rgba(self._A, bytes=True) self._rgbacache = A if self._A.ndim == 2: self.is_grayscale = self.cmap.is_gray() else: A = self._rgbacache vl = self.axes.viewLim im = _image.pcolor2(self._Ax, self._Ay, A, height, width, (vl.x0, vl.x1, vl.y0, vl.y1), bg) im.is_grayscale = self.is_grayscale return im def changed(self): self._rgbacache = None cm.ScalarMappable.changed(self) @allow_rasterization def draw(self, renderer, *args, **kwargs): if not self.get_visible(): return im = self.make_image(renderer.get_image_magnification()) gc = renderer.new_gc() gc.set_clip_rectangle(self.axes.bbox.frozen()) gc.set_clip_path(self.get_clip_path()) gc.set_alpha(self.get_alpha()) renderer.draw_image(gc, round(self.axes.bbox.xmin), round(self.axes.bbox.ymin), im) gc.restore() def set_data(self, x, y, A): A = cbook.safe_masked_invalid(A) if x is None: x = np.arange(0, A.shape[1]+1, dtype=np.float64) else: x = np.asarray(x, np.float64).ravel() if y is None: y = np.arange(0, A.shape[0]+1, dtype=np.float64) else: y = np.asarray(y, np.float64).ravel() if A.shape[:2] != (y.size-1, x.size-1): print A.shape print y.size print x.size raise ValueError("Axes don't match array shape") if A.ndim not in [2, 3]: raise ValueError("A must be 2D or 3D") if A.ndim == 3 and A.shape[2] == 1: A.shape = A.shape[:2] self.is_grayscale = False if A.ndim == 3: if A.shape[2] in [3, 4]: if (A[:,:,0] == A[:,:,1]).all() and (A[:,:,0] == A[:,:,2]).all(): self.is_grayscale = True else: raise ValueError("3D arrays must have RGB or RGBA as last dim") self._A = A self._Ax = x self._Ay = y self._rgbacache = None def set_array(self, *args): raise NotImplementedError('Method not supported') def set_alpha(self, alpha): """ Set the alpha value used for blending - not supported on all backends ACCEPTS: float """ martist.Artist.set_alpha(self, alpha) self.update_dict['array'] = True class FigureImage(martist.Artist, cm.ScalarMappable): zorder = 0 def __init__(self, fig, cmap = None, norm = None, offsetx = 0, offsety = 0, origin=None, **kwargs ): """ cmap is a colors.Colormap instance norm is a colors.Normalize instance to map luminance to 0-1 kwargs are an optional list of Artist keyword args """ martist.Artist.__init__(self) cm.ScalarMappable.__init__(self, norm, cmap) if origin is None: origin = rcParams['image.origin'] self.origin = origin self.figure = fig self.ox = offsetx self.oy = offsety self.update(kwargs) self.magnification = 1.0 def contains(self, mouseevent): """Test whether the mouse event occured within the image.""" if callable(self._contains): return self._contains(self,mouseevent) xmin, xmax, ymin, ymax = self.get_extent() xdata, ydata = mouseevent.x, mouseevent.y #print xdata, ydata, xmin, xmax, ymin, ymax if xdata is not None and ydata is not None: inside = xdata>=xmin and xdata<=xmax and ydata>=ymin and ydata<=ymax else: inside = False return inside,{} def get_size(self): """Get the numrows, numcols of the input image""" if self._A is None: raise RuntimeError('You must first set the image array') return self._A.shape[:2] def get_extent(self): """Get the image extent: left, right, bottom, top""" numrows, numcols = self.get_size() return (-0.5+self.ox, numcols-0.5+self.ox, -0.5+self.oy, numrows-0.5+self.oy) def set_data(self, A): """Set the image array.""" cm.ScalarMappable.set_array(self, cbook.safe_masked_invalid(A)) def set_array(self, A): """Deprecated; use set_data for consistency with other image types.""" self.set_data(A) def make_image(self, magnification=1.0): if self._A is None: raise RuntimeError('You must first set the image array') x = self.to_rgba(self._A, bytes=True) self.magnification = magnification # if magnification is not one, we need to resize ismag = magnification!=1 #if ismag: raise RuntimeError if ismag: isoutput = 0 else: isoutput = 1 im = _image.frombyte(x, isoutput) fc = self.figure.get_facecolor() im.set_bg( *mcolors.colorConverter.to_rgba(fc, 0) ) im.is_grayscale = (self.cmap.name == "gray" and len(self._A.shape) == 2) if ismag: numrows, numcols = self.get_size() numrows *= magnification numcols *= magnification im.set_interpolation(_image.NEAREST) im.resize(numcols, numrows) if self.origin=='upper': im.flipud_out() return im @allow_rasterization def draw(self, renderer, *args, **kwargs): if not self.get_visible(): return # todo: we should be able to do some cacheing here im = self.make_image(renderer.get_image_magnification()) gc = renderer.new_gc() gc.set_clip_rectangle(self.figure.bbox) gc.set_clip_path(self.get_clip_path()) gc.set_alpha(self.get_alpha()) renderer.draw_image(gc, round(self.ox), round(self.oy), im) gc.restore() def write_png(self, fname): """Write the image to png file with fname""" im = self.make_image() rows, cols, buffer = im.as_rgba_str() _png.write_png(buffer, cols, rows, fname) class BboxImage(_AxesImageBase): """The Image class whose size is determined by the given bbox.""" def __init__(self, bbox, cmap = None, norm = None, interpolation=None, origin=None, filternorm=1, filterrad=4.0, resample = False, **kwargs ): """ cmap is a colors.Colormap instance norm is a colors.Normalize instance to map luminance to 0-1 kwargs are an optional list of Artist keyword args """ _AxesImageBase.__init__(self, ax=None, cmap = cmap, norm = norm, interpolation=interpolation, origin=origin, filternorm=filternorm, filterrad=filterrad, resample = resample, **kwargs ) self.bbox = bbox def get_window_extent(self, renderer=None): if renderer is None: renderer = self.get_figure()._cachedRenderer if isinstance(self.bbox, BboxBase): return self.bbox elif callable(self.bbox): return self.bbox(renderer) else: raise ValueError("unknown type of bbox") def contains(self, mouseevent): """Test whether the mouse event occured within the image.""" if callable(self._contains): return self._contains(self,mouseevent) if not self.get_visible():# or self.get_figure()._renderer is None: return False,{} x, y = mouseevent.x, mouseevent.y inside = self.get_window_extent().contains(x, y) return inside,{} def get_size(self): """Get the numrows, numcols of the input image""" if self._A is None: raise RuntimeError('You must first set the image array') return self._A.shape[:2] def make_image(self, renderer, magnification=1.0): if self._A is None: raise RuntimeError('You must first set the image array or the image attribute') if self._imcache is None: if self._A.dtype == np.uint8 and len(self._A.shape) == 3: im = _image.frombyte(self._A, 0) im.is_grayscale = False else: if self._rgbacache is None: x = self.to_rgba(self._A, bytes=True) self._rgbacache = x else: x = self._rgbacache im = _image.frombyte(x, 0) if len(self._A.shape) == 2: im.is_grayscale = self.cmap.is_gray() else: im.is_grayscale = False self._imcache = im if self.origin=='upper': im.flipud_in() else: im = self._imcache # image input dimensions im.reset_matrix() im.set_interpolation(self._interpd[self._interpolation]) im.set_resample(self._resample) l, b, r, t = self.get_window_extent(renderer).extents #bbox.extents widthDisplay = (round(r) + 0.5) - (round(l) - 0.5) heightDisplay = (round(t) + 0.5) - (round(b) - 0.5) widthDisplay *= magnification heightDisplay *= magnification numrows, numcols = self._A.shape[:2] # resize viewport to display rx = widthDisplay / numcols ry = heightDisplay / numrows #im.apply_scaling(rx*sx, ry*sy) im.apply_scaling(rx, ry) #im.resize(int(widthDisplay+0.5), int(heightDisplay+0.5), # norm=self._filternorm, radius=self._filterrad) im.resize(int(widthDisplay), int(heightDisplay), norm=self._filternorm, radius=self._filterrad) return im @allow_rasterization def draw(self, renderer, *args, **kwargs): if not self.get_visible(): return # todo: we should be able to do some cacheing here image_mag = renderer.get_image_magnification() im = self.make_image(renderer, image_mag) l, b, r, t = self.get_window_extent(renderer).extents gc = renderer.new_gc() self._set_gc_clip(gc) gc.set_alpha(self.get_alpha()) #gc.set_clip_path(self.get_clip_path()) renderer.draw_image(gc, round(l), round(b), im) gc.restore() def imread(fname, format=None): """ Return image file in *fname* as :class:`numpy.array`. *fname* may be a string path or a Python file-like object. If *format* is provided, will try to read file of that type, otherwise the format is deduced from the filename. If nothing can be deduced, PNG is tried. Return value is a :class:`numpy.array`. For grayscale images, the return array is MxN. For RGB images, the return value is MxNx3. For RGBA images the return value is MxNx4. matplotlib can only read PNGs natively, but if `PIL <http://www.pythonware.com/products/pil/>`_ is installed, it will use it to load the image and return an array (if possible) which can be used with :func:`~matplotlib.pyplot.imshow`. """ def pilread(): """try to load the image with PIL or return None""" try: from PIL import Image except ImportError: return None image = Image.open( fname ) return pil_to_array(image) handlers = {'png' :_png.read_png, } if format is None: if cbook.is_string_like(fname): basename, ext = os.path.splitext(fname) ext = ext.lower()[1:] else: ext = 'png' else: ext = format if ext not in handlers.keys(): im = pilread() if im is None: raise ValueError('Only know how to handle extensions: %s; with PIL installed matplotlib can handle more images' % handlers.keys()) return im handler = handlers[ext] # To handle Unicode filenames, we pass a file object to the PNG # reader extension, since Python handles them quite well, but it's # tricky in C. if cbook.is_string_like(fname): fname = open(fname, 'rb') return handler(fname) def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None, dpi=100): """ Saves a 2D :class:`numpy.array` as an image with one pixel per element. The output formats available depend on the backend being used. Arguments: *fname*: A string containing a path to a filename, or a Python file-like object. If *format* is *None* and *fname* is a string, the output format is deduced from the extension of the filename. *arr*: A 2D array. Keyword arguments: *vmin*/*vmax*: [ None | scalar ] *vmin* and *vmax* set the color scaling for the image by fixing the values that map to the colormap color limits. If either *vmin* or *vmax* is None, that limit is determined from the *arr* min/max value. *cmap*: cmap is a colors.Colormap instance, eg cm.jet. If None, default to the rc image.cmap value. *format*: One of the file extensions supported by the active backend. Most backends support png, pdf, ps, eps and svg. *origin* [ 'upper' | 'lower' ] Indicates where the [0,0] index of the array is in the upper left or lower left corner of the axes. Defaults to the rc image.origin value. *dpi* The DPI to store in the metadata of the file. This does not affect the resolution of the output image. """ from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure figsize = [x / float(dpi) for x in arr.shape[::-1]] fig = Figure(figsize=figsize, dpi=dpi, frameon=False) canvas = FigureCanvas(fig) im = fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin) fig.savefig(fname, dpi=dpi, format=format) def pil_to_array( pilImage ): """ load a PIL image and return it as a numpy array of uint8. For grayscale images, the return array is MxN. For RGB images, the return value is MxNx3. For RGBA images the return value is MxNx4 """ def toarray(im): """Teturn a 1D array of floats.""" x_str = im.tostring('raw',im.mode,0,-1) x = np.fromstring(x_str,np.uint8) return x if pilImage.mode in ('RGBA', 'RGBX'): im = pilImage # no need to convert images elif pilImage.mode=='L': im = pilImage # no need to luminance images # return MxN luminance array x = toarray(im) x.shape = im.size[1], im.size[0] return x elif pilImage.mode=='RGB': #return MxNx3 RGB array im = pilImage # no need to RGB images x = toarray(im) x.shape = im.size[1], im.size[0], 3 return x else: # try to convert to an rgba image try: im = pilImage.convert('RGBA') except ValueError: raise RuntimeError('Unknown image mode') # return MxNx4 RGBA array x = toarray(im) x.shape = im.size[1], im.size[0], 4 return x def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear', preview=False): """ make a thumbnail of image in *infile* with output filename *thumbfile*. *infile* the image file -- must be PNG or PIL readable if you have `PIL <http://www.pythonware.com/products/pil/>`_ installed *thumbfile* the thumbnail filename *scale* the scale factor for the thumbnail *interpolation* the interpolation scheme used in the resampling *preview* if True, the default backend (presumably a user interface backend) will be used which will cause a figure to be raised if :func:`~matplotlib.pyplot.show` is called. If it is False, a pure image backend will be used depending on the extension, 'png'->FigureCanvasAgg, 'pdf'->FigureCanvasPDF, 'svg'->FigureCanvasSVG See examples/misc/image_thumbnail.py. .. htmlonly:: :ref:`misc-image_thumbnail` Return value is the figure instance containing the thumbnail """ basedir, basename = os.path.split(infile) baseout, extout = os.path.splitext(thumbfile) im = imread(infile) rows, cols, depth = im.shape # this doesn't really matter, it will cancel in the end, but we # need it for the mpl API dpi = 100 height = float(rows)/dpi*scale width = float(cols)/dpi*scale extension = extout.lower() if preview: # let the UI backend do everything import matplotlib.pyplot as plt fig = plt.figure(figsize=(width, height), dpi=dpi) else: if extension=='.png': from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas elif extension=='.pdf': from matplotlib.backends.backend_pdf import FigureCanvasPDF as FigureCanvas elif extension=='.svg': from matplotlib.backends.backend_svg import FigureCanvasSVG as FigureCanvas else: raise ValueError("Can only handle extensions 'png', 'svg' or 'pdf'") from matplotlib.figure import Figure fig = Figure(figsize=(width, height), dpi=dpi) canvas = FigureCanvas(fig) ax = fig.add_axes([0,0,1,1], aspect='auto', frameon=False, xticks=[], yticks=[]) basename, ext = os.path.splitext(basename) ax.imshow(im, aspect='auto', resample=True, interpolation='bilinear') fig.savefig(thumbfile, dpi=dpi) return fig
SpaceKatt/CSPLN
apps/scaffolding/mac/web2py/web2py.app/Contents/Resources/lib/python2.7/matplotlib/image.py
Python
gpl-3.0
46,614
[ "Gaussian" ]
11cef616d3453b519809fc4a5db78d26afc0f8e33bbf229e921b61285c451e5d
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 # # MDAnalysis --- http://www.mdanalysis.org # Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) # # Released under the GNU Public Licence, v2 or any higher version # # Please cite your use of MDAnalysis in published work: # # R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler, # D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein. # MDAnalysis: A Python package for the rapid analysis of molecular dynamics # simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th # Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy. # # N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein. # MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations. # J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787 # from __future__ import absolute_import from numpy.testing import (assert_equal, assert_raises, assert_almost_equal, assert_array_equal, raises) import numpy as np import os import MDAnalysis as mda from MDAnalysisTests.datafiles import AUX_XVG, XVG_BAD_NCOL, XVG_BZ2 from MDAnalysisTests.auxiliary.base import (BaseAuxReaderTest, BaseAuxReference) class XVGReference(BaseAuxReference): def __init__(self): super(XVGReference, self).__init__() self.testdata = AUX_XVG self.reader = mda.auxiliary.XVG.XVGReader # add the auxdata and format for .xvg to the reference description self.description['auxdata'] = os.path.abspath(self.testdata) self.description['format'] = self.reader.format # for testing the selection of data/time self.time_selector = 0 # take time as first value in auxilairy self.select_time_ref = range(self.n_steps) self.data_selector = [1,2] # select the second/third columns from auxiliary self.select_data_ref = [self.format_data([2*i, 2**i]) for i in range(self.n_steps)] class TestXVGReader(BaseAuxReaderTest): def __init__(self): reference = XVGReference() super(TestXVGReader, self).__init__(reference) @raises(ValueError) def test_changing_n_col_raises_ValueError(self): # if number of columns in .xvg file is not consistent, a ValueError # should be raised self.reader = self.ref.reader(XVG_BAD_NCOL) next(self.reader) @raises(ValueError) def test_time_selector_out_of_range_raises_ValueError(self): # if time_selector is not a valid index of _data, a ValueError # should be raised self.reader.time_selector = len(self.reader.auxstep._data) @raises(ValueError) def test_data_selector_out_of_range_raises_ValueError(self): # if data_selector is not a valid index of _data, a ValueError # should be raised self.reader.data_selector = [len(self.reader.auxstep._data)] class XVGFileReference(XVGReference): def __init__(self): super(XVGFileReference, self).__init__() self.reader = mda.auxiliary.XVG.XVGFileReader self.format = "XVG-F" self.description['format'] = self.format class TestXVGFileReader(TestXVGReader): def __init__(self): reference = XVGFileReference() super(TestXVGReader, self).__init__(reference) def test_get_auxreader_for(self): # Default reader of .xvg files is intead XVGReader, not XVGFileReader # so test specifying format reader = mda.auxiliary.core.get_auxreader_for(self.ref.testdata, format=self.ref.format) assert_equal(reader, self.ref.reader) def test_reopen(self): self.reader._reopen() # should start us back at before step 0, so next takes us to step 0 self.reader.next() assert_equal(self.reader.step, 0) def test_xvg_bz2(): reader = mda.auxiliary.XVG.XVGReader(XVG_BZ2) assert_array_equal(reader.read_all_times(), np.array([0., 50., 100.])) def test_xvg_bz2(): reader = mda.auxiliary.XVG.XVGFileReader(XVG_BZ2) assert_array_equal(reader.read_all_times(), np.array([0., 50., 100.]))
kain88-de/mdanalysis
testsuite/MDAnalysisTests/auxiliary/test_xvg.py
Python
gpl-2.0
4,340
[ "MDAnalysis" ]
67d4f6f64ab81afa864482122b49c5280031f6bcfeaaa0492daee6e084323467
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Opera browser history parsers.""" import unittest from plaso.parsers import opera from tests.parsers import test_lib class OperaTypedParserTest(test_lib.ParserTestCase): """Tests for the Opera Typed History parser.""" def testParse(self): """Tests the Parse function.""" parser = opera.OperaTypedHistoryParser() storage_writer = self._ParseFile(['typed_history.xml'], parser) number_of_events = storage_writer.GetNumberOfAttributeContainers('event') self.assertEqual(number_of_events, 4) number_of_warnings = storage_writer.GetNumberOfAttributeContainers( 'extraction_warning') self.assertEqual(number_of_warnings, 0) number_of_warnings = storage_writer.GetNumberOfAttributeContainers( 'recovery_warning') self.assertEqual(number_of_warnings, 0) events = list(storage_writer.GetEvents()) expected_event_values = { 'data_type': 'opera:history:typed_entry', 'date_time': '2013-11-11 23:45:27', 'entry_selection': 'Filled from autocomplete.', 'url': 'plaso.kiddaland.net'} self.CheckEventValues(storage_writer, events[0], expected_event_values) expected_event_values = { 'data_type': 'opera:history:typed_entry', 'date_time': '2013-11-11 22:46:07', 'entry_selection': 'Manually typed.', 'url': 'theonion.com'} self.CheckEventValues(storage_writer, events[3], expected_event_values) class OperaGlobalParserTest(test_lib.ParserTestCase): """Tests for the Opera Global History parser.""" def testParseFile(self): """Read a history file and run a few tests.""" parser = opera.OperaGlobalHistoryParser() storage_writer = self._ParseFile(['global_history.dat'], parser) number_of_events = storage_writer.GetNumberOfAttributeContainers('event') self.assertEqual(number_of_events, 37) number_of_warnings = storage_writer.GetNumberOfAttributeContainers( 'extraction_warning') self.assertEqual(number_of_warnings, 0) number_of_warnings = storage_writer.GetNumberOfAttributeContainers( 'recovery_warning') self.assertEqual(number_of_warnings, 0) events = list(storage_writer.GetEvents()) expected_event_values = { 'data_type': 'opera:history:entry', 'date_time': '2013-11-11 22:45:46', 'description': 'First and Only Visit', 'title': 'Karl Bretaprins fær ellilífeyri - mbl.is', 'url': ( 'http://www.mbl.is/frettir/erlent/2013/11/11/' 'karl_bretaprins_faer_ellilifeyri/')} self.CheckEventValues(storage_writer, events[4], expected_event_values) expected_event_values = { 'data_type': 'opera:history:entry', 'date_time': '2013-11-11 22:45:55'} self.CheckEventValues(storage_writer, events[10], expected_event_values) expected_event_values = { 'data_type': 'opera:history:entry', 'date_time': '2013-11-11 22:46:16', 'title': ( '10 Celebrities You Never Knew Were Abducted And Murdered ' 'By Andie MacDowell | The Onion - America\'s Finest News Source')} self.CheckEventValues(storage_writer, events[16], expected_event_values) if __name__ == '__main__': unittest.main()
joachimmetz/plaso
tests/parsers/opera.py
Python
apache-2.0
3,302
[ "VisIt" ]
95a23f87b7ab30d36624656993be01e76b12a6956f7761dbf29197bd64518ce2
# -*- coding: utf-8 -*- """ Copyright 2013-2014 Olivier Cortès <oc@1flow.io> This file is part of the 1flow project. 1flow is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 1flow is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with 1flow. If not, see http://www.gnu.org/licenses/ """ import sys import logging import operator import feedparser from celery import task from pymongo.errors import DuplicateKeyError from mongoengine import Document, Q, CASCADE from mongoengine.fields import (StringField, BooleanField, FloatField, DateTimeField, ListField, ReferenceField, GenericReferenceField, DBRef) from mongoengine.errors import NotUniqueError, ValidationError #from cache_utils.decorators import cached from django.conf import settings from django.utils.translation import ugettext_lazy as _, pgettext_lazy from ....base.utils.dateutils import now, timedelta, naturaldelta from .common import DocumentHelperMixin # , CACHE_ONE_DAY from .folder import Folder from .subscription import Subscription, generic_check_subscriptions_method from .article import Article from .user import User from .tag import Tag LOGGER = logging.getLogger(__name__) feedparser.USER_AGENT = settings.DEFAULT_USER_AGENT __all__ = ('read_post_create_task', 'Read', ) READ_BOOKMARK_TYPE_CHOICES = ( (u'U', _(u'Undefined')), (u'A', _(u'This afternoon')), (u'W', _(u'This week-end')), ) @task(name='Read.post_create', queue='high') def read_post_create_task(read_id, *args, **kwargs): read = Read.objects.get(id=read_id) return read.post_create_task(*args, **kwargs) class Read(Document, DocumentHelperMixin): user = ReferenceField('User', reverse_delete_rule=CASCADE) article = ReferenceField('Article', unique_with='user', reverse_delete_rule=CASCADE) # HEADS UP: no `reverse_delete_rule` here, this would be too heavy and # slow. The hard work is done in `Subscription.post_delete_task()`. subscriptions = ListField(ReferenceField(Subscription)) senders = ListField(ReferenceField(User), verbose_name=_(u'Senders'), help_text=_(u'All the users that have shared the ' u'article with the current owner of ' u'this read.')) date_created = DateTimeField(default=now) is_good = BooleanField(verbose_name=_('good for use?'), help_text=_(u'The system has validated the ' u'underlying article, and the read ' u'can now be shown, used by its ' u'owner, and counted in statistics.'), default=False) is_read = BooleanField(help_text=_(u'The Owner has read the content or ' u'has manually marked it as such.'), default=False) date_read = DateTimeField() is_auto_read = BooleanField(help_text=_(u'The system has automatically ' u'marked it as read, in respect of a system ' u'rule or a user preference.'), default=False) date_auto_read = DateTimeField() is_archived = BooleanField(help_text=_(u'The Owner has archived this ' u'read to explicitely keep it accessible.'), default=False) date_archived = DateTimeField() # NOTE: is_starred has no default, because we use True # as "I like it" and False as "I don't like it". is_starred = BooleanField(help_text=_(u'The owner has starred the ' u'content, signifying he/she loves it or ' u'that it is much of interest for him/her.')) date_starred = DateTimeField() is_bookmarked = BooleanField(help_text=_(u'This content is marked to ' u'be read later. When, depends on the ' u'`.bookmark_type` attribute.'), default=False) date_bookmarked = DateTimeField() bookmark_type = StringField(max_length=1, default=u'U', choices=READ_BOOKMARK_TYPE_CHOICES) is_fact = BooleanField(help_text=_(u'Qualifies a time-dependant fact.'), default=False) date_fact = DateTimeField() is_quote = BooleanField(help_text=_(u'Qualifies someone’s words, ' u'thoughts or intentions.'), default=False) date_quote = DateTimeField() is_number = BooleanField(help_text=_(u'Qualifies explicitely quantized ' u'data.'), default=False) date_number = DateTimeField() is_analysis = BooleanField(help_text=_(u'Qualifies in-depth analysis, ' u'studies or research publications.'), default=False) date_analysis = DateTimeField() is_prospective = BooleanField(help_text=_(u'Qualifies things that want' u' to watch, that will happen or not.'), default=False) date_prospective = DateTimeField() is_knowhow = BooleanField(help_text=_(u'Qualifies anything about ' u'How-to-do things and profession ' u'best-practices.'), default=False) date_knowhow = DateTimeField() is_rules = BooleanField(help_text=_(u'Qualifies anything about laws, ' u'governments/public regulations.'), default=False) date_rules = DateTimeField() is_knowledge = BooleanField(help_text=_(u'Qualifies anything that the ' u'owner wants to retain as a “must know”, ' u'whatever the context.'), default=False) date_knowledge = DateTimeField() knowledge_type = StringField(max_length=2) is_fun = BooleanField(help_text=_(u'Qualifies anything that makes you ' u'laugh out loud.'), default=False) date_fun = DateTimeField() # TODO: convert to UserTag to use ReferenceField and reverse_delete_rule. tags = ListField(GenericReferenceField(), default=list, verbose_name=_(u'Tags'), help_text=_(u'User set of tags for this read.')) # This will be set to Article.default_rating # until the user sets it manually. rating = FloatField() # ————————————————————————————————————————————————————————— Temporary space # items here will have a limited lifetime. # At the time this is created, set_subscriptions() does the right thing. # Don't let new reads be checked more than once, the database is already # overloaded with post-processing and normal end-users related usage. check_set_subscriptions_131004_done = BooleanField(default=True) def check_set_subscriptions_131004(self): """ Fix a bug where reads had too much subscriptions. """ if isinstance(self.user, DBRef) or self.user is None: self.delete() sys.stderr.write(u'u') return if isinstance(self.article, DBRef) or self.article is None: self.delete() sys.stderr.write(u'a') return if self.subscriptions.count() == 1: # Don't bother doing CPU-intensive tasks, # this one seems good. At least we hope. self.update(set__check_set_subscriptions_131004_done=True) else: subscriptions_to_keep = [] for subscription in self.subscriptions: try: if subscription.user == self.user: subscriptions_to_keep.append(subscription) except: sys.stderr.write(u'-') # We have to update() because changing the boolean to True # doesn't make MongoEngine write it to the database, because # the new value is not different from the default one… # # Then we update subscriptions via the same mechanism to # avoid two disctinct write operations on the database. # # No need to reload, this is a one-shot repair. self.update(set__check_set_subscriptions_131004_done=True, set__subscriptions=subscriptions_to_keep) # ———————————————————————————————————————————————————————— Class attributes watch_attributes = ( 'is_fact', 'is_number', 'is_analysis', 'is_quote', 'is_prospective', 'is_rules', 'is_knowhow', 'is_knowledge', 'is_fun', ) status_data = { # # NOTE 1: "is_good" has nothing to do here, it's a system flag. # do not confuse it with read statuses. # # NOTE 2: These two are not real statuses, but having them here # allows to keep everything status-related here, without # needing to craft specific code outside of this file. # Just do something like: # # if mode == 'is_read' and negated: # mode = 'is_unread' # # And then use `mode` as usual, like any other. # 'all': { 'list_headers': (_(u'%(count)s article'), _(u'%(count)s articles')), }, 'is_unread': { 'list_headers': (_(u'%(count)s unread article'), _(u'%(count)s unread articles')), }, # ————————————————————————————————————————————————————————————————————— 'is_read': { 'list_name': pgettext_lazy(u'past participle, plural', u'read'), 'view_name': u'read', 'list_url': _(ur'^read/read/$'), 'do_title': _(u'Mark as read'), 'list_headers': (_(u'%(count)s read article'), _(u'%(count)s read articles')), 'undo_title': _(u'Mark as unread'), 'do_label': _(u'Mark read'), 'undo_label': _(u'Mark unread'), 'status_label': pgettext_lazy(u'adjective', u'read'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'check-empty'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'check'), }, 'is_starred': { 'list_name': _(u'starred'), 'view_name': u'starred', 'list_url': _(ur'^read/starred/$'), 'do_title': _(u'Star (add to favorites)'), 'list_headers': (_(u'%(count)s starred article'), _(u'%(count)s starred articles')), 'undo_title': _(u'Remove from starred/favorites'), 'do_label': pgettext_lazy(u'verb', u'Star'), 'undo_label': _(u'Unstar'), 'status_label': _(u'starred'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'star-empty'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'star'), }, 'is_archived': { 'list_name': _(u'archived'), 'view_name': u'archived', 'list_url': _(ur'^read/archived/$'), 'do_title': _(u'Archive'), 'list_headers': (_(u'%(count)s article archived'), _(u'%(count)s articles archived')), 'undo_title': _(u'Delete'), 'do_label': _(u'Archive'), 'undo_label': _(u'Delete'), 'status_label': _(u'archived'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'download'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'archive'), }, 'is_bookmarked': { 'list_name': _(u'later'), 'view_name': u'later', 'list_url': _(ur'^read/later/$'), 'do_title': _(u'Keep for reading later'), 'list_headers': (_(u'%(count)s article to read later'), _(u'%(count)s articles to read later')), 'undo_title': _(u'Remove from reading list'), 'do_label': _(u'Read later'), 'undo_label': _(u'Do not read later'), 'status_label': _(u'kept for later'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'bookmark-empty'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'bookmark'), }, 'is_fact': { 'list_name': _(u'facts'), 'view_name': u'facts', 'list_url': _(ur'^read/facts/$'), 'do_title': _(u'Mark as fact / important event'), 'list_headers': (_(u'%(count)s article containing fact(s)'), _(u'%(count)s articles containing fact(s)')), 'undo_title': _(u'Remove from facts / important events'), 'status_title': _(u'This article contains one or ' u'more important facts'), 'do_label': _(u'Mark as fact'), 'undo_label': _(u'Unmark fact'), 'status_label': _(u'fact'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'circle-blank'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'bullseye'), }, 'is_number': { 'list_name': _(u'numbers'), 'view_name': u'numbers', 'list_url': _(ur'^read/numbers/$'), 'do_title': _(u'Mark as valuable number'), 'list_headers': (_(u'%(count)s article containing number(s)'), _(u'%(count)s articles containing number(s)')), 'undo_title': _(u'Remove from valuable numbers'), 'status_title': _(u'This article contains quantified ' u'numbers for a watch.'), 'do_label': _(u'Mark as number'), 'undo_label': _(u'Unmark number'), 'status_label': _(u'number'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'bar-chart'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'bar-chart icon-flip-horizontal'), 'status_icon': pgettext_lazy(u'awesome-font icon name', u'bar-chart'), #'undo_icon_stack': True, }, 'is_analysis': { 'list_name': _(u'analysis'), 'view_name': u'analysis', 'list_url': _(ur'^read/analysis/$'), 'do_title': _(u'Mark as analysis / study / research'), 'list_headers': (pgettext_lazy(u'singular', u'%(count)s analysis'), pgettext_lazy(u'plural', u'%(count)s analysis')), 'undo_title': _(u'Unmark analysis / study / research'), 'status_title': _(u'This article contains an analysis, ' u'an in-depth study or a research ' u'publication.'), 'do_label': _(u'Mark as analysis'), 'undo_label': _(u'Unmark analysis'), 'status_label': _(u'analysis'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'beaker'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'beaker icon-rotate-90'), 'status_icon': pgettext_lazy(u'awesome-font icon name', u'beaker'), }, 'is_quote': { 'list_name': _(u'quotes'), 'view_name': u'quotes', 'list_url': _(ur'^read/quotes/$'), 'do_title': _(u'Mark as containing quote(s) from people ' u'you consider important'), 'list_headers': (_(u'%(count)s article containing quote(s)'), _(u'%(count)s articles containing quote(s)')), 'undo_title': _(u'Unmark as containing quotes ' u'(people are not famous anymore?)'), 'status_title': _(u'This article contains one or more quote ' u'from people you care about.'), 'do_label': _(u'Mark as quote'), 'undo_label': _(u'Unmark quote'), 'status_label': pgettext_lazy(u'noun', u'quote'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'quote-left icon-flip-vertical'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'quote-right'), 'status_icon': pgettext_lazy(u'awesome-font icon name', u'quote-left icon-flip-vertical'), }, 'is_prospective': { 'list_name': _(u'prospective'), 'view_name': u'prospective', 'list_url': _(ur'^read/prospective/$'), 'do_title': _(u'Mark as prospective-related content'), 'list_headers': (_(u'%(count)s prospective article'), _(u'%(count)s prospective articles')), 'undo_title': _(u'Unmark as prospective-related content'), 'status_title': _(u'This article contains prospective element(s) ' u'or must-remember hypothesis.'), 'do_label': _(u'Mark as prospective'), 'undo_label': _(u'Unmark prospective'), 'status_label': _(u'prospective'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'lightbulb'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'lightbulb icon-rotate-180'), 'status_icon': pgettext_lazy(u'awesome-font icon name', u'lightbulb'), }, 'is_rules': { 'list_name': _(u'rules'), 'view_name': u'rules', 'list_url': _(ur'^read/rules/$'), 'do_title': _(u'Mark as legal/regulations-related content'), 'list_headers': (_(u'%(count)s regulation-related article'), _(u'%(count)s regulation-related articles')), 'undo_title': _(u'Unmark as legal content (overriden laws?)'), 'status_title': _(u'This article contains regulations/' u'law/rules element(s)'), 'do_label': _(u'Mark as law/regul.'), 'undo_label': _(u'Unmark law/regul.'), 'status_label': _(u'regulations'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'legal icon-flip-horizontal'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'legal icon-rotate-180'), 'status_icon': pgettext_lazy(u'awesome-font icon name', u'legal icon-flip-horizontal'), }, 'is_knowhow': { 'list_name': _(u'best-practices'), # WARNING: there is a '_' in the view name, and a '-' in the URL. 'view_name': u'know_how', 'list_url': _(ur'^read/best-practices/$'), 'do_title': _(u'Mark as best-practices / state of art ' u'content'), 'list_headers': (_(u'%(count)s best-practices article'), _(u'%(count)s best-practices articles')), 'undo_title': _(u'Unmark as best-practices / state of art ' u'(has it become obsolete?)'), 'status_title': _(u'This article contains best-practices / ' u' state of art element(s).'), 'do_label': _(u'Mark as best-practice'), 'undo_label': _(u'Unmark best-practice'), 'status_label': pgettext_lazy(u'noun', u'know-how'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'trophy'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'trophy icon-flip-vertical'), 'status_icon': pgettext_lazy(u'awesome-font icon name', u'trophy'), }, 'is_knowledge': { 'list_name': _(u'knowlegde'), 'view_name': u'knowledge', 'list_url': _(ur'^read/knowledge/$'), 'do_title': _(u'Mark as a valuable piece of ' u'knowlegde for your brain or life'), 'list_headers': (_(u'%(count)s knowledge article'), _(u'%(count)s knowledge articles')), 'undo_title': _(u'Unmark as neuronal-exciting ' u'element(s)'), 'status_title': _(u'This article contains a valuable ' u'piece of knowlegde.'), 'do_label': _(u'Mark as Knowledge'), 'undo_label': _(u'Unmark knowlegde'), 'status_label': _(u'knowledge'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'globe'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'globe icon-rotate-180'), 'status_icon': pgettext_lazy(u'awesome-font icon name', u'globe'), }, 'is_fun': { 'list_name': _(u'funbox'), 'view_name': u'fun', 'list_url': _(ur'^read/fun/$'), 'do_title': _(u'Mark as being fun. Are you sure?'), 'list_headers': (_(u'%(count)s fun article'), _(u'%(count)s fun articles')), 'undo_title': _(u'Not fun anymore, sadly.'), 'status_title': _(u'OMG, this thing is sooooooooo fun! LMAO!'), 'do_label': _(u'Mark as fun'), 'undo_label': _(u'Mark as boring'), 'status_label': _(u'fun'), 'do_icon': pgettext_lazy(u'awesome-font icon name', u'smile'), 'undo_icon': pgettext_lazy(u'awesome-font icon name', u'frown'), 'status_icon': pgettext_lazy(u'awesome-font icon name', u'smile'), }, } meta = { 'indexes': [ 'user', ('user', 'is_good'), ('user', 'is_good', 'is_read'), ('user', 'is_good', 'is_starred'), ('user', 'is_good', 'is_bookmarked'), 'article', ('article', 'is_good'), ] } # ——————————————————————————————————————————————————————————— Class methods @classmethod def get_status_attributes(cls): try: return cls._status_attributes_cache except AttributeError: # cls._status_attributes_cache = [fname for fname, field # in cls._fields.items() # if fname.startswith('is_') # and isinstance(field, # BooleanField)] cls._status_attributes_cache = [ k for k in cls.status_data.keys() if 'list_url' in cls.status_data[k] ] return cls._status_attributes_cache # ———————————————————————————————————— Class methods & Mongo/Django related @classmethod def signal_post_save_handler(cls, sender, document, created=False, **kwargs): read = document if created: if read._db_name != settings.MONGODB_NAME_ARCHIVE: read_post_create_task.delay(read.id) def post_create_task(self): """ Method meant to be run from a celery task. """ self.rating = self.article.default_rating self.set_subscriptions(commit=False) self.save() self.update_cached_descriptors() @classmethod def signal_pre_delete_handler(cls, sender, document, **kwargs): read = document if not read.is_good: # counters already don't take this read into account. return read.update_cached_descriptors(operation='-') def validate(self, *args, **kwargs): try: super(Read, self).validate(*args, **kwargs) except ValidationError as e: tags_error = e.errors.get('tags', None) if tags_error and 'GenericReferences can only contain documents' \ in str(tags_error): good_tags = set() to_replace = set() for tag in self.tags: if isinstance(tag, Document): good_tags.add(tag) else: to_replace.add(tag) new_tags = Tag.get_tags_set([t for t in to_replace if t not in (u'', None)]) self.tags = good_tags | new_tags e.errors.pop('tags') if e.errors: raise e def __unicode__(self): return _(u'{0}∞{1} (#{2}∞#{3}→#{4}) {5} @{6}').format( self.user.username, self.article.title[:40] + (self.article.title[40:] and u'…'), self.user.id, self.article.id, self.id, pgettext_lazy(u'adjective', u'read') if self.is_read else pgettext_lazy(u'adjective', u'unread'), self.rating) # —————————————————————————————————————————————————————————————— Properties @property def is_restricted(self): if (self.user.is_staff_or_superuser_and_enabled and self.user.preferences.staff.allow_all_articles): return False if self.is_archived: return False return any(map(lambda sub: sub.feed.restricted, self.subscriptions)) # TODO: refresh/implement this to avoid fetching content from the # database if the remote article is not available anymore. # NOTE: This is clearly overkill in the libre version, as 1flow # is just a personnal RSS / web crawler tool. This makes # sense for legal issues only if 1flow.io is a paid service. # # delta_from_now = timedelda(now() - self.date_published) # if self.is_read: # if self.is_archived: # if self.is_auto_read: # if self.article.feed.restrict_read_delta \ # and delta_from_now > self.article.feed.restrict_read_delta: # return True # and delta_from_now <= config.ARTICLE_LIMITS_READ @property def title(self): article = self.article feed = article.feed if feed: source = _(u' ({feed})').format(feed=feed.name) else: source = u'' return _(u'{title}{source}').format(title=article.title, source=source) @property def get_source(self): if self.article.source: return self.article.source if self.subscriptions: # This method displays things to the user. Don't let dead # DBRefs pass through. # # TODO: let things pass through for administrators, though. # return [s for s in self.subscriptions if isinstance(s, Document)] return self.article.get_source @property def get_source_unicode(self): source = self.get_source if source.__class__ in (unicode, str): return source sources_count = len(source) if sources_count > 2: return _(u'Multiple sources ({0} feeds)').format(sources_count) return u' / '.join(x.name for x in source) @property def reading_time(self): """ Return a rounded value of the approximate reading time, for the user and the article. """ wc = self.article.word_count_TRANSIENT if wc is None: return None return wc / self.user.preferences.read.reading_speed @property def reading_time_display(self): rtm = self.reading_time if rtm is None: return u'' if rtm == 0: return _(u'a quick read') return _(u'{0} read').format(naturaldelta(timedelta(seconds=rtm * 60))) @property def reading_time_abstracted(self): rtm = self.reading_time if rtm is None: return u'' inum = 1 icon = u'∎' # u'<i class="icon-time"></i>' tmpl = _(u'<span class="popover-top" data-toggle="tooltip" ' u'title="Reading time: {0}">{1}</span>') time = naturaldelta(timedelta(seconds=rtm * 60)) if rtm > 8: inum = 4 elif rtm > 3: inum = 3 elif rtm > 1: inum = 2 elif rtm == 0: # HEADS UP: patch/hack; non-breakable spaces everywhere. time = _(u'very quick (<1 min)') return tmpl.format(time, inum * icon) # ————————————————————————————————————————————————————————————————— Methods # HEADS UP: this method come from the subscription module. check_subscriptions = generic_check_subscriptions_method def set_subscriptions(self, commit=True): # @all_subscriptions, because here internal feeds count. user_feeds = [sub.feed for sub in self.user.all_subscriptions] article_feeds = [feed for feed in self.article.feeds if feed in user_feeds] # HEADS UP: searching only for feed__in=article_feeds will lead # to have other user's subscriptions attached to the read. # Harmless but very confusing. self.subscriptions = list(Subscription.objects( feed__in=article_feeds, user=self.user)) if commit: self.save() # TODO: only for the new subscriptions. #self.update_cached_descriptors( … ) return self.subscriptions def activate(self, force=False): """ This method will mark the Read ``.is_good=True`` and do whatever in consequence. """ if not force and not self.article.is_good: LOGGER.error(u'Cannot activate read %s, whose article ' u'is not ready for public use!', self) return self.is_good = True self.save() update_only = ['all'] if self.is_starred: update_only.append('starred') if self.is_bookmarked: update_only.append('bookmarked') if not self.is_read: update_only.append('unread') self.update_cached_descriptors(update_only=update_only) def remove_tags(self, tags=[]): """ If the user remove his own tags from a Read, it will get back the default tags from the article it comes from. """ if tags: for tag in Tag.get_tags_set(tags, origin=self): self.update(pull__tags=tag) self.safe_reload() if self.tags == []: self.tags = self.article.tags.copy() self.save() # NO update_cached_descriptors() here. def add_tags(self, tags): for tag in Tag.get_tags_set(tags, origin=self): self.update(add_to_set__tags=tag) self.safe_reload() # NO update_cached_descriptors() here. # ————————————————————————————————————————————— Update subscriptions caches def update_cached_descriptors(self, operation=None, update_only=None): if operation is None: operation = '+' assert operation in ('+', '-') if operation == '+': op = operator.add else: op = operator.sub if update_only is None: to_change = ['all_articles_count'] if self.is_archived: to_change.append('archived_articles_count') if self.is_bookmarked: to_change.append('bookmarked_articles_count') if self.is_starred: to_change.append('starred_articles_count') if not self.is_read: to_change.append('unread_articles_count') for watch_attr_name in Read.watch_attributes: if getattr(self, watch_attr_name): # Strip 'is_' from the attribute name. to_change.append(watch_attr_name[3:] + '_articles_count') else: assert type(update_only) in (type(tuple()), type([])) to_change = [only + '_articles_count' for only in update_only] for attr_name in to_change: try: updated_folders = [] for subscription in self.subscriptions: setattr(subscription, attr_name, op(getattr(subscription, attr_name), 1)) for folder in subscription.folders: if folder in updated_folders: continue setattr(folder, attr_name, op(getattr(folder, attr_name), 1)) updated_folders.append(folder) setattr(self.user, attr_name, op(getattr(self.user, attr_name), 1)) except AttributeError, e: LOGGER.warning(u'Skipped cache descriptor update for %s ' u'from %s: %s', attr_name, self, e) def is_read_changed(self): self.update_cached_descriptors(operation='-' if self.is_read else '+', update_only=['unread']) def is_starred_changed(self): self.update_cached_descriptors(operation='+' if self.is_starred else '-', update_only=['starred']) def mark_archived(self): if self.is_archived_can_change() and not self.is_archived: self.is_archived = True self.save() def is_archived_can_change(self): if self.is_archived: # A user can always unarchive anything. This is dangerous because # he can permanently loose data, but the UI asks for a confirmation # in that case. return True return True if self.is_restricted: LOGGER.warning(u'Implement real-time checking ' u'of archive-ability permission.') return True else: # An unrestricted read/feed can always change status. return True def is_archived_changed(self): self.update_cached_descriptors(operation='+' if self.is_archived else '-', update_only=['archived']) def is_bookmarked_changed(self): self.update_cached_descriptors(operation='+' if self.is_bookmarked else '-', update_only=['bookmarked']) # ————————————————————————————————————————————————————————— external properties # Defined here to avoid import loops def Folder_reads_property_get(self): # The owner has already filtered good reads via an indexed search. # # self.subscriptions is a QuerySet, we need # to convert it to a list for the new QuerySet. return self.owner.reads(subscriptions__in=[s for s in self.subscriptions]) def Subscription_reads_property_get(self): # The user has already filtered good reads via an indexed search. return self.user.reads(subscriptions__contains=self) def Article_reads_property_get(self): # Do NOT filter on is_good here. The Article needs to # know about ALL reads, to activate them when ready. return Read.objects.filter(article=self) def Article_good_reads_property_get(self): # Do NOT filter on is_good here. The Article needs to # know about ALL reads, to activate them when ready. return self.reads(is_good=True) def Article_bad_reads_property_get(self): # Do NOT filter on is_good here. The Article needs to # know about ALL reads, to activate them when ready. return self.reads(Q(is_good__exists=False) | Q(is_good=False)) def User_reads_property_get(self): return Read.objects.filter(user=self, is_good=True) Folder.reads = property(Folder_reads_property_get) Subscription.reads = property(Subscription_reads_property_get) Article.reads = property(Article_reads_property_get) Article.good_reads = property(Article_good_reads_property_get) Article.bad_reads = property(Article_bad_reads_property_get) User.reads = property(User_reads_property_get) # —————————————————————————————————————————————————————— external bound methods # Defined here to avoid import loops def Subscription_create_read_method(self, article, verbose=True, **kwargs): """ Returns a tuple (read, created) with the new (or existing) read, and ``created`` as a boolean indicating if it was actually created or if it existed before. """ new_read = Read(article=article, user=self.user) try: new_read.save() except (NotUniqueError, DuplicateKeyError): if verbose: LOGGER.info(u'Duplicate read %s!', new_read) cur_read = Read.objects.get(article=article, user=self.user) # If another feed has already created the read, be sure the # current one is registered in the read via the subscriptions. cur_read.update(add_to_set__subscriptions=self) # # NOTE: we do not check `is_good` here, when the read was not # created. This is handled (indirectly) via the article # check part of Subscription.check_reads(). DRY. # return cur_read, False except: # We must not fail here, because often this method is called in # a loop 'for subscription in ….subscriptions:'. All other read # creations need to succeed. LOGGER.exception(u'Could not save read %s!', new_read) else: # XXX: todo remove this 'is not None', when database is clean… tags = [t for t in article.tags if t is not None] params = dict(('set__' + key, value) for key, value in kwargs.items()) # If the article was already there and fetched (mutualized from # another feed, for example), activate the read immediately. # If we don't do this here, the only alternative is the daily # global_reads_checker() task, which is not acceptable for # "just-added" subscriptions, whose reads are created via the # current method. if article.is_good: params['set__is_good'] = True new_read.update(set__tags=tags, set__subscriptions=[self], **params) # Update cached descriptors self.all_articles_count += 1 self.unread_articles_count += 1 return new_read, True Subscription.create_read = Subscription_create_read_method
EliotBerriot/1flow
oneflow/core/models/nonrel/read.py
Python
agpl-3.0
42,501
[ "exciting" ]
28d232ea215633d0a209b89dd69a41dc9813d5812bf38aab370035fff468337d
# stdlib imports from functools import reduce import collections import datetime import json import operator import time import urllib.parse # django imports from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import UserPassesTestMixin from django.db import transaction from django.db.models import Q, Count, Max, Min from django.forms import HiddenInput from django.http import HttpResponse from django.http import HttpResponseForbidden from django.http import JsonResponse from django.http.response import Http404 from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.shortcuts import render from django.urls import reverse from django.utils import timezone from django.utils.decorators import method_decorator from django.utils.text import slugify from django.utils.text import smart_split from django.views import View from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_exempt # third-party imports from django_countries import countries from haystack.inputs import AutoQuery from haystack.query import SearchQuerySet from lxml import etree import jwt import pytz # project imports from dbdb.core.forms import CreateUserForm, SystemForm, SystemVersionForm, SystemVersionMetadataForm, SystemFeaturesForm, \ SystemVersionEditForm from dbdb.core.models import CitationUrl from dbdb.core.models import Feature from dbdb.core.models import FeatureOption from dbdb.core.models import License from dbdb.core.models import OperatingSystem from dbdb.core.models import ProgrammingLanguage from dbdb.core.models import ProjectType from dbdb.core.models import System from dbdb.core.models import SystemFeature from dbdb.core.models import SystemRedirect from dbdb.core.models import SystemVersion from dbdb.core.models import SystemVersionMetadata from dbdb.core.models import SystemACL from dbdb.core.models import SystemVisit from dbdb.core.models import SystemRecommendation UserModel = get_user_model() # constants FILTERGROUP_VISIBLE_LENGTH = 3 SITEMPA_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9' SITEMAP_PREFIX = '{%s}' % SITEMPA_NS SITEMAP_NSMAP = { None : SITEMPA_NS } # helper classes FieldSet = collections.namedtuple('FieldSet', ['id','label','choices','description','citation']) LetterPage = collections.namedtuple('LetterPage', ['id','letter','is_active','is_disabled']) Stat = collections.namedtuple('Stat', ['label','items', 'search_field', 'systems', 'count']) StatItem = collections.namedtuple('StatItem', ['label','value','slug']) class FilterChoice( collections.namedtuple('FilterChoice', ['id','label','checked']) ): is_hidden = False @property def sort_key(self): return ( 0 if self.checked else 1, self.label, ) pass class FilterGroup( collections.namedtuple('FieldSet', ['id','label','choices']) ): has_checked = False has_more = False def prepare(self): #self.choices.sort(key=lambda fc: fc.sort_key) for i,choice in enumerate(self.choices): self.has_checked = self.has_checked or choice.checked if i >= FILTERGROUP_VISIBLE_LENGTH and not choice.checked: choice.is_hidden = True self.has_more = True pass pass return pass class SearchTag: __slots__ = ['query','group_slug','group_name', 'tag_slug', 'tag_name'] def __init__(self, query, group_slug, group_name, tag_slug, tag_name): self.query = query self.group_slug = group_slug self.group_name = group_name self.tag_slug = tag_slug self.tag_name = tag_name return def __repr__(self): return repr( tuple( map(str, (self.group_slug, self.group_name, self.tag_slug, self.tag_name)) ) ) def get_removal_url(self): query = [] for key,values in self.query.lists(): for value in values: if key == self.group_slug and value == self.tag_slug: continue query.append((key, value)) return '?' + urllib.parse.urlencode(query, doseq=False) pass # helper functions def staff_check(user): return user.is_staff def super_user_check(user): return user.is_superuser # class based views # ============================================== # EmptyFieldsView # ============================================== class EmptyFieldsView(View): template_name = 'core/empty-fields.html' def build_search_fields(include_citations=False): import django.db.models.fields IGNORE_TYPES = set([ django.db.models.fields.AutoField, django.db.models.fields.related.ForeignKey, #django.db.models.fields.related.ManyToManyField, ]) IGNORE_NAMES = set([ "ver", "comment", "features", "created", ]) version_fields = [ ] for f in SystemVersion._meta.get_fields(): if f.name.endswith("_citations") and not include_citations: continue if not type(f) in IGNORE_TYPES and \ not f.name in IGNORE_NAMES: version_fields.append(f.name) ## FOR meta_fields = [ ] for f in SystemVersionMetadata._meta.get_fields(): if not type(f) in IGNORE_TYPES and \ not f.name in IGNORE_NAMES: meta_fields.append(f.name) return (version_fields, meta_fields) ## DEF def get(self, request): import django.db.models.fields if not request.user.is_authenticated: return redirect( settings.LOGIN_URL + '?next=' + reverse('fields') ) elif not request.user.is_superuser: raise Http404() version_fields, meta_fields = EmptyFieldsView.build_search_fields() versions = SystemVersion.objects.filter(is_current=True) search_field = request.GET.get('field') search_reverse = request.GET.get('reverse', False) if search_field: query = None field = None if search_field in version_fields: field = SystemVersion._meta.get_field(search_field) field_name = search_field if type(field) == django.db.models.fields.PositiveIntegerField: query = Q(**{search_field: None}) else: query = Q(**{search_field: ''}) elif search_field in meta_fields: field = SystemVersionMetadata._meta.get_field(search_field) field_name = "meta__" + search_field if type(field) in (django.db.models.fields.PositiveIntegerField, django.db.models.fields.related.ManyToManyField): query = Q(**{field_name: None}) else: query = Q(**{field_name: ''}) else: raise Exception("Invalid field '%s'" % search_field) if search_reverse: versions = versions.filter(~query) else: versions = versions.filter(query) # convert query list to regular list # and add href/url to each versions = list( versions.order_by('system__name') ) for version in versions: version.href = request.build_absolute_uri( version.system.get_absolute_url() ) if search_field in meta_fields: if type(field) == django.db.models.fields.related.ManyToManyField: method_handle = getattr(version.meta, search_field + "_str") version.value = method_handle() else: version.value = getattr(version.meta, search_field, "XXX") else: version.value = getattr(version, field_name, None) pass ## IF num_systems = System.objects.all().count() fields = sorted(version_fields + meta_fields) return render(request, self.template_name, { 'activate': 'empty', # NAV-LINKS 'versions': versions, 'field': search_field, 'reverse': search_reverse, 'fields': fields, 'match_percent': "%.1f" % (100 * (len(versions) / num_systems)), 'num_systems': num_systems, }) pass ## CLASS # ============================================== # DatabaseBrowseView # ============================================== class DatabaseBrowseView(View): template_name = 'core/database-browse.html' def build_filter_group_for_field(self, field, search_field, label, all_systems, querydict): empty_set = set() values = SystemVersionMetadata.objects \ .filter(systemversion__is_current=True) \ .filter(~Q(**{field: None})) \ .values_list(field) #.distinct() \ #.order_by() fg = FilterGroup(search_field, label, sorted([ FilterChoice( all_systems[v[0]].slug, all_systems[v[0]].name, all_systems[v[0]].slug in querydict.getlist(search_field, empty_set) ) for v in set(values) #for sys in System.objects.values_list('id','slug','name', named=True) ], key=lambda x: x[1])) return fg def build_filter_groups(self, querydict): empty_set = set() def reduce_feature_options(mapping, option): mapping[option.feature_id].choices.append( FilterChoice( option.slug, option.value, option.slug in querydict.getlist( option.feature__slug, empty_set ) ) ) return mapping other_filtersgroups = [] # Countries def reduce_countries(mapping, item): countries = item.countries.split(',') for c in countries: if c: mapping[c] = mapping.get(c, 0) + 1 return mapping system_countries = SystemVersion.objects \ .filter(is_current=True) \ .values_list('countries', named=True) system_countries = reduce(reduce_countries, system_countries, {}) countries_map = dict(countries) fg_country = FilterGroup('country', 'Country', sorted([ FilterChoice( code, countries_map[code], # name, code in querydict.getlist( 'country', empty_set ) ) for code in system_countries.keys() ], key=lambda x: x[1])) other_filtersgroups.append(fg_country) all_systems = dict([ (sys.id, sys) for sys in System.objects.values_list('id','slug','name', named=True) ]) # Compatible other_filtersgroups.append(self.build_filter_group_for_field(\ 'compatible_with', \ 'compatible', \ 'Compatible With', \ all_systems, \ querydict )) # Embedded other_filtersgroups.append(self.build_filter_group_for_field(\ 'embedded', \ 'embeds', \ 'Embeds / Uses', \ all_systems, \ querydict )) # Derived other_filtersgroups.append(self.build_filter_group_for_field(\ 'derived_from', \ 'derived', \ 'Derived From', \ all_systems, \ querydict )) # Inspired other_filtersgroups.append(self.build_filter_group_for_field(\ 'inspired_by', \ 'inspired', \ 'Inspired By', \ all_systems, \ querydict )) # add operating system fg_os = FilterGroup('os', 'Operating System', [ FilterChoice( os.slug, os.name, os.slug in querydict.getlist( 'os', empty_set ) ) for os in OperatingSystem.objects.values_list('id','slug','name', named=True) ]) other_filtersgroups.append(fg_os) # add programming languages fg_programming = FilterGroup('programming', 'Programming Languages', [ FilterChoice( p.slug, p.name, p.slug in querydict.getlist( 'programming', empty_set ) ) for p in ProgrammingLanguage.objects.values_list('id','slug','name', named=True) ]) other_filtersgroups.append(fg_programming) # add project types fg_project_type = FilterGroup('type', 'Project Types', [ FilterChoice( pt.slug, pt.name, pt.slug in querydict.getlist( 'type', empty_set ) ) for pt in ProjectType.objects.values_list('id','slug','name', named=True) ]) other_filtersgroups.append(fg_project_type) # add licenses fg_license = FilterGroup('license', 'Licenses', [ FilterChoice( l.slug, l.name, l.slug in querydict.getlist( 'license', empty_set ) ) for l in License.objects.values_list('id','slug','name', named=True) ]) other_filtersgroups.append(fg_license) # build from list of features (alphabetical order) filtergroups = collections.OrderedDict( ( f_id, FilterGroup(f_slug, f_label, []), ) for f_id,f_slug,f_label in Feature.objects.all().order_by('label').values_list('id','slug','label') ) # add feature options to features filtergroups = reduce( reduce_feature_options, FeatureOption.objects.all().order_by('value').values_list('feature_id','feature__slug','id','slug','value', named=True), filtergroups ) filtergroups = other_filtersgroups + list( filtergroups.values() ) for fg in filtergroups: fg.prepare() pass return filtergroups def build_pagination(self, letter): letters_alphabet = set( chr(i) for i in range( ord('A') , ord('Z')+1 ) ) letters_available = set( name.upper()[0] for name in System.objects.all().values_list('name', flat=True) ) letters_missing = letters_alphabet.difference( letters_available ) letters_all = letters_alphabet.union( letters_available ) pagination = list( LetterPage( l, l, l == letter, l not in letters_available ) for l in sorted(letters_all) ) pagination.append( LetterPage( 'ALL', 'All', 'ALL' == letter, False ) ) return pagination def slug_to_system(self, slugs): slugs = { s.strip() for s in slugs } systems = System.objects.filter(slug__in=slugs) return { s.slug : s for s in systems } ## DEF def do_search(self, request): has_search = False countries_map = dict(countries) # map feature slugs to ids features_map = { f_slug : f_id for f_id,f_slug in Feature.objects.all().order_by().values_list('id','slug') } # map feature options slugs to ids featuresoptions_map = { (f_id,fo_slug) : fo_id for f_id,fo_id,fo_slug in FeatureOption.objects.all().order_by().values_list('feature_id','id','slug') } # pull search criteria search_q = request.GET.get('q', '').strip() search_fg = { features_map[k] : set( request.GET.getlist(k) ) for k in request.GET.keys() if k in features_map } # define date filters search_start_min = request.GET.get('start-min', '').strip() search_start_max = request.GET.get('start-max', '').strip() search_end_min = request.GET.get('end-min', '').strip() search_end_max = request.GET.get('end-max', '').strip() # define static filters search_compatible = request.GET.getlist('compatible') search_country = request.GET.getlist('country') search_derived = request.GET.getlist('derived') search_embeds = request.GET.getlist('embeds') search_inspired = request.GET.getlist('inspired') search_os = request.GET.getlist('os') search_programming = request.GET.getlist('programming') search_supported = request.GET.getlist('supported') search_type = request.GET.getlist('type') search_license = request.GET.getlist('license') search_suffix = request.GET.getlist('suffix') # collect filters search_mapping = { 'query': search_q, 'start_min': search_start_min, 'start_max': search_start_max, 'end_min': search_end_min, 'end_max': search_end_max, 'compatible': search_compatible, 'country': search_country, 'derived': search_derived, 'embeds': search_embeds, 'inspired': search_inspired, 'os': search_os, 'programming': search_programming, 'supported': search_supported, 'type': search_type, 'license': search_license, 'suffix': search_suffix, } if not any(search_mapping.values()) and not any(search_fg): return (None, { }, []) search_tags = [] # create new search query sqs = SearchQuerySet() # apply keyword search to name (require all terms) if search_q: sqs = sqs.filter(content=AutoQuery(search_q)) # apply year limits if all((search_start_min, search_start_max)): search_start_min = int(search_start_min) search_start_max = int(search_start_max) sqs = sqs.filter(start_year__gte=search_start_min, start_year__lte=search_start_max) pass if all((search_end_min, search_end_max)): search_end_min = int(search_end_min) search_end_max = int(search_end_max) sqs = sqs.filter(end_year__gte=search_end_min, end_year__lte=search_end_max) pass # search - compatible if search_compatible: sqs = sqs.filter(compatible_with__in=search_compatible) systems = self.slug_to_system(search_compatible) search_mapping['compatible'] = systems.values() search_tags.extend( SearchTag(request.GET, 'compatible', 'Compatible With', k, v) for k,v in systems.items() ) pass # search - country if search_country: sqs = sqs.filter(countries__in=search_country) search_tags.extend( SearchTag(request.GET, 'country', 'Country', c, countries_map[c]) for c in search_country ) pass # search - derived from if search_derived: sqs = sqs.filter(derived_from__in=search_derived) systems = self.slug_to_system(search_derived) search_mapping['derived'] = systems.values() search_tags.extend( SearchTag(request.GET, 'derived', 'Derived From', k, v) for k,v in systems.items() ) pass # search - embedded if search_embeds: sqs = sqs.filter(embedded__in=search_embeds) systems = self.slug_to_system(search_embeds) search_mapping['embeds'] = systems.values() search_tags.extend( SearchTag(request.GET, 'embeds', 'Embeds / Uses', k, v) for k,v in systems.items() ) pass # search - inspired by if search_inspired: sqs = sqs.filter(inspired_by__in=search_inspired) systems = self.slug_to_system(search_inspired) search_mapping['inspired'] = systems.values() search_tags.extend( SearchTag(request.GET, 'inspired', 'Inspired By', k, v) for k,v in systems.items() ) pass # search - operating systems if search_os: sqs = sqs.filter(oses__in=search_os) oses = OperatingSystem.objects.filter(slug__in=search_os) search_tags.extend( SearchTag(request.GET, 'os', 'Operating System', os.slug, os.name) for os in oses ) pass # search - programming languages if search_programming: sqs = sqs.filter(written_langs__in=search_programming) langs = ProgrammingLanguage.objects.filter(slug__in=search_programming) search_tags.extend( SearchTag(request.GET, 'programming', 'Programming Languages', lang.slug, lang.name) for lang in langs ) pass # search - supported languages if search_supported: sqs = sqs.filter(supported_langs__in=search_supported) langs = ProgrammingLanguage.objects.filter(slug__in=search_supported) search_tags.extend( SearchTag(request.GET, 'supported', 'Supported Languages', lang.slug, lang.name) for lang in langs ) pass # search - project types if search_type: sqs = sqs.filter(project_types__in=search_type) types = ProjectType.objects.filter(slug__in=search_type) search_tags.extend( SearchTag(request.GET, 'type', 'Project Types', type.slug, type.name) for type in types ) pass # search - licenses if search_license: sqs = sqs.filter(licenses__in=search_license) licenses = License.objects.filter(slug__in=search_license) search_tags.extend( SearchTag(request.GET, 'license', 'Licenses', license.slug, license.name) for license in licenses ) pass # search - suffixes if search_suffix: for suffix in search_suffix: sqs = sqs.filter(lowercase_name__contains=suffix) search_tags.extend(SearchTag(request.GET, 'suffix', 'Suffix', suffix, suffix) for suffix in search_suffix) pass # convert feature option slugs to IDs to do search by filtering filter_option_ids = set() for feature_id,option_slugs in search_fg.items(): option_ids = set( map(lambda option_slug: featuresoptions_map[(feature_id,option_slug)], option_slugs) ) filter_option_ids.update(option_ids) pass # if there are filter options to search for, apply filter if filter_option_ids: for option_id in filter_option_ids: sqs = sqs.filter(feature_options__contains=option_id) search_tags.extend( SearchTag(request.GET, *row) for row in FeatureOption.objects.filter(id__in=filter_option_ids).values_list('feature__slug','feature__label','slug','value') ) return (sqs, search_mapping, search_tags) def handle_old_urls(self, request): query = [] # get mapping of feature options featuresoptions_map = { str(fo_id): (f_slug, fo_slug) for fo_id,fo_slug,f_slug in FeatureOption.objects.all().order_by().values_list('id','slug','feature__slug') } for k in request.GET.keys(): for v in request.GET.getlist(k): if k.startswith('fg'): query.append( featuresoptions_map[v] ) pass elif v: query.append((k,v)) pass pass pass return redirect( request.path + '?' + urllib.parse.urlencode(query) ) def get(self, request): # handle older filter group urls if any( filter(lambda k: k.startswith('fg'), request.GET.keys()) ): return self.handle_old_urls(request) # Perform the search and get back the versions along with a # mapping with the search keys results, search_keys, search_tags = self.do_search(request) search_q = request.GET.get('q', '').strip() # Search Letter search_letter = request.GET.get('letter', '').strip().upper() if results is not None: pass elif search_letter == 'ALL' or not search_letter: results = SearchQuerySet() search_letter = 'ALL' pass elif search_letter: results = SearchQuerySet().filter(letter__exact=search_letter.lower()).filter(name__startswith=search_letter) pass # generate letter pagination pagination = self.build_pagination(search_letter) # convert query list to regular list results = list( results.order_by('name') ) # check if there are results has_results = len(results) > 0 # get year ranges years_start = SystemVersion.objects.filter(is_current=True).filter(start_year__gt=0).aggregate( min_start_year=Min('start_year'), max_start_year=Max('start_year') ) years_end = SystemVersion.objects.filter(is_current=True).filter(end_year__gt=0).aggregate( min_end_year=Min('end_year'), max_end_year=Max('end_year') ) years = {} years.update(years_start) years.update(years_end) return render(request, self.template_name, { 'activate': 'browse', # NAV-LINKS 'filtergroups': self.build_filter_groups(request.GET), 'has_results': has_results, 'pagination': pagination, 'query': search_q, 'results': results, 'years': years, 'has_search': len(search_keys) != 0, 'search': search_keys, 'tags': search_tags, }) pass # ============================================== # CounterView # ============================================== @method_decorator(csrf_exempt, name='dispatch') class CounterView(View): @staticmethod def build_token(origin, **kwargs): payload = dict(kwargs) payload.update( { #'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=15), # +15 seconds ## disabled expatriation to allow caching 'iss': 'counter:{}'.format(origin), 'nbf': datetime.datetime.utcnow(), }) s = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256') s = s.decode('utf-8') return s def post(self, request): token = request.POST.get('token') if not token: return JsonResponse({ 'status':'missing token'}, status=400) try: payload = jwt.decode( token.encode('utf-8'), settings.SECRET_KEY, algorithms=['HS256'] ) iss = payload.get('iss') if iss == 'counter:system': pk = payload['pk'] # Skip bots user_agent = request.META.get('HTTP_USER_AGENT', '') if user_agent.lower().find("bot") != -1: return JsonResponse({ 'status':'bot' }) # And add a SystemVisit entry x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') # save visit system_visit = SystemVisit.objects.create( system_id=pk, ip_address=ip, user_agent=user_agent[:127] ) pass else: return JsonResponse({ 'status':('unrecognized counter: %r' % iss) }, status=400) pass except jwt.ExpiredSignatureError: return JsonResponse({ 'status':'expired counter' }, status=400) return JsonResponse({ 'status':'ok' }) pass # ============================================== # CreateUserView # ============================================== class CreateUserView(View): TOKEN_QUERY_NAME = 'token' template_name = 'registration/create_user.html' def decode_token(self, request): token = request.GET.get(CreateUserView.TOKEN_QUERY_NAME) if not token: return None try: payload = jwt.decode( token.encode('utf-8'), settings.SECRET_KEY, algorithms=['HS256'], verify=True ) pass except jwt.exceptions.ExpiredSignatureError: payload = False except: payload = None return payload def get(self, request, *args, **kwargs): expired_token = False initial = { } reg_info = self.decode_token(request) if reg_info == False: expired_token = True pass elif reg_info and 'sub' in reg_info: initial['email'] = reg_info['sub'] form = CreateUserForm(auto_id='%s', initial=initial) return render(request, self.template_name, { 'title': 'User Registration', 'expired_token': expired_token, 'form': form, 'recaptcha_key': getattr(settings, 'NORECAPTCHA_SITE_KEY'), }) def post(self, request, *args, **kwargs): expired_token = False initial = { } # check for a registration info reg_info = self.decode_token(request) # if the registration expired `False` then return to login page if reg_info == False: return redirect(settings.LOGIN_URL + '?status=failed') pass # if the registration included a subject, use as email address elif reg_info and 'sub' in reg_info: initial['email'] = reg_info['sub'] pass # create form class (it handles enforcing initial email) form = CreateUserForm(request.POST, auto_id='%s', initial=initial) if form.is_valid(): with transaction.atomic(): # create user with provided info user = UserModel.objects.create_user( username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password'] ) # associate the user with various systems if specified in registration info if reg_info and 'systems' in reg_info: system_ids = list( map(int, reg_info['systems']) ) # NOTE: if registration contained no longer valid system IDs, this will error out SystemACL.objects.bulk_create([ SystemACL( system_id=system_id, user_id=user.id ) for system_id in system_ids ]) pass pass # end successfully with a redirect to login page return redirect(settings.LOGIN_URL + '?status=success') return render(request, self.template_name, { 'form': form, 'recaptcha_key': getattr(settings, 'NORECAPTCHA_SITE_KEY'), }) pass # ============================================== # DatabasesEditView # ============================================== class DatabasesEditView(LoginRequiredMixin, View): template_name = 'core/databases-edit.html' def build_features(self, feature_form): features = Feature.objects.all() features = collections.OrderedDict( ( f.id, { 'id': 'feature_{}'.format(f.id), 'label': f.label, 'choices': None, 'description': None, 'citation': None, } ) for f in features ) for bf in feature_form: name = bf.name.split('_')[-1] feature_id = bf.field.feature_id features[feature_id][name] = bf pass return features @never_cache def get(self, request, slug=None): # If there is no slug, then they are trying to create a new database. # Only superusers are allowed to do that. if slug is None: if not request.user.is_superuser: raise Http404() # Create a new empty system for the form system = System() system_version = SystemVersion(system=system, is_current=True) system_meta = SystemVersionMetadata() system_features = SystemFeature.objects.none() pass # If there is a slug, then check to see whether they have permission # to edit this mofo else: # You always have to be logged in to edit an entry if not request.user.is_authenticated: return redirect( settings.LOGIN_URL + '?next=' + reverse('system', args=[slug])) system = System.objects.get(slug=slug) # Make sure this user has permissions to edit this page if not request.user.is_superuser: try: system_acl = SystemACL.objects.get(system=system, user=request.user) except SystemACL.DoesNotExist: base_url = reverse('system', args=[slug]) query_string = urllib.parse.urlencode({'noperms': 1}) url = '{}?{}'.format(base_url, query_string) return redirect(url) ## IF # Load in what we need system_version = SystemVersion.objects.get(system=system, is_current=True) system_meta = system_version.meta system_features = system_version.features.all() pass system_form = SystemForm(instance=system) # Don't allow non-superusers from editting the system name # This only really hides it from the UI. if request.user.is_superuser: system_form.fields['orig_name'].widget = HiddenInput() else: system_form.fields['name'].widget = HiddenInput() system_form.fields['orig_name'].initial = system.name feature_form = SystemFeaturesForm(features=system_features) features = self.build_features(feature_form) return render(request, self.template_name, { 'activate': 'create' if system.id is None else 'edit', # NAV-LINKS 'system_name': system.name, 'system_form': system_form, 'system_version_form': SystemVersionForm(instance=system_version), 'system_version_metadata_form': SystemVersionMetadataForm(instance=system_meta), 'feature_form': feature_form, 'features': features, }) @transaction.atomic def post(self, request, slug=None): if slug is None: if not request.user.is_superuser: raise Http404() system = System() system_version = SystemVersion(system=system, is_current=True) system_meta = SystemVersionMetadata() system_features = SystemFeature.objects.none() pass else: system = System.objects.get(slug=slug) system_version = SystemVersion.objects.get(system=system, is_current=True) system_meta = system_version.meta system_features = system_version.features.all() pass system_form = SystemForm(request.POST, instance=system) system_version_form = SystemVersionEditForm(request.POST, request.FILES) system_version_metadata_form = SystemVersionMetadataForm(request.POST) feature_form = SystemFeaturesForm(request.POST, features=system_features) if system_form.is_valid() and \ system_version_form.is_valid() and \ system_version_metadata_form.is_valid() and \ feature_form.is_valid(): if request.user.is_superuser: original_system_slug = system.slug system = system_form.save(commit=False) system.slug = slugify(system.name) system.save() # handle a redirect for a name change if system.slug != original_system_slug: SystemRedirect.objects.get_or_create( slug=original_system_slug, defaults=dict( system=system ) ) pass try: logo = system.current().logo except SystemVersion.DoesNotExist: logo = '' pass else: logo = system.current().logo pass system.versions.update(is_current=False) db_version = system_version_form.save(commit=False) db_version.creator = request.user db_version.system = system if logo and not db_version.logo: db_version.logo = logo db_version.save() system_version_form.save_m2m() db_meta = system_version_metadata_form.save() db_version.meta = db_meta db_version.save() system.ver = db_version.ver system.modified = timezone.now() system.save() db_version.description_citations.clear() for url in system_version_form.cleaned_data.get('description_citations', []): db_version.description_citations.add(url) db_version.history_citations.clear() for url in system_version_form.cleaned_data.get('history_citations', []): db_version.history_citations.add(url) db_version.start_year_citations.clear() for url in system_version_form.cleaned_data.get('start_year_citations', []): db_version.start_year_citations.add(url) db_version.end_year_citations.clear() for url in system_version_form.cleaned_data.get('end_year_citations', []): db_version.end_year_citations.add(url) features = { f.label : f for f in Feature.objects.all() } for field_name in feature_form.cleaned_data.keys(): feature_label = '_'.join( field_name.split('_')[:-1] ) feature = features[feature_label] value = feature_form.cleaned_data[field_name] if '_description' in field_name: sf, _ = SystemFeature.objects.get_or_create( system=db_version, feature=feature ) sf.description = value sf.save() pass elif '_citation'in field_name: sf, _ = SystemFeature.objects.get_or_create( system=db_version, feature=feature ) sf.citations.clear() for url in filter(None, value.split(',')): cit_url, _ = CitationUrl.objects.get_or_create(url=url) sf.citations.add(cit_url) pass pass elif '_choices'in field_name: sf, _ = SystemFeature.objects.get_or_create( system=db_version, feature=feature ) if not value: pass elif isinstance(value, str): sf.options.add( FeatureOption.objects.get( feature=feature, value=value ) ) else: for v in value: sf.options.add( FeatureOption.objects.get( feature=feature, value=v ) ) pass pass pass return redirect(db_version.system.get_absolute_url()) features = self.build_features(feature_form) return render(request, self.template_name, { 'activate': 'edit', # NAV-LINKS 'system_name': system.name, 'system_form': system_form, 'system_version_form': system_version_form, 'system_version_metadata_form': system_version_metadata_form, 'feature_form': feature_form, 'features': features, }) pass # ============================================== # DatabaseRevisionList # ============================================== class DatabaseRevisionList(View): template_name = 'core/revision_list.html' def get(self, request, slug): system = get_object_or_404(System, slug=slug) versions = SystemVersion.objects \ .filter(system=system) \ .select_related('system') return render(request, self.template_name, { 'activate': 'revisions', # NAV-LINKS 'system': system, 'versions': versions, }) @method_decorator(login_required) def post(self, request, slug): if not request.user.is_authenticated: return HttpResponseForbidden() system = System.objects.get(slug=slug) version = SystemVersion.objects.get(id=request.POST['ver']) system.versions.update(is_current=False) version.is_current = True system.ver = version.ver system.modified = timezone.now() version.save() system.save() return redirect('system', slug=slug) pass # ============================================== # DatabaseRevisionView # ============================================== class DatabaseRevisionView(View): template_name = 'core/revision_view.html' def get(self, request, slug, ver): system_version = get_object_or_404(SystemVersion.objects.select_related('system'), system__slug=slug, ver=ver) return render(request, self.template_name, { 'activate': 'revisions', # NAV-LINKS 'system': system_version.system, 'system_version': system_version, 'has_revision': True, 'system_features': system_version.features.all() }) pass # ============================================== # RecentChangesView # ============================================== class RecentChangesView(View): template_name = 'core/recent.html' def get(self, request): from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator page = request.GET.get('page', 1) username = request.GET.get('username', None) versions = None lookup_user = None # Try to get the versions for the given username if not username is None: User = get_user_model() try: lookup_user = User.objects.get(username=username) versions = SystemVersion.objects.filter(creator=lookup_user) except: lookup_user = None pass if versions is None: versions = SystemVersion.objects.all() # Sort by timestamps versions = versions.order_by('-created') paginator = Paginator(versions, 25) try: versions = paginator.get_page(page) except PageNotAnInteger: versions = paginator.get_page(1) except EmptyPage: versions = paginator.get_page(paginator.num_pages) return render(request, self.template_name, context={ 'activate': 'recent', # NAV-LINKS 'versions': versions, 'lookup_user': lookup_user, }) pass # ============================================== # HomeView # ============================================== class HomeView(View): ITEMS_TO_SHOW = 5 template_name = 'core/home.html' def get(self, request): # calculate date window start_date = timezone.now().astimezone(pytz.utc) - datetime.timedelta(days=30) # rolling 30 days start_date = datetime.datetime.combine(start_date.date(), datetime.time(0, 0, 0)) start_date = pytz.utc.localize(start_date) # get top systems by modified date most_recent = System.objects \ .order_by('-modified') most_recent = most_recent[:HomeView.ITEMS_TO_SHOW] # get top systems by number of (windowed) versions most_versions = System.objects \ .annotate(num_versions=Count('versions__id', filter=Q(versions__created__gte=start_date))) \ .order_by('-num_versions', 'name') \ .filter(num_versions__gt=0) most_versions = most_versions[:HomeView.ITEMS_TO_SHOW] # get top systems by number of (windowed) visits most_visits = System.objects \ .annotate(num_visits=Count('visits__id', filter=Q(visits__created__gte=start_date))) \ .order_by('-num_visits', 'name') \ .filter(num_visits__gt=0) most_visits = most_visits[:HomeView.ITEMS_TO_SHOW] # count numb systems num_systems = System.objects.all().count() return render(request, self.template_name, { 'most_recent': most_recent, 'most_versions': most_versions, 'most_visits': most_visits, 'no_nav_search': True, 'num_systems': num_systems, }) pass # ============================================== # SetupUserView # ============================================== class SetupUserView(UserPassesTestMixin, View): TOKEN_QUERY_NAME = 'token' template_name = 'registration/setup_user.html' def build_token(self, email, systems): payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7), 'iss': 'setup_user', 'sub': email, 'nbf': datetime.datetime.utcnow(), 'systems': list( map(int, systems) ), } s = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256') s = s.decode('utf-8') return s def get(self, request, *args, **kwargs): if request.GET.get('action') == 'url' and request.GET.get('email') and request.GET.getlist('systems'): email = request.GET.get('email').lower().strip() systems = request.GET.getlist('systems') response = None if UserModel.objects.filter(email=email).exists(): response = { 'error':'Email already exists' } pass else: url = reverse('create_user') + '?' + urllib.parse.urlencode({ SetupUserView.TOKEN_QUERY_NAME:self.build_token(email, systems) }) url = request.build_absolute_uri(url) response = { 'url':url } pass return JsonResponse(response) return render(request, self.template_name, { 'title': 'User Registration Setup', 'systems': System.objects.all(), }) def test_func(self): return super_user_check(self.request.user) pass # ============================================== # StatsView # ============================================== class StatsView(View): template_name = 'core/stats.html' default_limit = 10 def get_bycountries(self, limit): def reduce_countries(mapping, item): countries = item.countries.split(',') for c in countries: if c: mapping[c] = mapping.get(c, 0) + 1 return mapping system_countries = SystemVersion.objects \ .filter(is_current=True) \ .values_list('system_id', 'countries', named=True) system_countries = reduce(reduce_countries, system_countries, {}) system_countries = [ StatItem(k, v, k) for k,v in system_countries.items() ] system_countries.sort(key=lambda i: i.value, reverse=True) stat = Stat( 'Country of Origin', system_countries[:limit], 'country', False, len(system_countries) ) return stat def get_by_field(self, title, field, search_field, labels, slugs, is_systems, limit): def reduce_counts(mapping, item): assert not mapping is None if item is not None: mapping[item] = mapping.get(item, 0) + 1 values = SystemVersionMetadata.objects \ .filter(systemversion__is_current=True) \ .filter(~Q(**{field: None})) \ .values_list('systemversion__system_id', field, named=True) counts = { } for v in values: counts[v[1]] = counts.get(v[1], 0) + 1 #counts = reduce(reduce_counts, values, { }) stat_items = [ ] if is_systems: stat_items = [ StatItem(System.objects.get(id=k), v, slugs[k]) for k,v in counts.items() ] else: stat_items = [ StatItem(labels[k], v, slugs[k]) for k,v in counts.items() ] stat_items.sort(key=lambda i: i.value, reverse=True) stat = Stat( title, stat_items[:limit], search_field, is_systems, len(stat_items) ) return stat def get(self, request, stats_type=None): stats = [] # Countries if stats_type is None or stats_type == "country": limit = -1 if stats_type == "country" else self.default_limit stats.append( self.get_bycountries(limit) ) # Licenses if stats_type is None or stats_type == "license": limit = -1 if stats_type == "license" else self.default_limit labels = dict(License.objects.all().values_list('id', 'name')) slugs = dict(License.objects.all().values_list('id', 'slug')) stats.append( self.get_by_field('License', 'licenses', 'license', labels, slugs, False, limit) ) # Implementation Language if stats_type is None or stats_type == "programming": limit = -1 if stats_type == "programming" else self.default_limit all_values = ProgrammingLanguage.objects.all() labels = dict(all_values.values_list('id', 'name')) slugs = dict(all_values.values_list('id', 'slug')) stats.append( self.get_by_field('Implementation', 'written_in', 'programming', labels, slugs, False, limit) ) all_values = System.objects.all() labels = dict(all_values.values_list('id', 'name')) slugs = dict(all_values.values_list('id', 'slug')) # Compatibility if stats_type is None or stats_type == "compatible": stats.append( self.get_by_field('Compatibility', 'compatible_with', 'compatible', labels, slugs, True, self.default_limit) ) # Derived From if stats_type is None or stats_type == "derived": stats.append( self.get_by_field('Derived From', 'derived_from', 'derived', labels, slugs, True, self.default_limit) ) # Embeds if stats_type is None or stats_type == "embeds": stats.append( self.get_by_field('Embeds / Uses', 'embedded', 'embeds', labels, slugs, True, self.default_limit ) ) return render(request, self.template_name, context={ 'activate': 'stats', # NAV-LINKS 'stats': stats, 'stats_type': stats_type, }) pass # ============================================== # SitemapView # ============================================== class SitemapView(View): def get(self, request): response = HttpResponse(content_type='text/xml; charset=utf-8') root = etree.Element(SITEMAP_PREFIX+'urlset', nsmap=SITEMAP_NSMAP) tree = etree.ElementTree(root) # Stats Page url = etree.SubElement(root, 'url') loc = etree.SubElement(url, 'loc') loc.text = request.build_absolute_uri( reverse('stats') ) lastmod = etree.SubElement(url, 'lastmod') lastmod.text = datetime.date.today().isoformat() changefreq = etree.SubElement(url, 'changefreq') changefreq.text = 'weekly' # Systems for system in System.objects.order_by('name').iterator(): url = etree.SubElement(root, 'url') loc = etree.SubElement(url, 'loc') loc.text = request.build_absolute_uri( reverse('system', args=[system.slug]) ) lastmod = etree.SubElement(url, 'lastmod') lastmod.text = system.modified.date().isoformat() changefreq = etree.SubElement(url, 'changefreq') changefreq.text = 'weekly' pass tree.write(response, encoding='UTF-8', pretty_print=True, xml_declaration=True) return response pass # ============================================== # SystemView # ============================================== class SystemView(View): template_name = 'core/system.html' def get(self, request, slug): # try to get system by slug try: system = System.objects.get(slug=slug) pass except System.DoesNotExist: # if the system doesn't exist, check for a redirect try: r = SystemRedirect.objects.get(slug=slug) return redirect( 'system' , permanent=True, slug=r.system.slug ) pass except SystemRedirect.DoesNotExist: # with no redirect, throw 404 raise Http404( 'system does not exist' ) pass pass system_version = system.current() system_features = SystemFeature.objects.filter(system=system_version).select_related('feature').order_by('feature__label') # if they are logged in, check whether they are allowed to edit if not request.user.is_authenticated: user_can_edit = False elif request.user.is_superuser: user_can_edit = True else: user_can_edit = SystemACL.objects.filter(system=system, user=request.user).exists() pass # Compatible Systems compatible = [ ver.system for ver in SystemVersion.objects .filter(is_current=True) .filter(meta__compatible_with=system) .order_by("-logo") .select_related() ] # Derived Systems derived = [ ver.system for ver in SystemVersion.objects .filter(is_current=True) .filter(meta__derived_from=system) .order_by("-logo") .select_related() ] # Embedding Systems embeds = [ ver.system for ver in SystemVersion.objects .filter(is_current=True) .filter(meta__embedded=system) .order_by("-logo") .select_related() ] # Recommendations recommendations = [ rec.recommendation for rec in SystemRecommendation.objects .filter(system=system) .order_by("-score") .select_related() ] return render(request, self.template_name, { 'activate': 'system', # NAV-LINKS 'system': system, 'system_features': system_features, 'system_version': system_version, 'user_can_edit': user_can_edit, 'compatible': compatible, 'derived': derived, 'embeds': embeds, 'recommendations': recommendations, 'counter_token': CounterView.build_token('system', pk=system.id), }) pass # ============================================== # System Name AutoComplete # ============================================== def search_autocomplete(request): search_q = request.GET.get('q', '').strip() if search_q: sqs = SearchQuerySet().autocomplete(autocomplete_name=search_q) # [:5] suggestions = [system.name for system in sqs] else: suggestions = [ ] data = json.dumps(suggestions) return HttpResponse(data, content_type='application/json')
cmu-db/dbdb.io
dbdb/core/views.py
Python
apache-2.0
57,692
[ "VisIt" ]
70384e7665ca733b5aa2b29ba253462a8cba1b3ad357bec6092ac18ce3a27db5
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 math from functools import wraps from collections import OrderedDict from singa import utils from .tensor import Tensor from . import tensor from . import singa_wrap as singa class LayerMeta(type): def init_wrapper(func): @wraps(func) def wrapper(self, *args, **kwargs): if len(args) == 0: return if isinstance(args[0], list): assert len(args) > 0 and isinstance(args[0][0], Tensor), ( 'initialize function expects PlaceHolders or Tensors') dev = args[0][0].device else: assert len(args) > 0 and isinstance(args[0], Tensor), ( 'initialize function expects PlaceHolders or Tensors') dev = args[0].device prev_state = dev.graph_enabled() dev.EnableGraph(False) func(self, *args, **kwargs) self._initialized = True dev.EnableGraph(prev_state) return wrapper def forward_wrapper(func): @wraps(func) def wrapper(self, *args, **kwargs): if not self._initialized: self.initialize(*args, **kwargs) self._initialized = True return func(self, *args, **kwargs) return wrapper def __new__(cls, name, bases, attr): if 'initialize' in attr: attr['initialize'] = LayerMeta.init_wrapper(attr['initialize']) if 'forward' in attr: attr['forward'] = LayerMeta.forward_wrapper(attr['forward']) return super(LayerMeta, cls).__new__(cls, name, bases, attr) class Layer(object, metaclass=LayerMeta): sep = '.' def __init__(self): self.name = None self._initialized = False self._parent = None self._layers = dict() def initialize(self, *input): """ Initialize the layer This function will be called before the forward function if this layer hasn't been initialized. Those members that need to be initialized according to the input will be initialized in this function. e.g. parameters, states and handles. Args: *input: input args, should be consistent with the forward function """ pass def forward(self, *input): """ Forward propagation Args: *input: input arguments consisting of only PyTensors Returns: PyTensor instance(s) """ raise NotImplementedError def __call__(self, *args, **kwargs): return self.forward(*args, **kwargs) def get_params(self): """ Get parameters of this layer and all sublayers Returns: parameters(dict): A dictionary contains parameter names and values of this layer and all sublayers. """ params = dict() sublayers = self._layers for name, sublayer in sublayers.items(): if sublayer._initialized: params.update(sublayer.get_params()) return params def set_params(self, parameters): """ Set parameters for this layer and all sublayers Args: parameters(dict): A dictionary contains parameter names and corresponding values. The value shoud be either a PyTensor or numpy ndarray """ names = parameters.keys() sublayers = self._layers for name, sublayer in sublayers.items(): if sublayer._initialized: if self._has_layer_param(sublayer, names): sublayer.set_params(parameters) def get_states(self): """ Get states of this layer and all sublayers Returns: states(dict): A dictionary contains state names and values of this layer and all sublayers. """ states = dict() sublayers = self._layers for name, sublayer in sublayers.items(): if sublayer._initialized: states.update(sublayer.get_states()) states.update(self.get_params()) return states def set_states(self, states): """ Set states for this layer and all sublayers Args: states(dict): A dictionary contains state names and corresponding values. The value shoud be either a PyTensor or numpy ndarray """ names = states.keys() sublayers = self._layers for name, sublayer in sublayers.items(): if sublayer._initialized: if self._has_layer_param(sublayer, names): sublayer.set_states(states) self.set_params(states) def dtype_check(self, *inputs): """ check if all input have same data type. Args: *inputs: input args consisting of only PyTensors """ flag = inputs[0].device.graph_enabled() inputs[0].device.EnableGraph(False) x_dtype = inputs[0].dtype for inp in inputs: if inp.dtype != x_dtype: inp.to_type(x_dtype) inputs[0].device.EnableGraph(flag) def device_check(self, *inputs): """ Check if the devices of the input tensor are the same. Keep the device where each tensors is located the same as the first tensor. Copy data to the device of the first tensor if the device does not match. Args: *inputs: input args consisting of only PyTensors """ # disabled the graph to prevent buffering data transfer operator x_device = inputs[0].device prev_state = x_device.graph_enabled() x_device.EnableGraph(False) x_dev_id = x_device.id() for var in inputs: if var.device.id() != x_dev_id: var.to_device(x_device) x_device.EnableGraph(prev_state) def _has_layer_param(self, layer, names): """ Determine whether names contains parameter names in the layer Args: layer(Layer): the layer instance names(list): the list of parameter names Returns: boolean: whether names contains parameter names in that layer """ for name in names: if name.startswith(layer.name): return True return False def _get_name_prefix(self): """ Get the name prefix Returns: prefix(str): the layer or param name prefix """ if self.name and self._parent: return self.name + Layer.sep else: return '' def __getattr__(self, name): if '_layers' in self.__dict__: layers = self.__dict__['_layers'] if name in layers: return layers[name] raise AttributeError("'{}' object has no attribute '{}'".format( type(self).__name__, name)) def __setattr__(self, name, value): if isinstance(value, Layer): # TODO: remove the attr from dict first self.__dict__['_layers'][name] = value value.__dict__['_parent'] = self value.name = self._get_name_prefix() + name else: object.__setattr__(self, name, value) if isinstance(value, Tensor) and value.is_dummy(): # WARN: If tensors are initialized in __init__ function # their names may be incorrect and should be reset value.name = self._get_name_prefix() + name elif name == 'name' and value: # WARN: can't reset the name after the initialization # update sublayer name for name, sublayer in self._layers.items(): sublayer.name = self._get_name_prefix() + name def __delattr__(self, name): if name in self._layers: del self._layers[name] else: object.__delattr__(self, name) def register_layers(self, *args): """ Register a list of sublayers. Can only be called once in each subclass. Args: *args: a list of sublayers or a dictionary that contains the name and the instance of each sublayer """ if len(args) == 1 and isinstance(args[0], OrderedDict): items = args[0].items() else: items = [(v.__class__.__name__ + '_' + str(idx), v) for idx, v in enumerate(args)] for name, value in items: if isinstance(value, Layer): self._layers[name] = value value.__dict__['_parent'] = self value.name = name class Linear(Layer): """ Generate a Linear operator """ # TODO: replace current with # def __init__(self, out_features, bias=True): def __init__(self, out_features, *args, bias=True, **kwargs): """ Args: out_channels: int, the channel of output, also is the number of filters bias: bool """ super(Linear, self).__init__() self.out_features = out_features # TODO: for backward compatibility, to remove if len(args) > 0: self.in_features = out_features self.out_features = args[0] if len(args) > 1: self.bias = args[1] else: self.bias = bias def initialize(self, x): self.in_features = x.shape[1] w_shape = (self.in_features, self.out_features) b_shape = (self.out_features,) self.W = Tensor(shape=w_shape, dtype=x.dtype, requires_grad=True, stores_grad=True) std = math.sqrt(2.0 / (self.in_features + self.out_features)) self.W.gaussian(0.0, std) if self.bias: self.b = Tensor(shape=b_shape, dtype=x.dtype, requires_grad=True, stores_grad=True) self.b.set_value(0.0) else: self.b = None def forward(self, x): if self.b: self.device_check(x, self.W, self.b) self.dtype_check(x, self.W, self.b) else: self.device_check(x, self.W) self.dtype_check(x, self.W) assert x.shape[1] == self.W.shape[0], ( "Linear layer expects input features size %d received %d" % (self.W.shape[0], x.shape[1])) y = autograd.matmul(x, self.W) if self.bias: y = autograd.add_bias(y, self.b, axis=0) return y def get_params(self): if self.bias: return {self.W.name: self.W, self.b.name: self.b} else: return {self.W.name: self.W} def set_params(self, parameters): self.W.copy_from(parameters[self.W.name]) if self.bias: self.b.copy_from(parameters[self.b.name]) class Gemm(Layer): """ Generate a Gemm operator Y = alpha * A' * B' + beta * C B is weight, C is bias """ def __init__(self, nb_kernels, alpha=1.0, beta=1.0, transA=False, transB=True, bias=True, bias_shape=None): """ Args: nb_kernels: int, the channel of output, also is the number of filters alpha (float): Scalar multiplier for the product of input tensors A * B. beta (float): Scalar multiplier for input tensor C. ransA (bool): Whether A should be transposed transB (bool): Whether B should be transposed bias: bool """ super(Gemm, self).__init__() self.nb_kernels = nb_kernels self.alpha = alpha self.beta = beta self.transA = 1 if transA else 0 self.transB = 1 if transB else 0 self.bias = bias self.bias_shape = bias_shape def initialize(self, x): if self.transA == 0: self.in_features = x.shape[-1] else: self.in_features = x.shape[0] if self.transB == 0: w_shape = (self.in_features, self.nb_kernels) else: w_shape = (self.nb_kernels, self.in_features) if self.bias_shape: b_shape = self.bias_shape else: b_shape = (1, self.nb_kernels) self.W = Tensor(shape=w_shape, requires_grad=True, stores_grad=True, device=x.device) std = math.sqrt(2.0 / (self.in_features + self.nb_kernels)) self.W.gaussian(0.0, std) if self.bias: self.b = Tensor(shape=b_shape, requires_grad=True, stores_grad=True, device=x.device) self.b.set_value(0.0) else: self.b = None def forward(self, x): if self.b: self.device_check(x, self.W, self.b) else: self.device_check(x, self.W) if self.transA == 0: in_features = x.shape[-1] else: in_features = x.shape[0] if self.transB == 0: in_features_w = self.W.shape[0] else: in_features_w = self.W.shape[-1] assert in_features == in_features_w, ( "Gemm layer expects input features size %d received %d" % (in_features_w, in_features)) y = autograd.gemm(x, self.W, self.b, self.alpha, self.beta, self.transA, self.transB) return y def get_params(self): if self.bias: return {self.W.name: self.W, self.b.name: self.b} else: return {self.W.name: self.W} def set_params(self, parameters): self.W.copy_from(parameters[self.W.name]) if self.bias: self.b.copy_from(parameters[self.b.name]) class Embedding(Layer): """ Generate an Embedding operator """ def __init__(self, input_dim, output_dim, initializer="gaussian"): """init the Embedding operator Args: input_dim (int): the number of different words in the dictionary output_dim (int): the dimendion of a word after the embedding initializer (str, optional): weight initializer, can be [uniform, gaussian]. Defaults to "uniform". """ super(Embedding, self).__init__() self.input_dim = input_dim self.output_dim = output_dim self.initializer = initializer def initialize(self, x): w_shape = (self.input_dim, self.output_dim) self.W = Tensor(shape=w_shape, requires_grad=True, stores_grad=True, device=x.device) if self.initializer == 'uniform': self.W.uniform(-1., 1.) else: self.W.gaussian(0., 1.) def from_pretrained(self, W, freeze=True): self.set_params({self.W.name: W}) self.W.requires_grad = not freeze def forward(self, x): return autograd.embedding(x, self.W) def get_params(self): return {self.W.name: self.W} def set_params(self, parameters): self.W.copy_from(parameters[self.W.name]) class Conv2d(Layer): """ Generate a Conv 2d operator """ def __init__(self, nb_kernels, kernel_size, *args, stride=1, padding=0, dilation=1, group=1, bias=True, pad_mode="NOTSET", activation="NOTSET", **kwargs): """ Args: nb_kernels (int): the channel of output, also is the number of filters kernel_size (int or tuple): kernel size for two direction of each axis. For example, (2, 3), the first 2 means will add 2 at the beginning and also 2 at the end for its axis.and if a int is accepted, the kernel size will be initiated as (int, int) stride (int or tuple): stride, the logic is the same as kernel size. padding (int): tuple, list or None, padding, the logic is the same as kernel size. However, if you set pad_mode as "SAME_UPPER" or "SAME_LOWER" mode, you can set padding as None, and the padding will be computed automatically. dilation (int): only support 1 group (int): group bias (bool): bias pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input. In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. activation (string): can be NOTSET, RELU, where default value is NOTSET, which means there is no activation behind the conv2d layer. RELU means there is a ReLU behind current conv2d layer. """ super(Conv2d, self).__init__() # the old code create the layer like: Conv2d(8, 16, 3), or Conv2d(8, 16, 3, stride=1) # the following code block is for backward compatibility if len(args) > 0: nb_kernels = kernel_size kernel_size = args[0] if len(args) > 1: stride = args[1] if len(args) > 2: padding = args[2] self.nb_kernels = nb_kernels self.kernel_size = kernel_size self.stride = stride self.padding = padding self.dilation = dilation self.group = group self.bias = bias self.pad_mode = pad_mode self.activation = activation if isinstance(kernel_size, int): self.kernel_size = (kernel_size, kernel_size) elif isinstance(kernel_size, tuple): self.kernel_size = kernel_size else: raise TypeError("Wrong kernel_size type.") if isinstance(stride, int): self.stride = (stride, stride) elif isinstance(stride, tuple): self.stride = stride else: raise TypeError("Wrong stride type.") self.odd_padding = (0, 0, 0, 0) if isinstance(padding, int): self.padding = (padding, padding) elif isinstance(padding, tuple) or isinstance(padding, list): if len(padding) == 2: self.padding = padding elif len(padding) == 4: _h_mask = padding[0] - padding[1] _w_mask = padding[2] - padding[3] # the odd paddding is the value that cannot be handled by the tuple padding (w, h) mode # so we need to firstly handle the input, then use the nomal padding method. self.odd_padding = (max(_h_mask, 0), max(-_h_mask, 0), max(_w_mask, 0), max(-_w_mask, 0)) self.padding = ( padding[0] - self.odd_padding[0], padding[2] - self.odd_padding[2], ) else: raise TypeError("Wrong padding value.") if dilation != 1 and list(dilation) != [1, 1]: raise ValueError("Not implemented yet") self.inner_params = { "cudnn_prefer": "fastest", "workspace_MB_limit": 1024, } # TODO valid value of inner_params check for kwarg in kwargs: if kwarg not in self.inner_params: raise TypeError("Keyword argument not understood:", kwarg) else: self.inner_params[kwarg] = kwargs[kwarg] def initialize(self, x): self.in_channels = x.shape[1] w_shape = ( self.nb_kernels, int(self.in_channels / self.group), self.kernel_size[0], self.kernel_size[1], ) self.W = Tensor(shape=w_shape, requires_grad=True, stores_grad=True, device=x.device) # std = math.sqrt( # 2.0 / (self.in_channels * self.kernel_size[0] * self.kernel_size[1] + # self.nb_kernels)) std = math.sqrt( 2.0 / (w_shape[1] * self.kernel_size[0] * self.kernel_size[1] + self.nb_kernels)) self.W.gaussian(0.0, std) if self.bias: b_shape = (self.nb_kernels,) self.b = Tensor(shape=b_shape, requires_grad=True, stores_grad=True, device=x.device) self.b.set_value(0.0) else: # to keep consistency when to do forward. self.b = None # Tensor(data=CTensor([]), requires_grad=False, stores_grad=False) # if same pad mode, re-compute the padding if self.pad_mode in ("SAME_UPPER", "SAME_LOWER"): self.padding, self.odd_padding = utils.get_padding_shape( self.pad_mode, x.shape[2:], self.kernel_size, self.stride) self.padding = [self.padding[0], self.padding[2]] _x = x if self.odd_padding != (0, 0, 0, 0): x_shape = list(x.data.shape()) x_shape[2] += (self.odd_padding[0] + self.odd_padding[1]) x_shape[3] += (self.odd_padding[2] + self.odd_padding[3]) _x = Tensor(shape=x_shape, device=x.device) _x.set_value(0.0) if _x.device.id() == -1: if self.group != 1: raise ValueError("Not implemented yet") else: if not hasattr(self, "handle"): self.handle = singa.ConvHandle( _x.data, self.kernel_size, self.stride, self.padding, self.in_channels, self.nb_kernels, self.bias, self.group, ) else: if not hasattr(self, "handle"): if _x.dtype == tensor.float16: self.handle = singa.CudnnConvHandle( _x.data, self.kernel_size, self.stride, self.padding, self.in_channels, self.nb_kernels, self.bias, self.group, 1024*1024*1024, "tensor_ops" ) else: self.handle = singa.CudnnConvHandle( _x.data, self.kernel_size, self.stride, self.padding, self.in_channels, self.nb_kernels, self.bias, self.group, ) def forward(self, x): # sanitize the device of params/states, TODO: better to decorate forward() self.device_check(x, *[s for k, s in self.get_states().items()]) self.dtype_check(x, *[s for k, s in self.get_states().items()]) assert (self.group >= 1 and self.in_channels % self.group == 0), "please set reasonable group." assert (self.nb_kernels >= self.group and self.nb_kernels % self.group == 0), "nb_kernels and group dismatched." y = autograd.conv2d(self.handle, x, self.W, self.b, self.odd_padding) if self.activation != "NOTSET": if self.activation == "RELU": y = autograd.relu(y) return y def get_params(self): if self.bias: return {self.W.name: self.W, self.b.name: self.b} else: return {self.W.name: self.W} def set_params(self, parameters): self.W.copy_from(parameters[self.W.name]) if self.bias: self.b.copy_from(parameters[self.b.name]) class SeparableConv2d(Layer): """ Generate a Conv 2d operator """ def __init__(self, nb_kernels, kernel_size, *args, stride=1, padding=0, bias=False): """ Args: nb_kernels (int): the channel of output, also is the number of filters kernel_size (int or tuple): kernel size for two direction of each axis. For example, (2, 3), the first 2 means will add 2 at the beginning and also 2 at the end for its axis.and if a int is accepted, the kernel size will be initiated as (int, int) stride (int or tuple): stride, the logic is the same as kernel size. padding (int): tuple, list or None, padding, the logic is the same as kernel size. However, if you set pad_mode as "SAME_UPPER" or "SAME_LOWER" mode, you can set padding as None, and the padding will be computed automatically. bias (bool): bias """ super(SeparableConv2d, self).__init__() # the following code block is for backward compatibility if len(args) > 0: nb_kernels = kernel_size kernel_size = args[0] if len(args) > 1: stride = args[1] if len(args) > 2: padding = args[2] self.nb_kernels = nb_kernels self.kernel_size = kernel_size self.stride = stride self.padding = padding self.bias = bias def initialize(self, x): self.in_channels = x.shape[1] self.depthwise_conv = Conv2d( self.in_channels, self.kernel_size, stride=self.stride, padding=self.padding, group=self.in_channels, bias=self.bias, ) self.point_conv = Conv2d(self.nb_kernels, 1, bias=self.bias) def forward(self, x): y = self.depthwise_conv(x) y = self.point_conv(y) return y class BatchNorm2d(Layer): """ Generate a BatchNorm 2d operator """ def __init__(self, *args, momentum=0.9): """ Args: momentum (float): Factor used in computing the running mean and variance. """ super(BatchNorm2d, self).__init__() if len(args) > 0: self.channels = args[0] if len(args) > 1: self.momentum = args[1] self.momentum = momentum assert 0 <= momentum <= 1.0, ("Illegal momentum") def initialize(self, x): self.channels = x.shape[1] param_shape = (self.channels,) self.scale = Tensor(shape=param_shape, requires_grad=True, stores_grad=True) self.scale.set_value(1.0) self.bias = Tensor(shape=param_shape, requires_grad=True, stores_grad=True) self.bias.set_value(0.0) self.running_mean = Tensor(shape=param_shape, requires_grad=False, stores_grad=False) self.running_mean.set_value(0.0) self.running_var = Tensor(shape=param_shape, requires_grad=False, stores_grad=False) self.running_var.set_value(1.0) if not hasattr(self, "handle"): if x.device.id() == -1: self.handle = singa.BatchNormHandle(self.momentum, x.data) else: self.handle = singa.CudnnBatchNormHandle(self.momentum, x.data) def forward(self, x): assert x.shape[1] == self.channels, ( "number of channels dismatched. %d vs %d" % (x.shape[1], self.channels)) self.device_check(x, self.scale, self.bias, self.running_mean, self.running_var) self.dtype_check(x, self.scale, self.bias, self.running_mean, self.running_var) y = autograd.batchnorm_2d( self.handle, x, self.scale, self.bias, self.running_mean, self.running_var, ) return y def get_params(self): return {self.scale.name: self.scale, self.bias.name: self.bias} def set_params(self, parameters): self.scale.copy_from(parameters[self.scale.name]) self.bias.copy_from(parameters[self.bias.name]) def get_states(self): ret = self.get_params() ret[self.running_mean.name] = self.running_mean ret[self.running_var.name] = self.running_var return ret def set_states(self, states): self.set_params(states) self.running_mean.copy_from(states[self.running_mean.name]) self.running_var.copy_from(states[self.running_var.name]) class Pooling2d(Layer): """ Generate a Pooling 2d operator """ def __init__(self, kernel_size, stride=None, padding=0, is_max=True, pad_mode="NOTSET"): """ Args: kernel_size (int or tuple): kernel size for two direction of each axis. For example, (2, 3), the first 2 means will add 2 at the beginning and also 2 at the end for its axis.and if a int is accepted, the kernel size will be initiated as (int, int) stride (int or tuple): stride, the logic is the same as kernel size. padding (int): tuple, list or None, padding, the logic is the same as kernel size. However, if you set pad_mode as "SAME_UPPER" or "SAME_LOWER" mode, you can set padding as None, and the padding will be computed automatically. is_max (bool): is max pooling or avg pooling pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input. In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. """ super(Pooling2d, self).__init__() if isinstance(kernel_size, int): self.kernel_size = (kernel_size, kernel_size) elif isinstance(kernel_size, tuple): self.kernel_size = kernel_size else: raise TypeError("Wrong kernel_size type.") if stride is None: self.stride = self.kernel_size elif isinstance(stride, int): self.stride = (stride, stride) elif isinstance(stride, tuple): self.stride = stride assert stride[0] > 0 or (kernel_size[0] == 1 and padding[0] == 0), ( "stride[0]=0, but kernel_size[0]=%d, padding[0]=%d" % (kernel_size[0], padding[0])) else: raise TypeError("Wrong stride type.") self.odd_padding = (0, 0, 0, 0) if isinstance(padding, int): self.padding = (padding, padding) elif isinstance(padding, tuple) or isinstance(padding, list): if len(padding) == 2: self.padding = padding elif len(padding) == 4: _h_mask = padding[0] - padding[1] _w_mask = padding[2] - padding[3] # the odd paddding is the value that cannot be handled by the tuple padding (w, h) mode # so we need to firstly handle the input, then use the nomal padding method. self.odd_padding = (max(_h_mask, 0), max(-_h_mask, 0), max(_w_mask, 0), max(-_w_mask, 0)) self.padding = ( padding[0] - self.odd_padding[0], padding[2] - self.odd_padding[2], ) else: raise TypeError("Wrong padding value.") self.is_max = is_max self.pad_mode = pad_mode def initialize(self, x): # if same pad mode, re-compute the padding if self.pad_mode in ("SAME_UPPER", "SAME_LOWER"): self.padding, self.odd_padding = utils.get_padding_shape( self.pad_mode, x.shape[2:], self.kernel_size, self.stride) # if same pad mode, re-compute the padding if self.pad_mode in ("SAME_UPPER", "SAME_LOWER"): self.padding, self.odd_padding = utils.get_padding_shape( self.pad_mode, x.shape[2:], self.kernel_size, self.stride) self.padding = [self.padding[0], self.padding[2]] _x = x if self.odd_padding != (0, 0, 0, 0): x_shape = list(x.data.shape()) x_shape[2] += (self.odd_padding[0] + self.odd_padding[1]) x_shape[3] += (self.odd_padding[2] + self.odd_padding[3]) _x = Tensor(shape=x_shape, device=x.device) _x.set_value(0.0) if _x.device.id() == -1: self.handle = singa.PoolingHandle( _x.data, self.kernel_size, self.stride, self.padding, self.is_max, ) else: self.handle = singa.CudnnPoolingHandle( _x.data, self.kernel_size, self.stride, self.padding, self.is_max, ) def forward(self, x): y = autograd.pooling_2d(self.handle, x, self.odd_padding) return y class MaxPool2d(Pooling2d): """ Generate a Max Pooling 2d operator """ def __init__(self, kernel_size, stride=None, padding=0, pad_mode="NOTSET"): """ Args: kernel_size (int or tuple): kernel size for two direction of each axis. For example, (2, 3), the first 2 means will add 2 at the beginning and also 2 at the end for its axis.and if a int is accepted, the kernel size will be initiated as (int, int) stride (int or tuple): stride, the logic is the same as kernel size. padding (int): tuple, list or None, padding, the logic is the same as kernel size. However, if you set pad_mode as "SAME_UPPER" or "SAME_LOWER" mode, you can set padding as None, and the padding will be computed automatically. pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input. In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. """ super(MaxPool2d, self).__init__(kernel_size, stride, padding, True, pad_mode) class AvgPool2d(Pooling2d): def __init__(self, kernel_size, stride=None, padding=0, pad_mode="NOTSET"): """ Args: kernel_size (int or tuple): kernel size for two direction of each axis. For example, (2, 3), the first 2 means will add 2 at the beginning and also 2 at the end for its axis.and if a int is accepted, the kernel size will be initiated as (int, int) stride (int or tuple): stride, the logic is the same as kernel size. padding (int): tuple, list or None, padding, the logic is the same as kernel size. However, if you set pad_mode as "SAME_UPPER" or "SAME_LOWER" mode, you can set padding as None, and the padding will be computed automatically. pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input. In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. """ super(AvgPool2d, self).__init__(kernel_size, stride, padding, False, pad_mode) class MaxPool1d(Pooling2d): """ Generate a Max Pooling 1d operator """ def __init__(self, kernel_size, stride=None, padding=0, pad_mode="NOTSET"): """ Args: kernel_size (int or tuple): kernel size for two direction of each axis. For example, (2, 3), the first 2 means will add 2 at the beginning and also 2 at the end for its axis.and if a int is accepted, the kernel size will be initiated as (int, int) stride (int or tuple): stride, the logic is the same as kernel size. padding (int): tuple, list or None, padding, the logic is the same as kernel size. However, if you set pad_mode as "SAME_UPPER" or "SAME_LOWER" mode, you can set padding as None, and the padding will be computed automatically. pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input. In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. """ if stride is None: stride = kernel_size super(MaxPool1d, self).__init__((1, kernel_size), (1, stride), (0, padding), True, pad_mode) class AvgPool1d(Pooling2d): """ Generate a Avg Pooling 1d operator """ def __init__(self, kernel_size, stride=None, padding=0, pad_mode="NOTSET"): """ Args: kernel_size (int or tuple): kernel size for two direction of each axis. For example, (2, 3), the first 2 means will add 2 at the beginning and also 2 at the end for its axis.and if a int is accepted, the kernel size will be initiated as (int, int) stride (int or tuple): stride, the logic is the same as kernel size. padding (int): tuple, list or None, padding, the logic is the same as kernel size. However, if you set pad_mode as "SAME_UPPER" or "SAME_LOWER" mode, you can set padding as None, and the padding will be computed automatically. pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input. In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. """ if stride is None: stride = kernel_size super(AvgPool1d, self).__init__((1, kernel_size), (1, stride), (0, padding), False, pad_mode) class RNN_Base(Layer): def step_forward(self, x=None, h=None, c=None, Wx=None, Wh=None, Bx=None, Bh=None, b=None): raise NotImplementedError class RNN(RNN_Base): """ Generate a RNN operator """ def __init__( self, input_size, hidden_size, num_layers=1, nonlinearity="tanh", bias=True, batch_first=False, dropout=0, bidirectional=False, ): """ Args: input_size (int): The number of expected features in the input x hidden_size (int): The number of features in the hidden state h num_layers (int): Number of recurrent layers. Default: 1 nonlinearity (string): The non-linearity to use. Default: 'tanh' bias (bool): If False, then the layer does not use bias weights. Default: True batch_first (bool): If True, then the input and output tensors are provided as (batch, seq, feature). Default: False dropout (float): If non-zero, introduces a Dropout layer on the outputs of each RNN layer except the last layer, with dropout probability equal to dropout. Default: 0 bidirectional (bool): If True, becomes a bidirectional RNN. Default: False """ super(RNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.nonlinearity = nonlinearity self.bias = bias self.batch_first = batch_first self.dropout = dropout self.bidirectional = bidirectional def initialize(self, xs, h0): Wx_shape = (self.input_size, self.hidden_size) self.Wx = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True) self.Wx.gaussian(0.0, 1.0) Wh_shape = (self.hidden_size, self.hidden_size) self.Wh = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True) self.Wh.gaussian(0.0, 1.0) b_shape = (self.hidden_size,) self.b = Tensor(shape=b_shape, requires_grad=True, stores_grad=True) self.b.set_value(0.0) def forward(self, xs, h0): # xs: a tuple or list of input tensors if not isinstance(xs, tuple): xs = tuple(xs) inputs = xs + (h0,) self.device_check(*inputs) # self.device_check(inputs[0], *self.params) self.device_check(inputs[0], self.Wx, self.Wh, self.b) batchsize = xs[0].shape[0] out = [] h = self.step_forward(xs[0], h0, self.Wx, self.Wh, self.b) out.append(h) for x in xs[1:]: assert x.shape[0] == batchsize h = self.step_forward(x, h, self.Wx, self.Wh, self.b) out.append(h) return out, h def step_forward(self, x, h, Wx, Wh, b): y2 = autograd.matmul(h, Wh) y1 = autograd.matmul(x, Wx) y = autograd.add(y2, y1) y = autograd.add_bias(y, b, axis=0) if self.nonlinearity == "tanh": y = autograd.tanh(y) elif self.nonlinearity == "relu": y = autograd.relu(y) else: raise ValueError return y def get_params(self): return { self.Wx.name: self.Wx, self.Wh.name: self.Wh, self.b.name: self.b } def set_params(self, parameters): self.Wx.copy_from(parameters[self.Wx.name]) self.Wh.copy_from(parameters[self.Wh.name]) self.b.copy_from(parameters[self.b.name]) class LSTM(RNN_Base): """ Generate a LSTM operator """ def __init__( self, input_size, hidden_size, nonlinearity="tanh", num_layers=1, bias=True, batch_first=False, dropout=0, bidirectional=False, ): """ Args: input_size (int): The number of expected features in the input x hidden_size (int): The number of features in the hidden state h num_layers (int): Number of recurrent layers. Default: 1 nonlinearity (string): The non-linearity to use. Default: 'tanh' bias (bool): If False, then the layer does not use bias weights. Default: True batch_first (bool): If True, then the input and output tensors are provided as (batch, seq, feature). Default: False dropout (float): If non-zero, introduces a Dropout layer on the outputs of each RNN layer except the last layer, with dropout probability equal to dropout. Default: 0 bidirectional (bool): If True, becomes a bidirectional RNN. Default: False """ super(LSTM, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.nonlinearity = nonlinearity self.bias = bias self.batch_first = batch_first self.dropout = dropout self.bidirectional = bidirectional def initialize(self, xs, h0_c0): # 1. Wx_i input, Bx_i # 2. Wx_f forget, Bx_f # 3. Wx_o output, Bx_o # 4. Wx_g candidate, Bx_g Wx_shape = (self.input_size, self.hidden_size) self.Wx_i = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True) self.Wx_f = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True) self.Wx_o = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True) self.Wx_g = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True) Wh_shape = (self.hidden_size, self.hidden_size) self.Wh_i = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True) self.Wh_f = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True) self.Wh_o = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True) self.Wh_g = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True) [ w.gaussian(0.0, 0.01) for w in [ self.Wx_i, self.Wx_f, self.Wx_o, self.Wx_g, self.Wh_i, self.Wh_f, self.Wh_o, self.Wh_g ] ] Bx_shape = (self.hidden_size,) self.Bx_i = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True) self.Bx_f = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True) self.Bx_o = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True) self.Bx_g = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True) self.Bh_i = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True) self.Bh_f = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True) self.Bh_o = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True) self.Bh_g = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True) [ b.set_value(0.0) for b in [ self.Bx_i, self.Bx_f, self.Bx_o, self.Bx_g, self.Bh_i, self.Bh_f, self.Bh_o, self.Bh_g ] ] def forward(self, xs, h0_c0): # xs: a tuple or list of input tensors # h0_c0: a tuple of (h0, c0) h0, c0 = h0_c0 if not isinstance(xs, list): xs = list(xs) inputs = xs + list((h0, c0)) self.device_check(*inputs) self.device_check(inputs[0], *[s for k, s in self.get_states().items()]) batchsize = xs[0].shape[0] out = [] h, c = self.step_forward(xs[0], h0, c0) out.append(h) for x in xs[1:]: assert x.shape[0] == batchsize h, c = self.step_forward(x, h, c) out.append(h) return out, h, c def step_forward(self, x, h, c): # input y1 = autograd.matmul(x, self.Wx_i) y1 = autograd.add_bias(y1, self.Bx_i, axis=0) y2 = autograd.matmul(h, self.Wh_i) y2 = autograd.add_bias(y2, self.Bh_i, axis=0) i = autograd.add(y1, y2) i = autograd.sigmoid(i) # forget y1 = autograd.matmul(x, self.Wx_f) y1 = autograd.add_bias(y1, self.Bx_f, axis=0) y2 = autograd.matmul(h, self.Wh_f) y2 = autograd.add_bias(y2, self.Bh_f, axis=0) f = autograd.add(y1, y2) f = autograd.sigmoid(f) # output y1 = autograd.matmul(x, self.Wx_o) y1 = autograd.add_bias(y1, self.Bx_o, axis=0) y2 = autograd.matmul(h, self.Wh_o) y2 = autograd.add_bias(y2, self.Bh_o, axis=0) o = autograd.add(y1, y2) o = autograd.sigmoid(o) y1 = autograd.matmul(x, self.Wx_g) y1 = autograd.add_bias(y1, self.Bx_g, axis=0) y2 = autograd.matmul(h, self.Wh_g) y2 = autograd.add_bias(y2, self.Bh_g, axis=0) g = autograd.add(y1, y2) g = autograd.tanh(g) cout1 = autograd.mul(f, c) cout2 = autograd.mul(i, g) cout = autograd.add(cout1, cout2) hout = autograd.tanh(cout) hout = autograd.mul(o, hout) return hout, cout def get_params(self): ret = {} for w in [ self.Wx_i, self.Wx_f, self.Wx_o, self.Wx_g, self.Wh_i, self.Wh_f, self.Wh_o, self.Wh_g ]: ret[w.name] = w for b in [ self.Bx_i, self.Bx_f, self.Bx_o, self.Bx_g, self.Bh_i, self.Bh_f, self.Bh_o, self.Bh_g ]: ret[b.name] = b return ret def set_params(self, parameters): for w in [ self.Wx_i, self.Wx_f, self.Wx_o, self.Wx_g, self.Wh_i, self.Wh_f, self.Wh_o, self.Wh_g ]: w.copy_from(parameters[w.name]) for b in [ self.Bx_i, self.Bx_f, self.Bx_o, self.Bx_g, self.Bh_i, self.Bh_f, self.Bh_o, self.Bh_g ]: b.copy_from(parameters[b.name]) ''' layers without params or states ''' class ReLU(Layer): """ Generate a ReLU operator """ def __init__(self): super(ReLU, self).__init__() def forward(self, x): return autograd.relu(x) class Sigmoid(Layer): """ Generate a ReLU operator """ def __init__(self): super(Sigmoid, self).__init__() def forward(self, x): return autograd.sigmoid(x) class Add(Layer): """ Generate a Add operator """ def __init__(self): super(Add, self).__init__() def forward(self, a, b): return autograd.add(a, b) class Flatten(Layer): """ Generate a Flatten operator """ def __init__(self, axis=1): super(Flatten, self).__init__() self.axis = axis def forward(self, x): return autograd.flatten(x, self.axis) class SoftMaxCrossEntropy(Layer): """ Generate a SoftMaxCrossEntropy operator """ def __init__(self): super(SoftMaxCrossEntropy, self).__init__() def forward(self, x, t): return autograd.softmax_cross_entropy(x, t) class SoftMax(Layer): """ Generate a SoftMax operator """ def __init__(self): super(SoftMax, self).__init__() def forward(self, x): return autograd.softmax(x) class MeanSquareError(Layer): """ Generate a MeanSquareError operator """ def __init__(self): super(MeanSquareError, self).__init__() def forward(self, x, t): return autograd.mse_loss(x, t) class CrossEntropy(Layer): """ Generate a CrossEntropy operator """ def __init__(self): super(CrossEntropy, self).__init__() def forward(self, x, t): return autograd.cross_entropy(x, t) class BinaryCrossEntropy(Layer): """ Generate a BinaryCrossEntropy operator """ def __init__(self): super(BinaryCrossEntropy, self).__init__() def forward(self, x, t): return autograd.binary_cross_entropy(x, t) class Dropout(Layer): """ Generate a Dropout operator """ def __init__(self, ratio=0.5): super(Dropout, self).__init__() self.ratio = ratio def forward(self, x): return autograd.dropout(x, self.ratio) class Cat(Layer): """ Generate a Cat Operator """ def __init__(self, axis=0): super(Cat, self).__init__() self.axis = axis def forward(self, xs): return autograd.cat(xs, self.axis) class Reshape(Layer): """ Generate a Reshape Operator """ def __init__(self): super(Reshape, self).__init__() def forward(self, x, shape): return autograd.reshape(x, shape) class CudnnRNN(Layer): """ `CudnnRNN` class implements with c++ backend and run the operation directly on cuDNN While `RNN` class implements with high level singa API """ def __init__(self, hidden_size, activation="tanh", num_layers=1, bias=True, batch_first=True, dropout=0, bidirectional=False, rnn_mode="lstm", use_mask=False, return_sequences=True): """ Args: hidden_size: hidden feature dim rnn_mode: accepted value: "vanilla", "tanh", "relu", "lstm", "gru" """ assert singa.USE_CUDA, "Not able to run without CUDA" assert num_layers > 0, "num layers should be > 0" assert 0 <= dropout < 1, "dropout shouldbe >=0 and <1" super(CudnnRNN, self).__init__() self.rnn_mode = rnn_mode self.hidden_size = hidden_size self.num_layers = num_layers self.dropout = dropout self.bidirectional = 1 if bidirectional else 0 self.return_sequences = return_sequences self.batch_first = batch_first self.use_mask = use_mask # GPU parameter # cudnn_rnn_mode: 0 - RNN RELU, 1 - RNN TANH, 2 - LSTM, 3 - GRU if self.rnn_mode == "lstm": self.cudnn_rnn_mode = 2 elif self.rnn_mode == "vanilla" or self.rnn_mode == "tanh": self.cudnn_rnn_mode = 1 elif self.rnn_mode == "relu": self.cudnn_rnn_mode = 0 elif self.rnn_mode == "gru": self.cudnn_rnn_mode = 3 def initialize(self, x, hx=None, cx=None, seq_lengths=None): if self.batch_first: x = x.transpose((1, 0, 2)) self.input_size = x.shape[1] # GPU handle self.handle = singa.CudnnRNNHandle(x.data, self.hidden_size, mode=self.cudnn_rnn_mode, num_layers=self.num_layers, dropout=self.dropout, bidirectional=self.bidirectional) self.W = Tensor(shape=(self.handle.weights_size,), requires_grad=True, stores_grad=True, device=x.device) k = 1 / self.hidden_size self.W.uniform(-math.sqrt(k), math.sqrt(k)) def forward(self, x, hx=None, cx=None, seq_lengths=None): self.device_check(x, self.W) if self.batch_first: # (bs,seq,data) -> (seq,bs,data) x = autograd.transpose(x, (1, 0, 2)) batch_size = x.shape[1] directions = 2 if self.bidirectional else 1 if hx == None: hx = Tensor(shape=(self.num_layers * directions, batch_size, self.hidden_size), requires_grad=False, stores_grad=False, device=x.device).set_value(0.0) if cx == None: cx = Tensor(shape=(self.num_layers * directions, batch_size, self.hidden_size), requires_grad=False, stores_grad=False, device=x.device).set_value(0.0) # outputs returned is list # inputs has shape of {sequence length, batch size, feature size} if self.use_mask: assert type(seq_lengths) == Tensor, "wrong type for seq_lengths" y = autograd._RNN(self.handle, return_sequences=self.return_sequences, use_mask=self.use_mask, seq_lengths=seq_lengths)(x, hx, cx, self.W)[0] else: y = autograd._RNN( self.handle, return_sequences=self.return_sequences, )(x, hx, cx, self.W)[0] if self.return_sequences and self.batch_first: # (seq, bs, hid) -> (bs, seq, hid) y = autograd.transpose(y, (1, 0, 2)) return y def get_params(self): return {self.W.name: self.W} def set_params(self, parameters): self.set_attribute(self.W, parameters[self.W.name]) ''' import autograd at the end to resolve circular import ''' from singa import autograd
apache/incubator-singa
python/singa/layer.py
Python
apache-2.0
58,103
[ "Gaussian" ]
777151b49600ae1962056d47c09fb3e6c86023cf476b01e2a4de9a236b4a6ccf
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function import numpy as np def p_value_to_str(p_value, permutations): """Format p-value as a string with the correct number of decimals. Number of decimals is determined by the number of permutations. Parameters ---------- p_value : float or None p-value to convert to string. permutations : int Number of permutations used to calculate `p_value`. Returns ------- str `p_value` formatted as a string with the correct number of decimals. If `p_value` is ``None`` or ``np.nan``, ``'N/A'`` is returned. If `permutations` is less than 10, a message stating insufficient number of permutations is returned. """ if p_value is None or np.isnan(p_value): result = 'N/A' elif permutations < 10: result = ('Too few permutations to compute p-value (permutations ' '= %d)' % permutations) else: decimal_places = int(np.log10(permutations + 1)) result = ('%1.' + '%df' % decimal_places) % p_value return result
JWDebelius/scikit-bio
skbio/stats/_misc.py
Python
bsd-3-clause
1,470
[ "scikit-bio" ]
e779e9e8f82c811ef0ce16c9f3c2176e2bbe95147aa1214456f97c25abc54846
''' # This script is an example of calculation of long range interactions (Coulomb interaction) using # the Ewald summation method. # # The initial data file is 'ewald.espressopp'. It contains initial information about # the system: the box size, particle id, position and charge. # # File 'ewald_result.dat' contains results which were obtained by Markus Deserno for exactly # the same system. Ewald parameter (alpha = 1.112583061), Cutoff in R space (rspacecutoff = 4.9) # cutoff in K space (kspacecutoff = 30). It compares the results of Markus Deserno with Espresso++ # implementation. The forces which affect the particles, total energy and the differences between # Deserno's results and Espresso++ implementation are printed at the end of the script. ''' # this is an auxiliary function. It reads the results of Deserno from "deserno_ewald.dat" def readingDesernoForcesFile(): # forces x,y,z fx, fy, fz = [], [], [] # energy energy = 0.0 # reading the general information file = open("ewald_result.dat") i = 0 for line in file: # energy if i==6: tmp = line.split() energy = float(tmp[0]) # forces if i>=9: line = line.replace('{','').replace('}','') tmp = line.split() fx.append(float(tmp[0])) fy.append(float(tmp[1])) fz.append(float(tmp[2])) i=i+1 return energy, fx, fy, fz # end of the function readingDesernoForcesFile # The script itself import sys import mpi4py.MPI as MPI import espressopp from espressopp import Real3D from espressopp.tools.convert import espresso_old # reading the particle coordinates, charges and box size from old espressopp data file # file 'ini_struct_deserno.dat' contains the data we need print "Reading system data:" Lx, Ly, Lz, x, y, z, type, q, vx,vy,vz,fx,fy,fz,bondpairs = espresso_old.read('ewald.espressopp') # creating the system box box = (Lx, Ly, Lz) print "System box size:", box # number of particles num_particles = len(x) print "Number of particles = ", num_particles print "The first particle has coordinates", x[0], y[0], z[0] ''' # Ewald method suppose to calculate electrostatic interaction dividing it into R space and # K space part # # alpha - Ewald parameter # rspacecutoff - the cutoff in real space # kspacecutoff - the cutoff in reciprocal space ''' alpha = 1.112583061 rspacecutoff = 4.9 kspacecutoff = 30 # seting the skin for Verlet list (it is not important here) skin = 0.09 # Coulomb prefactor parameters bjerrumlength = 1.0 temperature = 1.0 coulomb_prefactor = bjerrumlength * temperature nodeGrid = espressopp.tools.decomp.nodeGrid(MPI.COMM_WORLD.size) cellGrid = espressopp.tools.decomp.cellGrid(box, nodeGrid, rspacecutoff, skin) system = espressopp.System() system.rng = espressopp.esutil.RNG() system.bc = espressopp.bc.OrthorhombicBC(system.rng, box) system.skin = skin system.storage = espressopp.storage.DomainDecomposition(system, nodeGrid, cellGrid) # Adding the particles props = ['id', 'pos', 'type', 'q'] new_particles = [] for i in range(0, num_particles): part = [ i, Real3D(x[i], y[i], z[i]), type[i], q[i] ] new_particles.append(part) system.storage.addParticles(new_particles, *props) system.storage.decompose() ## potential and interaction ## # setting the Verlet list vl = espressopp.VerletList(system, rspacecutoff) # the R space part of electrostatic interaction according to the Ewald method ''' Creating the Coulomb potential which is responsible for the R space part according to the Ewald method. It is based on the Coulomb prefactor (coulomb_prefactor), Ewald parameter (alpha), and the cutoff in R space (rspacecutoff) ''' coulombR_pot = espressopp.interaction.CoulombRSpace(coulomb_prefactor, alpha, rspacecutoff) # creating the interaction based on the Verlet list coulombR_int = espressopp.interaction.VerletListCoulombRSpace(vl) # setting the potential for the interaction between particles of type 0 and 0 coulombR_int.setPotential(type1=0, type2=0, potential = coulombR_pot) # adding the interaction to the system system.addInteraction(coulombR_int) # k space part of electrostatic interaction according to the Ewald method ''' Creating the Coulomb potential which is responsible for the K space part according to the Ewald method. It is based on the system information (system), Coulomb prefactor (coulomb_prefactor), Ewald parameter (alpha), and the cutoff in K space (kspacecutoff) ''' ewaldK_pot = espressopp.interaction.CoulombKSpaceEwald(system, coulomb_prefactor, alpha, kspacecutoff) # creating the interaction based on the Cell list for all particle interaction and potential in K space ewaldK_int = espressopp.interaction.CellListCoulombKSpaceEwald(system.storage, ewaldK_pot) # adding the interaction to the system system.addInteraction(ewaldK_int) # creating the integrator which based on the Verlet algorithm integrator = espressopp.integrator.VelocityVerlet(system) # seting the time step (it is not important here) integrator.dt = 0.0001 # nothing will be changed in system, just forces will be calculated ones integrator.run(0) # reading Deserno results (energy and forces) energy_Deserno, forceX_Deserno, forceY_Deserno, forceZ_Deserno = readingDesernoForcesFile() # printing the particle id, force (x,y,z), and force difference (x,y,z) format0 = '\n %45s %105s \n' print (format0 % ('forces', 'the difference between Deserno\'s result and forces by Espresso++')) format1 = '%3s %20s %20s %20s %10s %20s %25s %25s\n' print (format1 % ('id', 'fx', 'fy', 'fz', ' ', 'dfx', 'dfy', 'dfz')) format2 = '%3d %3s %3.17f %3s %3.17f %3s %3.17f %10s %3.17f %3s %3.17f %3s %3.17f' for j in range(0, num_particles): print (format2 % (j, ' ', \ system.storage.getParticle(j).f.x, ' ', \ system.storage.getParticle(j).f.y, ' ', \ system.storage.getParticle(j).f.z, \ ' ', \ abs(system.storage.getParticle(j).f.x-forceX_Deserno[j]), ' ', \ abs(system.storage.getParticle(j).f.y-forceY_Deserno[j]), ' ', \ abs(system.storage.getParticle(j).f.z-forceZ_Deserno[j])) ) # calculating the R space part of electrostatic energy enR = coulombR_int.computeEnergy() # calculating the K space part of electrostatic energy enK = ewaldK_int.computeEnergy() # total energy enTot = enR + enK # printing the total energy and the difference with Deserno results print '\nTotal energy: %5.16f; The difference in energy (Deserno\'s result, Espresso++): %5.16f\n' % (enTot, enTot-energy_Deserno) sys.exit()
capoe/espressopp.soap
examples/ewald/ewald.py
Python
gpl-3.0
6,691
[ "ESPResSo" ]
4f7ddf0ef27814e09a2da7f6d6cd64446574a5fc5a60f83b9c1f6ded62551f1d
# Define a CloudFormation template to host a tiny ElasticSearch stack: # 1 ElasticSearch server # 1 Logstash indexing server # 1 Kibana server # # Template Parameters (provided at templat creation time): # - name # Name of the stack, of course. Required. # - description # Description of the stack. Please provide one. # - region # The AWS region in which this template will be executed # - bucket # The S3 bucket where configuration and deployment files are located # - vpc_id # ID of the VPC in which this stack is built # - vpc_cidr # CIDR block of the vpc # - es_subnets # List of the subnet in which the Logstash/Elasticsearch server should be built. # Don't know about the rest of these... # - kibana_subnet_ids # List of subnets in which the kibana server should be built. # - es_instance_type # Instance type of the server instances. Defaults to t2.micro # - kibana_instance_type # Instance type of the ui instances. Defaults to t2.micro # # Stack Parameters (provided to the template at stack create/update time): # # - ServerKey # Name of the key pair to use to connect to server instances # # Stack Outputs: # # - ElasticSearchASG # ID of the autoscaling group controlling the Nth cluster member # - ElasticSearchENI # ID of the elastic network interface attached to the Logstash/ElasticSearch server import troposphere as tp import troposphere.autoscaling as asg import troposphere.cloudformation as cf import troposphere.ec2 as ec2 import troposphere.elasticloadbalancingv2 as elb2 import troposphere.iam as iam from scaffold.cf.template import TemplateBuilder, asgtag, AMI_REGION_MAP_NAME, REF_REGION, REF_STACK_NAME from scaffold.cf import net from scaffold.cf import AmiRegionMap from scaffold.iam import service_role_policy_doc from .tiny_userdata import ESUserdata, LogstashUserdata from .tiny_initconfig import ESInitConfig, LogstashInitConfig AMI_REGION_MAP = { 'us-east-1': {'ES': 'ami-60b6c60a', 'LOGSTASH': 'ami-60b6c60a', 'KIBANA': 'ami-60b6c60a'}, 'us-west-1': {'ES': 'ami-d5ea86b5', 'LOGSTASH': 'ami-d5ea86b5', 'KIBANA': 'ami-d5ea86b5'}, 'us-west-2': {'ES': 'ami-f0091d91', 'LOGSTASH': 'ami-f0091d91', 'KIBANA': 'ami-f0091d91'} # 'eu-west-1' # 'eu-central-1' # 'sa-east-1' # 'ap-southeast-1' # 'ap-southeast-2' # 'ap-northeast-1' # 'ap-northeast-2' } class TinyElkTemplate(TemplateBuilder): BUILD_PARM_NAMES = ['vpc_id', 'vpc_cidr', 'es_subnets'] SERVER_KEY_PARM_NAME = 'ServerKey' def __init__(self, name, region, bucket, bucket_key_prefix, vpc_id, vpc_cidr, es_subnets, create_logstash=False, description='[REPLACEME]'): super(TinyElkTemplate, self).__init__(name, description, TinyElkTemplate.BUILD_PARM_NAMES) self.region = region self.bucket = bucket self.bucket_key_prefix = bucket_key_prefix self.vpc_id = vpc_id self.vpc_cidr = vpc_cidr self.es_subnets = es_subnets def internal_add_mappings(self): self.add_mapping(AMI_REGION_MAP_NAME, AmiRegionMap(AMI_REGION_MAP)) def internal_build_template(self): self.create_parameters() self._create_common() self.create_elasticsearch() self.create_kibana() if self.create_logstash: self.create_logstash() def create_parameters(self): self.add_parameter(tp.Parameter(TinyElkTemplate.SERVER_KEY_PARM_NAME, Type='String')) def _create_common(self): self.ssh_sg = self._create_simple_sg('ElkSSHSecurityGroup', 'Security Group for accessing Elk stack instances', net.SSH) def _create_simple_sg(self, name, description, port_ranges): if type(port_ranges) is not list: port_ranges = [port_ranges] rules = [net.sg_rule(self.vpc_cidr, port, net.TCP) for port in port_ranges] sg = ec2.SecurityGroup(name, GroupDescription=description, SecurityGroupIngress=rules, VpcId=self.vpc_id, Tags=self.default_tags) self.add_resource(sg) return sg def create_elasticsearch(self): es_sg = self._create_es_sg() es_tg = self._create_es_target_group() self.es_elb = self._create_es_elb(es_tg) self._create_es_asg(es_sg, es_tg) def _create_es_sg(self): return self._create_simple_sg('ElasticsearchSecurityGroup', 'Security Group for Elasticsearch nodes', (9200, 9400)) def _create_es_target_group(self): target_group = elb2.TargetGroup('ElasticsearchTargetGroup', HealthCheckIntervalSeconds=60, HealthCheckPath='/_cluster/health', HealthCheckPort=9200, HealthCheckProtocol='HTTP', HealthCheckTimeoutSeconds=5, HealthyThresholdCount=2, UnhealthyThresholdCount=2, Matcher=elb2.Matcher(HttpCode='200-299'), Name='ElasticsearchTiny', Port=9200, Protocol='HTTP', Tags=self.default_tags, VpcId=self.vpc_id) self.add_resource(target_group) return target_group def _create_es_elb(self, target_group): sg = ec2.SecurityGroup('ElasticsearchELBSecurityGroup', GroupDescription='Security Group for the Elasticsearch ELB', SecurityGroupIngress=[net.sg_rule(self.vpc_cidr, 9200, net.TCP)], VpcId=self.vpc_id, Tags=self.default_tags) elb = elb2.LoadBalancer('ElasticsearchELB', Name='ElasticsearchTiny', Scheme='internal', SecurityGroups=[tp.Ref(sg)], Subnets=self.es_subnets, Tags=self.default_tags) listener = elb2.Listener('ElasticsearchELBListener', DefaultActions=[elb2.Action(TargetGroupArn=tp.Ref(target_group), Type='forward')], LoadBalancerArn=tp.Ref(elb), Port=9200, Protocol='HTTP') self.add_resources(sg, elb, listener) self.output(elb) self.output_named('ElasticsearchDNSName', tp.GetAtt(elb.title, 'DNSName')) return elb def _create_es_asg(self, sg, target_group): asg_name = 'ElasticsearchASG' lc = asg.LaunchConfiguration('ElasticsearchLC', ImageId=tp.FindInMap(AMI_REGION_MAP_NAME, REF_REGION, 'ES'), InstanceType='t2.micro', # TODO: how should we parameterize this? IamInstanceProfile=tp.Ref(self._create_es_iam_profile()), SecurityGroups=[tp.Ref(sg), tp.Ref(self.ssh_sg)], KeyName=tp.Ref(TinyElkTemplate.SERVER_KEY_PARM_NAME), InstanceMonitoring=False, AssociatePublicIpAddress=False, UserData=self._create_es_userdata(asg_name)) group = asg.AutoScalingGroup(asg_name, MinSize=1, MaxSize=1, LaunchConfigurationName=tp.Ref(lc), TargetGroupARNs=[tp.Ref(target_group)], VPCZoneIdentifier=self.es_subnets, Tags=asgtag(self._rename('{} Elasticsearch')), Metadata=self._create_es_initconfig()) self.add_resources(lc, group) self.output(group) return group def _create_es_iam_profile(self): role = iam.Role('ElasticsearchInstanceRole', AssumeRolePolicyDocument=service_role_policy_doc.ec2, Policies=[ iam.Policy( PolicyName='ElasticsearchInstance', PolicyDocument={ 'Statement': [{ 'Effect': 'Allow', 'Resource': 'arn:aws:s3:::{}/*'.format(self.bucket), 'Action': ['s3:Get*'] }] } ) ]) profile = iam.InstanceProfile('ElasticsearchInstanceProfile', Path='/', Roles=[tp.Ref(role)]) self.add_resources(role, profile) return profile def _create_es_userdata(self, resource_name): items = ESUserdata(REF_STACK_NAME, resource_name, ['default'], REF_REGION).items() return tp.Base64(tp.Join('', items)) def _create_es_initconfig(self): init = ESInitConfig() return cf.Init( cf.InitConfigSets( default=['elasticsearch'] ), elasticsearch=cf.InitConfig( packages=init.packages(), files=init.files(), services=init.services() ) ) def create_logstash(self): ls_sg = self._create_ls_sg() ls_eni = self._create_ls_eni(ls_sg) self._create_ls_asg(ls_eni) def _create_ls_sg(self): return self._create_simple_sg('LogstashIndexSG', 'Security Group for Logstash indexing nodes', 5044) def _create_ls_eni(self, sg): eni = ec2.NetworkInterface('LogstashIndexENI', Description='ENI for the Logstash indexer', GroupSet=[tp.Ref(sg)], SourceDestCheck=True, SubnetId=self.es_subnets[0], # TODO: is there a better way to allocate? I dunno. Tags=self.default_tags) self.add_resource(eni) self.output(eni) return eni def _create_ls_asg(self, eni): asg_name = 'LogstashIndexASG' lc = asg.LaunchConfiguration('LogstashIndexLC', ImageId=tp.FindInMap(AMI_REGION_MAP_NAME, REF_REGION, 'LOGSTASH'), InstanceType='t2.micro', # TODO: how should we parameterize this? IamInstanceProfile=tp.Ref(self._create_ls_iam_profile()), SecurityGroups=[tp.Ref(self.ssh_sg)], KeyName=tp.Ref(TinyElkTemplate.SERVER_KEY_PARM_NAME), InstanceMonitoring=False, AssociatePublicIpAddress=False, UserData=self._create_ls_userdata(asg_name, eni)) group = asg.AutoScalingGroup(asg_name, MinSize=1, MaxSize=1, LaunchConfigurationName=tp.Ref(lc), VPCZoneIdentifier=[eni.SubnetId], Tags=asgtag(self._rename('{} Logstash')), Metadata=self._create_ls_initconfig()) self.add_resources(lc, group) self.output(group) return group def _create_ls_iam_profile(self): role = iam.Role('LogstashInstanceRole', AssumeRolePolicyDocument=service_role_policy_doc.ec2, Policies=[ iam.Policy( PolicyName='LogstashInstance', PolicyDocument={ 'Statement': [{ 'Effect': 'Allow', 'Resource': 'arn:aws:s3:::{}/*'.format(self.bucket), 'Action': ['s3:Get*'] }, { 'Effect': 'Allow', 'Resource': '*', 'Action': ['ec2:Attach*', 'ec2:Describe*'] }] } ) ]) profile = iam.InstanceProfile('LogstashInstanceProfile', Path='/', Roles=[tp.Ref(role)]) self.add_resources(role, profile) return profile def _create_ls_userdata(self, resource_name, eni): userdata = LogstashUserdata(eni_id=tp.Ref(eni), es_host_ref=tp.GetAtt(self.es_elb.title, 'DNSName'), stack_ref=REF_STACK_NAME, resource_name=resource_name, configsets=['default'], region=REF_REGION) return tp.Base64(tp.Join('', userdata.items())) def _create_ls_initconfig(self): init = LogstashInitConfig(self.bucket, self.bucket_key_prefix) return cf.Init( cf.InitConfigSets( default=['logstash'] ), logstash=cf.InitConfig( packages=init.packages(), files=init.files(), commands=init.commands(), services=init.services() ) ) def create_kibana(self): pass if __name__ == '__main__': t = TinyElkTemplate('Testing', region='us-west-2', bucket='my_bucket', bucket_key_prefix='my_bucket_prefix', vpc_id='vpc-deadbeef', vpc_cidr='10.0.0.0/16', es_subnets=['subnet-deadbeef', 'subnet-cab4abba'], create_logstash=False, description='Testing') t.build_template() print(t.to_json())
mccormickmichael/laurel
app/elk/tiny_template.py
Python
unlicense
14,862
[ "Elk" ]
2b1d87caba4fbebc4195a0c96ed86a115310d1fa2f4956ee8c12fca531d32ddd
import numpy as np import torch from torch.autograd import Variable import torch.nn as nn from rllab.misc.overrides import overrides from pytorchrl.core.parameterized import Parameterized from pytorchrl.distributions.diagonal_gaussian import DiagonalGaussian from pytorchrl.policies.base import StochasticPolicy class GaussianMLPPolicy(StochasticPolicy, Parameterized): """ Stochastic policy as Gaussian distribution. """ def __init__( self, observation_dim, action_dim, hidden_sizes=(32, 32), adaptive_std=True, std_based_on_state=False, init_std=1.0, std_share_network=False, std_hidden_size=(32, 32), min_std=1e-6, hidden_nonlinearity=nn.Tanh, std_hidden_nonlinearity=nn.Tanh, output_nonlinearity=None, dist_cls=DiagonalGaussian, ): """ Create Policy Network Parameters ---------- adaptive_std (bool): Whether to change std of the network, if false, std will always be init_std. std_based_on_state (bool): Whether std is a function of state, std = func(state), or just a array of numbers. This option is only effective is adaptive_std is True. init_std (float): Initial std. This only effective if std_based_on_state if False. std_share_network (bool): Whether share the network parameter, if this is true, the mean and std is only separate at the last layer. Otherwise, std and mean have two different network. """ super(GaussianMLPPolicy, self).__init__() self.observation_dim = int(observation_dim) self.action_dim = int(action_dim) self.adaptive_std = adaptive_std self.std_share_network = std_share_network self.init_std = init_std self.std_based_on_state = std_based_on_state self.min_std = min_std sizes = [self.observation_dim] + list(hidden_sizes) std_hidden_size = [self.observation_dim] + list(std_hidden_size) # Create the tensor has the same shape as action init_std_tensor = torch.Tensor(self.action_dim).fill_(init_std) if adaptive_std: if self.std_based_on_state: if self.std_share_netowrk: self.model, self.mean_model, self.log_std_model = \ self.define_shared_network(sizes, hidden_nonlinearity, output_nonlinearity) else: self.mean_model = self.define_single_network(sizes, hidden_nonlinearity, output_nonlinearity) self.log_std_model = self.define_single_network( std_hidden_size, std_hidden_nonlinearity, output_nonlinearity=None) else: self.mean_model = self.define_single_network(sizes, hidden_nonlinearity, output_nonlinearity) self.log_std_model = nn.Parameter(init_std_tensor) else: self.mean_model = self.define_single_network(sizes, hidden_nonlinearity, output_nonlinearity) self.log_std_model = Variable(init_std_tensor) self.dist_cls = dist_cls def define_shared_network(self, sizes, hidden_nonlinearity, output_nonlinearity): """ Define the network output both mean and log_std of the policy with shared parameters. Parameters ---------- sizes (list): A list of integer specify the size of each layer from input to last hidden layer. output_nonlinearity: #TODO (ewei) Returns ------- model (nn.Module): A Module take input and output the Variable of last hidden layer mean (nn.Module): A layer take the last hidden layer output and produce the mean of the policy log_std (nn.Module): A layer take the last hidden layer output and produce the log std of the policy. """ # Create the base model submodules = [] for index, size in enumerate(sizes): if index != len(sizes) - 1: submodules.append(nn.Linear(size, sizes[index + 1])) submodules.append(hidden_nonlinearity()) model = nn.Sequential(*submodules) # Create the layer for means mean_modules = [] last_hidden_size = sizes[len(sizes) - 1] mean_modules.append(nn.Linear(last_hidden_size, self.action_dim)) if output_nonlinearity is not None: mean_modules.append(output_nonlinearity()) means = nn.Sequential(*mean_modules) # Create the layer for log stds log_stds = nn.Linear(last_hidden_size, self.action_dim) return model, means, log_stds def define_single_network(self, sizes, hidden_nonlinearity, output_nonlinearity): """ Define a single input - single output network (thus, no shared part). Parameters ---------- sizes (list): hidden_nonlinearity (): output_nonlinearity (): """ submodules = [] for index, size in enumerate(sizes): if index != len(sizes) - 1: submodules.append(nn.Linear(size, sizes[index + 1])) submodules.append(hidden_nonlinearity()) last_hidden_size = sizes[len(sizes) - 1] submodules.append(nn.Linear(last_hidden_size, self.action_dim)) if output_nonlinearity is not None: submodules.append(output_nonlinearity()) model = nn.Sequential(*submodules) return model def forward(self, observations): """ Return action for given state Parameters ---------- observations (Variable): state wrapped in Variable Returns ------- means (Variable): mean of the gaussian policy log_stds (Variable): log of std of the gaussian policy """ if self.adaptive_std: if self.std_based_on_state: if self.std_share_netowrk: last_hidden = self.model(observations) means = self.mean_model(last_hidden) log_stds = self.log_std_model(last_hidden) else: means = self.mean_model(observations) log_stds = self.log_std_model(observations) else: means = self.mean_model(observations) # Expand the log_stds log_stds = self.log_std_model.expand_as(means) else: means = self.mean_model(observations) # Expand the log_stds log_stds = self.log_std_model.expand_as(means) # Set the minimum log_std if self.min_std is not None: min_log_std = Variable(torch.Tensor( np.log([self.min_std]))).type(torch.FloatTensor) # max operation requires two variables log_stds = torch.max(log_stds, min_log_std) return means, log_stds @overrides def get_action(self, observation): """ Get observation and return the action for the observation. Parameters ---------- observation (numpy.ndarray): current observation. Return ------ action (numpy.ndarray): action for the observation. agent_info (dict): Additional info for the agent """ # Need to first convert observation into Variable # We do not need to call backward in get_action method # Thus, we set volatile to True. obs_variable = Variable(torch.from_numpy(observation), volatile=True).type(torch.FloatTensor) means_variable, log_stds_variable = self.forward(obs_variable) means = means_variable.data.numpy() log_stds = log_stds_variable.data.numpy() rnd = np.random.normal(size=means.shape) actions = rnd * np.exp(log_stds) + means return actions, dict(mean=means, log_std=log_stds) def get_actions(self, observations): """ Get observation and returnt the actions for the observations. This is the batch version of the get_action method. If the input observations is of size n * obs_dim, where n is the batch size, and obs_dim is the dimension of the observation, then the actions, means, and log_stds in the return values is of size n * act_dim, where act_dim is the size of action dimension. Parameters ---------- observations (numpy.ndarray): current observation. Returns ------- actions (numpy.ndarray): actions for the observations. agent_infos (dict): Additional info for the agent """ obs_variable = Variable(torch.from_numpy(observations), volatile=True).type(torch.FloatTensor) means_variable, log_stds_variable = self.forward(obs_variable) means = means_variable.data.numpy() log_stds = log_stds_variable.data.numpy() rnd = np.random.normal(size=means.shape) actions = rnd * np.exp(log_stds) + means return actions, dict(mean=means, log_std=log_stds) @overrides def get_internal_params(self): return self.parameters() @overrides def get_internal_named_params(self): return self.named_parameters() def get_policy_distribution(self, obs_var): """ Return the distribution of this policy based on observation. This is different from the method 'distribution' in that, we need to do a forward pass to get mean and log_stds using the neural network. Parameters ---------- obs_var (Variable): Returns ------- distribution (DiagonalGaussian): """ means_variable, log_stds_variable = self.forward(obs_var) return self.dist_cls.from_dict(means_variable, log_stds_variable) def distribution(self, dist_info): """ Return the distribution of this policy based on the provided info. No forward pass is needed. Parameters ---------- dist_info (dict): Returns ------- distribution (DiagonalGaussian): """ means = dist_info['mean'] log_stds = dist_info['log_std'] if isinstance(means, np.ndarray): means = Variable(torch.from_numpy(means)).type(torch.FloatTensor) if isinstance(log_stds, np.ndarray): log_stds = Variable(torch.from_numpy(log_stds)).type(torch.FloatTensor) return self.dist_cls.from_dict(means, log_stds)
nosyndicate/pytorchrl
pytorchrl/policies/gaussian_mlp_policy.py
Python
mit
10,812
[ "Gaussian" ]
8b10a87fb022c0f7f2d521e86f9755427a6a6fc2ce431137461d49e9a8374d42
from __future__ import print_function import argparse import os import random from collections import defaultdict import pysam import mirtop.libs.logger as mylog import mirtop.libs.do as runner def _read_fasta(fa, size): source = dict() with open(fa) as inh: for line in inh: if line.startswith(">"): name = line.strip().split()[0].replace(">", "") else: if len(line.strip()) >= size: source.update({name: line.strip()[0:size]}) return source def _update_ends(source): nts = ["A", "T", "C", "G"] start_idx = 0 end_idx = 0 for name in source: source[name] = nts[start_idx] + source[name] + nts[end_idx] if end_idx == 3 and start_idx == 3: end_idx = -1 start_idx = 0 if end_idx == 3: start_idx += 1 end_idx = 0 end_idx += 1 return source def _write_fasta(sequences, filename): with open(filename, 'w') as outh: for name in sequences: if sequences[name]: print(">%s\n%s" % (name, sequences[name]), file=outh) return filename def _parse_hits(sam, source): uniques = defaultdict(list) # read sequences and score hits (ignore same sequence) handle = pysam.Samfile(sam, "rb") for line in handle: reference = handle.getrname(line.reference_id) name = line.query_name # sequence = line.query_sequence if not line.is_reverse else reverse_complement(line.query_sequence) if reference == name: continue # print([reference, name, line.get_tag("NM")]) distance = line.get_tag("NM") uniques[name].append(distance) uniques[reference].append(distance) # read parsed data and keep the ones with score > 10 edit distance for name in uniques: if min(uniques[name]) < 4: if name in source: source[name] = None return source parser = argparse.ArgumentParser() parser.add_argument("--fa", help="File with mature sequences.", required=True) parser.add_argument("-s", "--size", default=22, help="Size of spike-ins to generate.") parser.add_argument("-n", "--number", default=16, help="Number of spike-ins to generate.") parser.add_argument("-o", "--out", default="spikeins.fa", help="Name used for output files.") parser.add_argument("--seed", help="set up seed for reproducibility.", default=42) parser.add_argument("--universe", help="Set up universe sequences to avoid duplication.", default=None) args = parser.parse_args() random.seed(args.seed) mylog.initialize_logger(os.path.dirname(os.path.abspath(args.out))) logger = mylog.getLogger(__name__) # Read file to get all sequences longer than size - 2 size = args.size - 2 source = _read_fasta(args.fa, size) logger.info("%s was read: %s sequences were loaded" % (args.fa, len(source))) source = _update_ends(source) logger.info("source updated with extended nts: %s" % source) # Map all vs all with razers3 modified = _write_fasta(source, os.path.join(os.path.dirname(args.out), "modified.fa")) sam = os.path.join(os.path.dirname(args.out), "modified.bam") runner.run(("razers3 -i 75 -rr 80 -f -so 1 -o {output} {target} {query}").format(output=sam, target=modified, query=modified)) uniques = _parse_hits(sam, source) print(uniques) if args.universe: sam = os.path.join(os.path.dirname(args.out), "modified_vs_universe.sam") runner.run(("razers3 -i 75 -rr 80 -f -o {output} {target} {query}").format(output=sam, target=args.universe, query=modified)) uniques = _parse_hits(sam, uniques) print(uniques) # Write uniques to fasta _write_fasta(uniques, args.out)
miRTop/mirtop
scripts/make_spikeins.py
Python
mit
3,822
[ "pysam" ]
4ec1a3d6cd8a16f3fb1842c6af2a91150a02fe02ce01a3c81f8e436b72f1ddc1
def sextract(filter): from config_bonn import appendix, cluster, tag, arc, filter_root import utilities import os, re, bashreader, sys, string from glob import glob from copy import copy dict = bashreader.parseFile('progs.ini') for key in dict.keys(): os.environ[key] = str(dict[key]) TEMPDIR = '/tmp/' PHOTCONF = './photconf/' path='/nfs/slac/g/ki/ki05/anja/SUBARU/%(cluster)s/' % {'cluster':cluster} search_params = {'path':path, 'cluster':cluster, 'filter':filter, 'appendix':appendix, 'PHOTCONF':PHOTCONF, 'tag':tag, 'DATACONF':os.environ['DATACONF'], 'TEMPDIR':TEMPDIR,'fwhm':1.00} searchstr = "/%(path)s/*%(filter)s*/SCIENCE/*fits" % search_params print searchstr files = glob(searchstr) files.sort() print files exposures = {} # first 30 files print files[0:30] for file in files: #[0:30]: if string.find(file,'wcs') == -1 and string.find(file,'.sub.fits') == -1: res = re.split('_',re.split('/',file)[-1]) print res if not exposures.has_key(res[0]): exposures[res[0]] = {} if not exposures[res[0]].has_key('images'): exposures[res[0]]['images'] = [] if not exposures[res[0]].has_key('keywords'): exposures[res[0]]['keywords'] = {} exposures[res[0]]['images'].append(file) # res[0] is the root of the image name print 'hey', file reload(utilities) if not exposures[res[0]]['keywords'].has_key('ROTATION'): #if exposure does not have keywords yet, then get them exposures[res[0]]['keywords']['filter'] = filter res2 = re.split('/',file) for r in res2: if string.find(r,filter) != -1: print r exposures[res[0]]['keywords']['date'] = r.replace(filter + '_','') exposures[res[0]]['keywords']['fil_directory'] = r search_params['fil_directory'] = r kws = utilities.get_header_kw(file,['ROTATION','OBJECT']) # return KEY/NA if not SUBARU for kw in kws.keys(): exposures[res[0]]['keywords'][kw] = kws[kw] print 'hey2!!!!!!' print exposures #first = exposures[exposures.keys()[0]] #first['images'] = [first['images'][0]] #exposures = {exposures.keys()[0]: first} #exp_tmp = {} #for exposure in exposures.keys()[0:2]: # exp_tmp[exposure] = exposures[exposure] #exposures = exp_tmp exposures = {exposures.keys()[0]: exposures[exposures.keys()[0]]} print exposures print 'stop1' #temporary method for kw in exposures.keys(): # now go through exposure by exposure exposure = exposures[kw] print kw, exposure['images'] children = [] print exposure['images'] print 'hey!!!!!!' for image in exposure['images']: child = os.fork() if child: children.append(child) else: params = copy(search_params) params['GAIN'] = 1.000 #float(exposure['keywords']['GAIN']) params['PIXSCALE'] = float(exposure['keywords']['PIXSCALE']) ROOT = re.split('\.',re.split('\/',image)[-1])[0] params['ROOT'] = ROOT NUM = re.split('O',re.split('\_',ROOT)[1])[0] params['NUM'] = NUM print ROOT weightim = "/%(path)s/%(fil_directory)s/WEIGHTS/%(ROOT)s.weight.fits" % params #flagim = "/%(path)s/%(fil_directory)s/WEIGHTS/globalflag_%(NUM)s.fits" % params #finalflagim = TEMPDIR + "flag_%(ROOT)s.fits" % params params['finalflagim'] = weightim #os.system('rm ' + finalflagim) #command = "ic -p 16 '1 %2 %1 0 == ?' " + weightim + " " + flagim + " > " + finalflagim print command #raw_input() #utilities.run(command) command = "sex /%(path)s/%(fil_directory)s/SCIENCE/%(ROOT)s.fits -c %(PHOTCONF)s/singleastrom.conf.sex \ -FLAG_IMAGE ''\ -FLAG_TYPE MAX\ -CATALOG_NAME %(TEMPDIR)s/seeing_%(ROOT)s.cat \ -FILTER_NAME %(PHOTCONF)s/default.conv\ -CATALOG_TYPE 'ASCII' \ -DETECT_MINAREA 8 -DETECT_THRESH 8.\ -ANALYSIS_THRESH 8 \ -WEIGHT_IMAGE /%(path)s/%(fil_directory)s/WEIGHTS/%(ROOT)s.weight.fits\ -WEIGHT_TYPE MAP_WEIGHT\ -PARAMETERS_NAME %(PHOTCONF)s/singleastrom.ascii.flag.sex" % params print command os.system(command) sys.exit(0) for child in children: os.waitpid(child,0) command = 'cat ' + TEMPDIR + 'seeing_' + kw + '*cat > ' + TEMPDIR + 'paste_seeing_' + kw + '.cat' utilities.run(command) file_seeing = TEMPDIR + '/paste_seeing_' + kw + '.cat' PIXSCALE = float(exposure['keywords']['PIXSCALE']) reload(utilities) print file_seeing, kw, PIXSCALE, exposure['keywords']['PIXSCALE'] fwhm = utilities.calc_seeing(file_seeing,10,PIXSCALE) # get the CRPIX values for #image = exposure['images'][0] start = 1 for image in exposure['images']: print image res = re.split('\_\d+',re.split('\/',image)[-1]) #print res imroot = "/%(path)s/%(fil_directory)s/SCIENCE/" % search_params im = imroot + res[0] + '_1' + res[1] #print im crpix = utilities.get_header_kw(image,['CRPIX1','CRPIX2','NAXIS1','NAXIS2']) if start == 1: crpixzero = copy(crpix) crpixhigh = copy(crpix) start = 0 from copy import copy if float(crpix['CRPIX1']) > float(crpixzero['CRPIX1']) and float(crpix['CRPIX2']) > float(crpixzero['CRPIX2']): crpixzero = copy(crpix) if float(crpix['CRPIX1']) < float(crpixhigh['CRPIX1']) and float(crpix['CRPIX2']) < float(crpixhigh['CRPIX2']): crpixhigh = copy(crpix) print crpix, crpixzero, crpixhigh LENGTH1 = abs(float(crpixhigh['CRPIX1']) - float(crpixzero['CRPIX1'])) + float(crpix['NAXIS1']) LENGTH2 = abs(float(crpixhigh['CRPIX2']) - float(crpixzero['CRPIX2'])) + float(crpix['NAXIS2']) print crpixhigh['CRPIX1'], crpixzero['CRPIX1'], crpix['NAXIS1'], crpix['NAXIS2'] #raw_input() children = [] for image in exposure['images']: child = os.fork() if child: children.append(child) else: params = copy(search_params) params['fwhm'] = fwhm params['GAIN'] = 1.000 #float(exposure['keywords']['GAIN']) params['PIXSCALE'] = float(exposure['keywords']['PIXSCALE']) ROOT = re.split('\.',re.split('\/',image)[-1])[0] params['ROOT'] = ROOT NUM = re.split('O',re.split('\_',ROOT)[1])[0] params['NUM'] = NUM print ROOT finalflagim = TEMPDIR + "flag_%(ROOT)s.fits" % params weightim = "/%(path)s/%(fil_directory)s/WEIGHTS/%(ROOT)s.weight.fits" % params #flagim = "/%(path)s/%(fil_directory)s/WEIGHTS/globalflag_%(NUM)s.fits" % params #finalflagim = TEMPDIR + "flag_%(ROOT)s.fits" % params params['finalflagim'] = weightim im = "/%(path)s/%(fil_directory)s/SCIENCE/%(ROOT)s.fits" % params crpix = utilities.get_header_kw(im,['CRPIX1','CRPIX2']) command = "sex /%(path)s/%(fil_directory)s/SCIENCE/%(ROOT)s.fits -c %(PHOTCONF)s/phot.conf.sex \ -PARAMETERS_NAME %(PHOTCONF)s/phot.param.sex \ -CATALOG_NAME %(TEMPDIR)s/%(ROOT)s.cat \ -FILTER_NAME %(DATACONF)s/default.conv\ -FILTER Y \ -FLAG_TYPE MAX\ -FLAG_IMAGE ''\ -SEEING_FWHM %(fwhm).3f \ -DETECT_MINAREA 10 -DETECT_THRESH 10 -ANALYSIS_THRESH 10 \ -MAG_ZEROPOINT 27.0 \ -GAIN %(GAIN).3f \ -WEIGHT_IMAGE /%(path)s/%(fil_directory)s/WEIGHTS/%(ROOT)s.weight.fits\ -WEIGHT_TYPE MAP_WEIGHT" % params #-CHECKIMAGE_TYPE BACKGROUND,APERTURES,SEGMENTATION\ #-CHECKIMAGE_NAME /%(path)s/%(fil_directory)s/PHOTOMETRY/coadd.background.fits,/%(path)s/%(fil_directory)s/PHOTOMETRY/coadd.apertures.fits,/%(path)s/%(fil_directory)s/PHOTOMETRY/coadd.segmentation.fits\ catname = "%(TEMPDIR)s/%(ROOT)s.cat" % params print command utilities.run(command,[catname]) import commands lines = commands.getoutput('ldactoasc -s -b -i ' + catname + ' -t LDAC_OBJECTS | wc -l') import re res = re.split('\n',lines) print lines if int(res[-1]) == 0: sys.exit(0) command = 'scamp ' + catname + " -SOLVE_PHOTOM N -ASTREF_CATALOG SDSS-R6 -CHECKPLOT_TYPE NONE -WRITE_XML N " print command utilities.run(command) headfile = "%(TEMPDIR)s/%(ROOT)s.head" % params hf = open(headfile,'r').readlines() hdict = {} for line in hf: import re if string.find(line,'=') != -1: res = re.split('=',line) name = res[0].replace(' ','') res = re.split('/',res[1]) value = res[0].replace(' ','') print name, value hdict[name] = value imfix = "/tmp/%(ROOT)s.fixwcs.fits" % params command = "cp " + im + " " + imfix utilities.run(command) for name in ['CRVAL1','CRVAL2','CD1_1','CD1_2','CD2_1','CD2_2','CRPIX1','CRPIX1']: command = 'sethead ' + imfix + ' ' + name + '=' + hdict[name] print command os.system(command) command = "sex /tmp/%(ROOT)s.fixwcs.fits -c %(PHOTCONF)s/phot.conf.sex \ -PARAMETERS_NAME %(PHOTCONF)s/phot.param.sex \ -CATALOG_NAME %(TEMPDIR)s/%(ROOT)s.fixwcs.cat \ -FILTER_NAME %(DATACONF)s/default.conv\ -FILTER Y \ -FLAG_TYPE MAX\ -FLAG_IMAGE ''\ -SEEING_FWHM %(fwhm).3f \ -DETECT_MINAREA 5 -DETECT_THRESH 5 -ANALYSIS_THRESH 5 \ -MAG_ZEROPOINT 27.0 \ -GAIN %(GAIN).3f \ -WEIGHT_IMAGE /%(path)s/%(fil_directory)s/WEIGHTS/%(ROOT)s.weight.fits\ -WEIGHT_TYPE MAP_WEIGHT" % params #-CHECKIMAGE_TYPE BACKGROUND,APERTURES,SEGMENTATION\ #-CHECKIMAGE_NAME /%(path)s/%(fil_directory)s/PHOTOMETRY/coadd.background.fits,/%(path)s/%(fil_directory)s/PHOTOMETRY/coadd.apertures.fits,/%(path)s/%(fil_directory)s/PHOTOMETRY/coadd.segmentation.fits\ catname = "%(TEMPDIR)s/%(ROOT)s.cat" % params print command utilities.run(command,[catname]) command = 'ldacconv -b 1 -c R -i ' + TEMPDIR + params['ROOT'] + '.fixwcs.cat -o ' + TEMPDIR + params['ROOT'] + '.conv' print command utilities.run(command) # Xpos_ABS is difference of CRPIX and zero CRPIX command = 'ldaccalc -i ' + TEMPDIR + params['ROOT'] + '.conv -o ' + TEMPDIR + params['ROOT'] + '.newpos -t OBJECTS -c "(Xpos + ' + str(float(crpixzero['CRPIX1']) - float(crpix['CRPIX1'])) + ');" -k FLOAT -n Xpos_ABS "" -c "(Ypos + ' + str(float(crpixzero['CRPIX2']) - float(crpix['CRPIX2'])) + ');" -k FLOAT -n Ypos_ABS "" -c "(Ypos*0 + ' + str(params['NUM']) + ');" -k FLOAT -n CHIP "" ' #command = 'ldaccalc -i ' + TEMPDIR + params['ROOT'] + '.conv -o ' + TEMPDIR + params['ROOT'] + '.newpos -t OBJECTS -c "(' + str(crpix['CRPIX1']) + ' - Xpos);" -k FLOAT -n Xpos_ABS "" -c "(' + str(crpix['CRPIX2']) + ' - Ypos);" -k FLOAT -n Ypos_ABS "" -c "(Ypos*0 + ' + str(params['NUM']) + ');" -k FLOAT -n CHIP "" ' print command utilities.run(command) sys.exit(0) for child in children: #print 'waiting for' child os.waitpid(child,0) from glob import glob outcat = TEMPDIR + 'tmppaste_' + kw + '.cat' newposlist = glob(TEMPDIR + kw + '*newpos') if len(newposlist) > 1: command = 'ldacpaste -i ' + TEMPDIR + kw + '*newpos -o ' + outcat print command else: command = 'cp ' + newposlist[0] + ' ' + outcat utilities.run(command) os.system('ldactoasc -i ' + outcat + ' -b -s -k MAG_APER MAGERR_APER -t OBJECTS > /tmp/' + kw + 'aper') os.system('asctoldac -i /tmp/' + kw + 'aper -o /tmp/' + kw + 'cat1 -t OBJECTS -c ./photconf/MAG_APER.conf') outfinal = TEMPDIR + 'paste_' + kw + '.cat' os.system('ldacjoinkey -i ' + outcat + ' -p /tmp/' + kw + 'cat1 -o ' + outfinal + ' -k MAG_APER1 MAG_APER2 MAGERR_APER1 MAGERR_APER2') exposures[kw]['pasted_cat'] = outfinal return exposures, LENGTH1, LENGTH2 def match(exposures): import os from config_bonn import cluster print exposures sdsscat ='/nfs/slac/g/ki/ki05/anja/SUBARU/%(cluster)s/PHOTOMETRY/sdss.cat' % {'cluster':cluster} for exposure in exposures.keys(): print exposure + 'aa' catalog = exposures[exposure]['pasted_cat'] print catalog outcat = '/tmp/matched_' + exposure + '.cat' command = 'match_simple.sh ' + catalog + ' ' + sdsscat + ' ' + outcat print command os.system(command) exposures[exposure]['matched_cat'] = outcat return exposures def match_simple(exposures,cluster): import os print exposures starcat ='/nfs/slac/g/ki/ki05/anja/SUBARU/%(cluster)s/PHOTOMETRY/sdssstar.cat' % {'cluster':cluster} galaxycat ='/nfs/slac/g/ki/ki05/anja/SUBARU/%(cluster)s/PHOTOMETRY/sdssgalaxy.cat' % {'cluster':cluster} path='/nfs/slac/g/ki/ki05/anja/SUBARU/%(cluster)s/' % {'cluster':cluster} illum_path='/nfs/slac/g/ki/ki05/anja/SUBARU/ILLUMINATION/' % {'cluster':cluster} #os.system('mkdir -p ' + path + 'PHOTOMETRY/ILLUMINATION/') os.system('mkdir -p ' + path + 'PHOTOMETRY/ILLUMINATION/STAR/') os.system('mkdir -p ' + path + 'PHOTOMETRY/ILLUMINATION/GALAXY/') from glob import glob if len(glob(starcat)) == 0: image = exposures[exposures.keys()[0]]['images'][0] print image command = 'python retrieve_test.py ' + image + ' ' + starcat print command os.system(command) for exposure in exposures.keys(): print exposure + 'aa' catalog = exposures[exposure]['pasted_cat'] filter = exposures[exposure]['keywords']['filter'] print catalog outcat = '/tmp/matched.cat' command = 'match_simple.sh ' + catalog + ' ' + starcat + ' ' + outcat print command os.system(command) exposures[exposure]['matched_cat'] = outcat os.system('rm ' + outcatlink) command = 'ln -s ' + outcat + ' ' + outcatlink print command os.system(command) return exposures def fit_color(): from photo_abs_new import * from config_bonn import cluster infile='/tmp/input.asc' outfile='/tmp/photo_res' extinction=-0.2104 color=0.0 night=-1 label='imz' sigmareject=3 step='STEP_1' bandcomp='z' color1which='imz' color2which='imz' extcoeff=None #### FIX COLOR COEFF data, airmass, color1, color2, magErr, X, Y = readInput(infile) pdict = {'zp':24,'extcoeff':extcoeff,'color1':0,'color2':0} #write input quantities to dictionary var_names = {'bandcomp':bandcomp, 'color1which':color1which , 'color2which':color2which, 'sigmareject':sigmareject, 'cluster':cluster, 'label':label} #define the fits you want to make fits = [{'model':[{'name':'zp','term':['zp'],'value':pdict['zp']},{'name':'color1','term':['color1'],'value':pdict['color1']},{'name':'color2','term':['color2'],'value':pdict['color2']},{'name':'X','term':['X'],'value':0},{'name':'YTY','term':['Y','Y'],'value':0},{'name':'XTX','term':['X','X'],'value':0},{'name':'Y','term':['Y'],'value':0},{'name':'XTY','term':['X','Y'],'value':0}], \ 'fixed':[], \ 'apply' : ['zp','color1','color2','X','Y','XTY','XTX','YTY'], \ 'plots':[{'xaxis_var':'color1','term_names':['color1']}]}, {'model':[{'name':'zp','term':['zp'],'value':pdict['zp']},{'name':'color1','term':['color1'],'value':pdict['color1']},{'name':'color2','term':['color2'],'value':pdict['color2']}], \ 'fixed':[], \ 'apply':[], \ 'plots':[{'xaxis_var':'color1','term_names':['color1']},{'xaxis_var':'color2','term_names':['color2']}]}, \ {'model':[{'name':'zp','term':['zp'],'value':pdict['zp']},{'name':'color1','term':['color1'],'value':pdict['color1']}], \ 'fixed':[], \ 'apply': [], \ 'plots':[{'xaxis_var':'color1','term_names':['color1']}]}] #generate a class for the fit model for i in range(len(fits)): print fits[i]['apply'] j = phot_funct(fits[i]['model'],fits[i]['fixed'],fits[i]['apply']) fits[i]['class'] = j print i print fits[i] fits = photCalib(data, airmass, color1, color2, magErr, X, Y, fits, sigmareject) #make a label for the fitting model for i in range(len(fits)): jj = [] for term in fits[i]['model']: print term jj.append(reduce(lambda x,y: x + 'T' + y,term['term'])) model = reduce(lambda z,w: z + 'P' + w, jj) fits[i]['class'].fitvars['model_name'] = model jj = [] for term in fits[i]['fixed']: print term jj.append(reduce(lambda x,y: x + 'T' + y,term['term'])) if len(jj): model = reduce(lambda z,w: z + 'P' + w, jj) else: model = '' fits[i]['class'].fitvars['fixed_name'] = model corr_data = fits[0]['class'].apply_fit(data,airmass,color1,color2,magErr,X,Y) calcDataIllum('illum',LENGTH1,LENGTH2,1000, corr_data, airmass, color1, color2, magErr, X, Y) import sys sys.exit(0) yesno = raw_input('make illumination image?') if len(yesno) > 0: if yesno[0] == 'y' or yesno[0] == 'Y': calcIllum(12000,12000,1000,fits) #makePlotsNew(data, airmass, color1, color2, X, Y, outfile, fits, var_names) def phot(exposures,filter,type,LENGTH1,LENGTH2): import utilities info = {'B':{'filter':'g','color1':'gmr','color2':'umg','EXTCOEFF':-0.2104,'COLCOEFF':0.0},\ 'W-J-B':{'filter':'g','color1':'gmr','color2':'umg','EXTCOEFF':-0.2104,'COLCOEFF':0.0},\ 'W-J-V':{'filter':'g','color1':'gmr','color2':'rmi','EXTCOEFF':-0.1202,'COLCOEFF':0.0},\ 'W-C-RC':{'filter':'r','color1':'rmi','color2':'gmr','EXTCOEFF':-0.0925,'COLCOEFF':0.0},\ 'W-C-IC':{'filter':'i','color1':'imz','color2':'rmi','EXTCOEFF':-0.02728,'COLCOEFF':0.0},\ 'W-S-Z+':{'filter':'z','color1':'imz','color2':'rmi','EXTCOEFF':0.0,'COLCOEFF':0.0}} #filters = ['W-J-V','W-C-RC','W-C-IC','W-S-Z+'] #cluster = 'MACS2243-09' #filters = ['W-S-Z+'] # ['W-J-B','W-J-V','W-C-RC','W-C-IC','W-S-Z+'] base='/nfs/slac/g/ki/ki05/anja/SUBARU/' + cluster + '/PHOTOMETRY/cat/' base='' #file='all_merg.cat' #file='matched_SUPA0055758.cat' #file = exposures[exposures.keys()[0]]['matched_cat'] if type == 'galaxy': mag='MAG_AUTO' magerr='MAGERR_AUTO' if type == 'star': mag='MAG_APER2' magerr='MAGERR_APER2' import mk_saturation_plot,os,re os.environ['BONN_TARGET'] = cluster os.environ['INSTRUMENT'] = 'SUBARU' stars_0 = [] stars_90 = [] for exposure in exposures.keys(): file = exposures[exposure]['matched_cat'] ROTATION = exposures[exposure]['keywords']['ROTATION'] print ROTATION #raw_input() import os ppid = str(os.getppid()) from glob import glob if 1: #len(glob(file)): for filter in [filter]: print 'filter', filter os.environ['BONN_FILTER'] = filter dict = info[filter] #run('ldacfilter -i ' + base + file + ' -o /tmp/good.stars -t PSSC\ # -c "(Flag=0) AND (SEx_CLASS_STAR_' + filter + '>0.90);"',['/tmp/good.stars']) #command = 'ldacfilter -i ' + base + file + ' -o /tmp/good.stars' + ppid + ' -t PSSC -c "(((SEx_IMAFLAGS_ISO=0 AND SEx_CLASS_STAR>0.0) AND (SEx_Flag=0)) AND Flag=0);"' #print command #raw_input() #utilities.run(command,['/tmp/good.stars' + ppid]) #run('ldacfilter -i ' + base + file + ' -o /tmp/good.stars -t PSSC\ # -c "(SEx_CLASS_STAR>0.00);"',['/tmp/good.stars']) utilities.run('ldacfilter -i ' + base + file + ' -o /tmp/good.colors' + ppid + ' -t PSSC\ -c "(' + dict['color1'] + '>-900) AND (' + dict['color2'] + '>-900);"',['/tmp/good.colors']) #utilities.run('ldacfilter -i /tmp/good.stars' + ppid + ' -o /tmp/good.colors' + ppid + ' -t PSSC\ # -c "(' + dict['color1'] + '>-900) AND (' + dict['color2'] + '>-900);"',['/tmp/good.colors' + ppid]) utilities.run('ldaccalc -i /tmp/good.colors' + ppid + ' -t PSSC -c "(' + dict['filter'] + 'mag - SEx_' + mag + ');" -k FLOAT -n magdiff "" -o /tmp/all.diff.cat' + ppid ,['/tmp/all.diff.cat' + ppid] ) utilities.run('ldactoasc -b -q -i /tmp/all.diff.cat' + ppid + ' -t PSSC -k SEx_' + mag + ' ' + dict['filter'] + 'mag SEx_FLUX_RADIUS SEx_CLASS_STAR ' + dict['filter'] + 'err ' + dict['color1'] + ' > /tmp/mk_sat' + ppid,['/tmp/mk_sat' + ppid] ) # run('ldactoasc -b -q -i ' + base + file + ' -t PSSC -k SEx_' + mag + '_' + filter + ' ' + dict['filter'] + 'mag SEx_FLUX_RADIUS SEx_CLASS_STAR ' + dict['filter'] + 'err ' + dict['color1'] + ' > /tmp/mk_sat',['/tmp/mk_sat'] ) val = [] val = raw_input("Look at the saturation plot?") if len(val)>0: if val[0] == 'y' or val[0] == 'Y': mk_saturation_plot.mk_saturation('/tmp/mk_sat' + ppid,filter) # make stellar saturation plot lower_mag,upper_mag,lower_diff,upper_diff = re.split('\s+',open('box' + filter,'r').readlines()[0]) utilities.run('ldacfilter -i /tmp/all.diff.cat' + ppid + ' -t PSSC\ -c "(((SEx_' + mag + '>' + lower_mag + ') AND (SEx_' + mag + '<' + upper_mag + ')) AND (magdiff>' + lower_diff + ')) AND (magdiff<' + upper_diff + ');"\ -o /tmp/filt.mag.cat' + ppid ,['/tmp/filt.mag.cat' + ppid]) #utilities.run('ldacfilter -i /tmp/all.diff.cat' + ppid + ' -t PSSC\ # -c "(((' + dict['filter'] + 'mag>' + lower_mag + ') AND (' + dict['filter'] + 'mag<' + upper_mag + ')) AND (magdiff>' + lower_diff + ')) AND (magdiff<' + upper_diff + ');"\ # -o /tmp/filt.mag.cat' + ppid ,['/tmp/filt.mag.cat' + ppid]) utilities.run('ldactoasc -b -q -i /tmp/filt.mag.cat' + ppid + ' -t PSSC -k SEx_Xpos_ABS SEx_Ypos_ABS > /tmp/positions' + ppid,['/tmp/positions' + ppid] ) utilities.run('ldacaddkey -i /tmp/filt.mag.cat' + ppid + ' -o /tmp/filt.airmass.cat' + ppid + ' -t PSSC -k AIRMASS 0.0 FLOAT "" ',['/tmp/filt.airmass.cat' + ppid] ) utilities.run('ldactoasc -b -q -i /tmp/filt.airmass.cat' + ppid + ' -t PSSC -k SEx_' + mag + ' ' + dict['filter'] + 'mag ' + dict['color1'] + ' ' + dict['color2'] + ' AIRMASS SEx_' + magerr + ' ' + dict['filter'] + 'err SEx_Xpos_ABS SEx_Ypos_ABS > /tmp/input.asc' + ppid ,['/tmp/input.asc' + ppid] ) #utilities.run('ldactoasc -b -q -i /tmp/filt.airmass.cat -t PSSC -k SEx_' + mag + ' ' + dict['filter'] + 'mag ' + dict['color1'] + ' ' + dict['color2'] + ' AIRMASS SEx_' + magerr + ' ' + dict['filter'] + 'err SEx_Ra SEx_Dec > /tmp/input.asc',['/tmp/input.asc'] ) # fit photometry #utilities.run("./photo_abs_new.py --input=/tmp/input.asc \ # --output=/tmp/photo_res --extinction="+str(dict['EXTCOEFF'])+" \ # --color="+str(dict['COLCOEFF'])+" --night=-1 --label="+dict['color1']+" --sigmareject=3\ # --step=STEP_1 --bandcomp="+dict['filter']+" --color1="+dict['color1']+" --color2="+dict['color2']) import photo_abs_new good_stars = photo_abs_new.run_through('illumination',infile='/tmp/input.asc' + ppid,output='/tmp/photo_res',extcoeff=dict['color1'],sigmareject=3,step='STEP_1',bandcomp=dict['filter'],color1which=dict['color1'],color2which=dict['color2']) if int(ROTATION) == 0: stars_0.append(good_stars) if int(ROTATION) == 1: stars_90.append(good_stars) from copy import copy if len(stars_0)> 0: dict = copy(stars_0[0]) blank_0 = {} for key in dict.keys(): blank_0[key] = [] for i in range(len(stars_0)): for j in range(len(stars_0[i][key])): blank_0[key].append(stars_0[i][key][j]) #print key, blank[key] photo_abs_new.calcDataIllum('illumination',LENGTH1, LENGTH2, 1000, blank_0['corr_data'], blank_0['airmass_good'], blank_0['color1_good'], blank_0['color2_good'], blank_0['magErr_good'], blank_0['X_good'], blank_0['Y_good'],rot=0) if len(stars_90)> 0: dict = copy(stars_90[0]) blank_90 = {} for key in dict.keys(): blank_90[key] = [] for i in range(len(stars_90)): for j in range(len(stars_90[i][key])): blank_90[key].append(stars_90[i][key][j]) #print key, blank[key] photo_abs_new.calcDataIllum('illumination',LENGTH1, LENGTH2, 1000, blank_90['corr_data'], blank_90['airmass_good'], blank_90['color1_good'], blank_90['color2_good'], blank_90['magErr_good'], blank_90['X_good'], blank_90['Y_good'],rot=0) #photo_abs_new.calcDataIllum('illumination',1000, blank_90['corr_data'], blank_90['airmass_good'], blank_90['color1_good'], blank_90['color2_good'], blank_90['magErr_good'], blank_90['X_good'], blank_90['Y_good'],rot=1) from config_bonn import cluster filter = 'W-C-RC' import pickle if 0: exposures, LENGTH1, LENGTH2 = sextract(filter) print exposures f = open('/tmp/tmppickle' + cluster + filter,'w') m = pickle.Pickler(f) pickle.dump([exposures,LENGTH1,LENGTH2],m) f.close() print LENGTH1, LENGTH2 raw_input() if 1: f = open('/tmp/tmppickle' + cluster + filter,'r') m = pickle.Unpickler(f) exposures, LENGTH1, LENGTH2 = m.load() type = 'galaxy' exposures = match_simple(exposures,cluster) for key in exposures.keys(): print exposures[key]['matched_cat'] #print exposures phot(exposures,filter,type,LENGTH1,LENGTH2) for key in exposures.keys(): print exposures[key]['images']
deapplegate/wtgpipeline
non_essentials/calc_test/calc_tmp.save2.py
Python
mit
30,619
[ "Galaxy" ]
6c01a19e70fd96a8cf38619e9c17b8515e4f4656124f7848e3cecb74e675252a
# Copyright 2009-2014 Ram Rachum. # This program is distributed under the MIT license. from __future__ import with_statement import os.path, sys sys.path += [ os.path.dirname(__file__), os.path.join(os.path.dirname(__file__), 'third_party.zip'), ] import bisect import re import inspect import logging import wingapi import shared python_identifier_subpattern = r'''[a-zA-Z_][0-9a-zA-Z_]*''' pattern = re.compile( r'''(?P<object>%s(?:\.%s)*)\.(?P<attribute_name>%s)''' % ( python_identifier_subpattern, python_identifier_subpattern, python_identifier_subpattern ) ) def _get_matches(document): assert isinstance(document, wingapi.CAPIDocument) document_text = shared.get_text(document) return tuple(pattern.finditer(document_text)) def implicit_getattr_to_explicit(editor=wingapi.kArgEditor): ''' Convert something like `foo.bar` into `getattr(foo, 'bar', None)`. Also selects the `None` so it could be easily modified. Suggested key combination: `Insert Shift-G` ''' assert isinstance(editor, wingapi.CAPIEditor) document = editor.GetDocument() assert isinstance(document, wingapi.CAPIDocument) _, current_position = editor.GetSelection() #head = max(current_position - 100, 0) #tail = min(current_position + 100, document.GetLength()) #text = document.GetCharRange(head, tail) matches = _get_matches(document) if not matches: return match_spans = tuple(match.span(0) for match in matches) candidate_index = max( bisect.bisect_left(match_spans, (current_position, 0)) - 1, 0 ) candidate_span = match_spans[candidate_index] candidate = matches[candidate_index] #if candidate[0] <= current_position <= candidate[1]: #editor.SetSelection(*candidate) #else: #print(candidate) #try: #print(shared.get_text(document)[candidate[0]:candidate[1]]) #except: #pass new_text = 'getattr(%s, %s, None)' % (candidate.group(1), repr(candidate.group(2))) wingapi.gApplication.ExecuteCommand('set-visit-history-anchor') with shared.UndoableAction(document): document.DeleteChars(candidate_span[0], candidate_span[1] - 1) document.InsertChars(candidate_span[0], new_text) editor.SetSelection(candidate_span[0]+len(new_text)-5, candidate_span[0]+len(new_text)-1)
cool-RR/cute-wing-stuff
scripts/implicit_getattr_to_explicit.py
Python
mit
2,509
[ "VisIt" ]
c5a1b9dcda809aa1c5aafeb7c3010830d837f1ee654b115104222a8c896b42ad
# # mainTab # tab = self.notebook.mainTab tab.settings['Program'] = 'vasp' tab.settings['Output file name'] = 'OUTCAR' # # Handle the special case of the first scenario # self.notebook.switchScenario(0,scenarioType="Single crystal") # # # tab = self.notebook.mainTab tab.settings['Program'] = 'vasp' tab.settings['Output file name'] = 'OUTCAR' tab.settings['Excel file name'] = '' tab.settings['QM program'] = 'vasp' tab.settings['Hessian symmetrisation'] = 'symm' # # tab = self.notebook.settingsTab tab.settings['Eckart flag'] = True tab.settings['Neutral Born charges'] = False tab.settings['Sigma value'] = 5 tab.settings['Mass definition'] = 'average' tab.settings['Optical permittivity edited'] = False tab.sigmas_cm1 = [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5] # # tab = self.notebook.scenarios[0] tab.settings['Legend'] = '(001) theta 0' tab.settings['Scenario type'] = 'Single crystal' tab.settings['Unique direction - h'] = 0 tab.settings['Unique direction - k'] = 0 tab.settings['Unique direction - l'] = 1 tab.settings['Azimuthal angle'] = 0.0 tab.settings['Angle of incidence'] = 60.0 tab.settings['Superstrate dielectric'] = 1.0 tab.settings['Substrate dielectric'] = 1.0 tab.settings['Superstrate depth'] = 999.0 tab.settings['Substrate depth'] = 999.0 tab.settings['Film thickness'] = 100.0 tab.settings['Mode'] = 'Thick slab' tab.settings['Frequency units'] = 'wavenumber' for az in [ 10, 20, 30, 40, 50, 60, 70, 80, 90]: self.notebook.addScenario(scenarioType="Single crystal") tab = self.notebook.scenarios[-1] tab.settings['Legend'] = '(001) theta {}'.format(az) tab.settings['Azimuthal angle'] = az # tab = self.notebook.plottingTab tab.settings['Minimum frequency'] = 0 tab.settings['Maximum frequency'] = 250 tab.settings['Frequency increment'] = 0.2 tab.settings['Plot type'] = 'Crystal Reflectance (P polarisation)'
JohnKendrick/PDielec
Examples/SingleCrystal/Bi2Se3/script.py
Python
mit
1,880
[ "CRYSTAL", "VASP" ]
91f790c8fa6ed4d3ea0501d1935b42bb81752e139ffcfdb54ab8b0780e016a80
#!/usr/bin/env python from __future__ import division __author__ = "Jai Ram Rideout" __copyright__ = "Copyright 2012, The QIIME project" __credits__ = ["Jai Ram Rideout", "Jose Antonio Navas Molina"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "Jai Ram Rideout" __email__ = "jai.rideout@gmail.com" from os.path import split, splitext from bfillings.formatdb import build_blast_db_from_fasta_path from qiime.util import load_qiime_config, get_options_lookup from qiime.parallel.util import ParallelWrapper class ParallelBlaster(ParallelWrapper): _script_name = load_qiime_config()['blastall_fp'] _input_splitter = ParallelWrapper._split_fasta _job_prefix = 'BLAST' def _precommand_initiation( self, input_fp, output_dir, working_dir, params): if params['refseqs_path']: # Build the blast database from the refseqs_path -- all procs # will then access one db rather than create one per proc. blast_db, db_files_to_remove = \ build_blast_db_from_fasta_path(params['refseqs_path']) self.files_to_remove += db_files_to_remove params['blast_db'] = blast_db def _get_job_commands(self, fasta_fps, output_dir, params, job_prefix, working_dir, command_prefix=None, command_suffix='; exit'): """Generate blastall commands which should be run.""" # Create basenames for each of the output files. These will be filled # in to create the full list of files created by all of the runs. out_filenames = [job_prefix + '.%d_blast_out.txt'] command_prefix = command_prefix or \ '/bin/bash; export BLASTMAT=%s;' % params['blastmat_dir'] if not params['disable_low_complexity_filter']: complexity_filter_str = 'T' else: complexity_filter_str = 'F' # Create lists to store the results. commands = [] result_filepaths = [] # Iterate over the input files. for i, fasta_fp in enumerate(fasta_fps): # Each run ends with moving the output file from the tmp dir to # the output_dir. Build the command to perform the move here. # rename_command, current_result_filepaths = \ # self._get_rename_command([fn % i for fn in out_filenames], # working_dir, output_dir) #result_filepaths += current_result_filepaths # TODO should this be put in self._get_rename_command()? infile_basename = splitext(split(fasta_fp)[1])[0] working_outfile_path = '%s/%s_blast_out.txt' %\ (working_dir, infile_basename) outfile_path = '%s/%s_blast_out.txt' % (output_dir, infile_basename) rename_command = '; mv %s %s' % (working_outfile_path, outfile_path) result_filepaths.append(outfile_path) command = '%s %s -p blastn -m 9 -e %s -F %s -W %s -b %s -i %s -d %s > %s %s %s' % \ (command_prefix, self._script_name, params['e_value'], complexity_filter_str, params['word_size'], params['num_hits'], fasta_fp, params['blast_db'], working_outfile_path, rename_command, command_suffix) commands.append(command) return commands, result_filepaths def _write_merge_map_file(self, input_file_basename, job_result_filepaths, params, output_dir, merge_map_filepath, failures=False): """ """ f = open(merge_map_filepath, 'w') out_filepath = '%s/%s_blast_out.txt' % (output_dir, input_file_basename) f.write('\t'.join(job_result_filepaths + [out_filepath])) f.write('\n') f.close()
josenavas/qiime
qiime/parallel/blast.py
Python
gpl-2.0
4,254
[ "BLAST" ]
c3b4d7daba291465bfab3d0985914008d43e5e690c9eb7a5aea140975d3ef9f9
import numpy import itertools import random import math def convert_spike_list_to_timed_spikes(spike_list, min_idx, max_idx, tmin, tmax, tstep): times = numpy.array(range(tmin, tmax, tstep)) spike_ids = sorted(spike_list) possible_neurons = range(min_idx, max_idx) spikeArray = dict([(neuron, times) for neuron in spike_ids if neuron in possible_neurons]) return spikeArray def convert_file_to_spikes(input_file_name, min_idx=None, max_idx=None, tmin=None, tmax=None, compatible_input=True): data = numpy.array(numpy.loadtxt(fname=input_file_name), dtype=int) # get the array from the original text file if compatible_input: data = numpy.roll(data, 1, axis=1) # swap neuron ID and time if necessary if min_idx is None: min_idx = numpy.fmin.reduce(data[:,0], 0) if max_idx is None: max_idx = numpy.fmax.reduce(data[:,0], 0) + 1 if tmin is None: tmin = numpy.fmin.reduce(data[:,1], 0) if tmax is None: tmax = numpy.fmax.reduce(data[:,1], 0) data = data[(data[:,1]>=tmin) & (data[:,1]<tmax) & (data[:,0]>=min_idx) & (data[:,0]<max_idx),:] # filter by mins and maxes if data.shape == (0,): return {} # nothing left: return an empty dict. sort_keys = numpy.lexsort((data[:,1], data[:,0])) # otherwise sort, grouping by neuron ID then time. data = data[sort_keys,:] spiking_neurons = itertools.groupby(data, lambda x: x[0]) # and taking one group at a time#, spikeArray = dict([(neuron[0], numpy.array([spike_time[1] for spike_time in neuron[1]])) for neuron in spiking_neurons]) # create a dictionary indexed by neuron number of the spike times. return spikeArray def loop_array(input_array, runtime=0, num_repeats=1, sampletime=0): spikeArray = {} for neuron in input_array: if not sampletime: sampletime = int(numpy.fmax.reduce(input_array[neuron],0)) last_array = numpy.array([]) if sampletime*num_repeats < runtime or (runtime > 0 and sampletime*num_repeats > runtime): num_repeats = runtime/sampletime last_array = input_array[neuron][input_array[neuron] <= (runtime%sampletime)] spikeArray[neuron] = numpy.concatenate([input_array[neuron]+repeat*sampletime for repeat in range(num_repeats)]) if len(last_array): spikeArray[neuron] = numpy.concatenate([spikeArray[neuron], last_array]) return spikeArray def splice_arrays(input_arrays, input_times=None, input_neurons=None): spikeArray = {} if input_neurons is None: input_neurons = [None]*len(input_arrays) if input_times is None: input_times = [[(reduce(lambda x, y: min(x, numpy.fmin.reduce(y,0)), input_group.values(), 0), reduce(lambda x, y: max(x, numpy.fmax.reduce(y,0)), input_group.values(), 0))] for input_group in input_arrays] for in_idx in range(len(input_arrays)): for neuron in input_arrays[in_idx].items(): if input_neurons[in_idx] is None or neuron[0] in input_neurons[in_idx]: for time_range in input_times[in_idx]: if time_range is None: time_range = (reduce(lambda x, y: min(x, numpy.fmin.reduce(y,0)), input_arrays[in_idx].values(), 0), reduce(lambda x, y: max(x, numpy.fmax.reduce(y,0)), input_arrays[in_idx].values(), 0)) if neuron[0] in spikeArray: spikeArray[neuron[0]].extend([time for time in neuron[1] if time >= time_range[0] and time < time_range[1]]) else: spikeArray[neuron[0]] = [time for time in neuron[1] if time >= time_range[0] and time < time_range[1]] for neuron in spikeArray.items(): spikeArray[neuron[0]] = numpy.sort(numpy.unique(numpy.array(neuron[1]))) return spikeArray def splice_files(input_files, input_times=None, input_neurons=None, compatible_input=True): # splice_files expects a list of files, a list of lists, one for each file, giving the onset # and offset times for each file, and a list of neurons relevant to each file, which will be # spliced together into a single spike list. spikeArray = {} if input_times is None: input_times = [[(None, None)] for file_idx in len(input_files)] for file_idx in len(input_files): if input_neurons is None or input_neurons[file_idx] is None: max_neuron_id = numpy.fmax.reduce(input_files[file_idx].keys(), 0) + 1 min_neuron_id = numpy.fmin.reduce(input_files[file_idx].keys(), 0) else: max_neuron_id = numpy.fmax.reduce(input_neurons[file_idx], 0) + 1 min_neuron_id = numpy.fmin.reduce(input_neurons[file_idx], 0) for time_range in input_times[file_idx]: for neuron in convert_file_to_spikes(input_file_name=input_files[file_idx], min_idx=min_neuron_id, max_idx=max_neuron_id, tmin=time_range[0], tmax=time_range[1], compatible_input=compatible_input).items(): if neuron[0] in spikeArray: spikeArray[neuron[0]].append(neuron[1]) else: spikeArray[neuron[0]] = neuron[1] for neuron in spikeArray.items(): spikeArray[neuron[0]] = numpy.sort(numpy.unique(numpy.array(neuron[1]))) return spikeArray def subsample_spikes_by_time(spikeArray, start, stop, step): subsampledArray = {} for neuron in spikeArray: times = numpy.sort(spikeArray[neuron][(spikeArray[neuron] >= start) & (spikeArray[neuron] < stop)]) interval = step/2 + step%2 t_now = times[0] t_start = times[0] t_last = len(times) t_index = 0 subsampled_times = [] while t_index < t_last: spikes_in_interval = 0 while t_index < t_last and times[t_index] <= t_start + interval: spikes_in_interval += 1 if spikes_in_interval >= interval: t_start = times[t_index] + interval subsampled_times.append(times[t_index]) try: t_index = next(i for i in range(t_index, t_last) if times[i] >= t_start) except StopIteration: t_index = t_last break t_index += 1 else: if t_index < t_last: t_start = times[t_index] subsampledArray[neuron] = numpy.array(subsampled_times) return subsampledArray def random_skew_times(spikeArray, skewtime, seed=3425670): random.seed(seed) #return dict([(neuron, [int(abs(t+random.uniform(-skewtime, skewtime))) for t in spikeArray[neuron]]) for neuron in spikeArray]) spikeDict = dict([(neuron, numpy.array(numpy.fabs(spikeArray[neuron]+numpy.random.uniform(-skewtime, skewtime, len(spikeArray[neuron]))), dtype=int)) for neuron in spikeArray]) #test_out = open('spikeArray.txt', 'w') #test_out.write('%s' % spikeDict) #test_out.close() return spikeDict def generate_shadow_spikes(spikeArray, dim_x, dim_y, move_velocity): """ generate a second set of spikes as if coming from a DVS retina. imagines that the offset pixels perfectly register with perfect timing precision. args: spikeArray, in the format above for an array of Spikes: a dict of {id: [times]} dim_x, size of the field in the x-dimension dim_y, size of the field in the y-dimension move_velocity: an (s, theta) tuple, where s is the speed measured in pixels/ms, theta the angle of virtual movement measured in radians anticlockwise (0 is horizontal movement to the right). The function will displace the shadow by s pixels in the reverse of direction indicated for each time point where spikes are registered. It will add one last set of spikes at time tmax+1, at position of the source spikes at time tmax. """ motion_x = -move_velocity[0]*math.cos(move_velocity[1]) motion_y = -move_velocity[0]*math.sin(move_velocity[1]) spikeArray_out = dict([(int(motion_x+spike[0]%dim_x)+dim_x*int(motion_y+spike[0]/dim_x), spike[1][1:]) for spike in spikeArray.items() if len(spike[1]) > 1]) spikeArray_out = dict([item for item in spikeArray_out.items() if item[0] >= 0 and item[0] < dim_x*dim_y]) spikeArray_out.update(dict([(spike[0], numpy.append(spikeArray_out.get(spike[0], numpy.array([], dtype=int)), [int(max(spike[1]))])) for spike in spikeArray.items()])) return spikeArray_out
dhgarcia/babelModules
pynnModules/Network/spike_file_to_spike_array.py
Python
gpl-3.0
8,559
[ "NEURON" ]
66c971b7b41b36c39f815de93e86aebe99a06a5bac46f0f7f0f9f629d9046bad
############################### # This file is part of PyLaDa. # # Copyright (C) 2013 National Renewable Energy Lab # # PyLaDa is a high throughput computational platform for Physics. It aims to make it easier to # submit large numbers of jobs on supercomputers. It provides a python interface to physical input, # such as crystal structures, as well as to a number of DFT (VASP, CRYSTAL) and atomic potential # programs. It is able to organise and launch computational jobs on PBS and SLURM. # # PyLaDa is free software: you can redistribute it and/or modify it under the terms of the GNU # General Public License as published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # PyLaDa is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along with PyLaDa. If not, see # <http://www.gnu.org/licenses/>. ############################### # -*- coding: utf-8 -*- from pytest import fixture, mark from pylada.espresso import structure_handling as sh from quantities import angstrom, bohr_radius @fixture def pwscfin(tmpdir): string = """ &system ibrav=5, celldm = 1.0 0.0 0.0 0.5, / ATOMIC_POSITIONS alat A 0 0 0 B 1 2 3 """ tmpdir.join('pos.in').write(string) return tmpdir.join('pos.in') def get_namelist(ibrav, **kwargs): from pylada.espresso import Namelist result = Namelist({'ibrav': ibrav}) for key, value in kwargs.items(): if value is not None: setattr(result, key, value) return result @mark.parametrize('celldim, subtitle, expected_scale', [ (None, 'bohr', bohr_radius), (None, 'angstrom', angstrom), (None, None, bohr_radius), ('A', None, angstrom), ([2.5], 'alat', 2.5 * bohr_radius), # card takes precedence over celldm ('A', 'bohr', bohr_radius), ([2.5], 'bohr', bohr_radius), ([2.5], 'angstrom', angstrom), ]) def test_free_cell(celldim, subtitle, expected_scale): from numpy import allclose, abs, array from pylada.espresso import Card, Namelist namelist = Namelist({'ibrav': 0}) if celldim is not None: namelist.celldm = celldim card = Card('CELL_PARAMETERS', subtitle=subtitle, value=""" 1 2 3 2 3 4 4 4 6 """) cell, scale = sh._read_free(namelist, card) assert allclose(cell, array([[1, 2, 4], [2, 3, 4], [3, 4, 6]], dtype='float64')) assert abs(scale - expected_scale) < 1e-8 @mark.parametrize('celldim, A, expected_scale', [ (None, 0.75, 0.75 * angstrom), ('A', None, angstrom), ([1.1], None, 1.1 * bohr_radius) ]) def test_cubic_cell_and_scale(celldim, A, expected_scale): from numpy import abs, allclose namelist = get_namelist(1, celldm=celldim, A=A) cell, scale = sh.read_cell_and_scale(namelist, None) assert allclose(cell, [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) assert abs(scale - expected_scale) < 1e-8 @mark.parametrize('celldim, A, expected_scale', [ (None, 0.75, 0.75 * angstrom), ('A', None, angstrom), ([1.1], None, 1.1 * bohr_radius) ]) def test_fcc_cell_and_scale(celldim, A, expected_scale): from numpy import abs, allclose namelist = get_namelist(2, celldm=celldim, A=A) cell, scale = sh.read_cell_and_scale(namelist, None) assert allclose(2 * cell, [[-1, 0, -1], [0, 1, 1], [1, 1, 0]]) assert abs(scale - expected_scale) < 1e-8 @mark.parametrize('celldim, A, expected_scale', [ (None, 0.75, 0.75 * angstrom), ('A', None, angstrom), ([1.1], None, 1.1 * bohr_radius) ]) def test_bcc_cell_and_scale(celldim, A, expected_scale): from numpy import abs, allclose namelist = get_namelist(3, celldm=celldim, a=A) cell, scale = sh.read_cell_and_scale(namelist, None) assert allclose(2 * cell, [[1, -1, -1], [1, 1, -1], [1, 1, 1]]) assert abs(scale - expected_scale) < 1e-8 @mark.parametrize('celldim, A, expected_scale, C, c_over_a', [ (None, 0.75, 0.75 * angstrom, 1, 1. / 0.75), ([0.75, 0, 1. / 0.75], None, 0.75 * bohr_radius, None, 1. / 0.75), ]) def test_hexa_cell_and_scale(celldim, A, expected_scale, C, c_over_a): from numpy import abs, allclose, sqrt namelist = get_namelist(4, celldm=celldim, a=A, c=C) cell, scale = sh.read_cell_and_scale(namelist, None) expected_cell = [[1, -0.5, 0], [0, sqrt(3.) / 2., 0], [0, 0, c_over_a]] assert allclose(cell, expected_cell) assert abs(scale - expected_scale) < 1e-8 def test_read_structure(pwscfin): from numpy import allclose, sqrt from quantities import bohr_radius from pylada.espresso.structure_handling import read_structure structure = read_structure(str(pwscfin)) c = 0.5 tx, ty, tz = sqrt((1. - c) / 2.), sqrt((1. - c) / 6.), sqrt((1. + 2. * c) / 3.) assert allclose(structure.cell.transpose(), [[tx, -ty, tz], [0, 2 * ty, tz], [-tx, -ty, tz]]) assert abs(structure.scale - bohr_radius) < 1e-8 assert len(structure) == 2 assert structure[0].type == 'A' assert allclose(structure[0].pos, [0, 0, 0.]) assert structure[1].type == 'B' assert allclose(structure[1].pos, [1, 2, 3.]) def test_write_read_loop(tmpdir, pwscfin): from numpy import abs, allclose from f90nml import Namelist as F90Namelist from pylada.espresso.structure_handling import add_structure, read_structure from pylada.espresso.misc import write_pwscf_input structure = read_structure(str(pwscfin)) namelist = F90Namelist() cards = [] add_structure(structure, namelist, cards) write_pwscf_input(namelist, cards, str(tmpdir.join('other.in'))) reread = read_structure(str(tmpdir.join('other.in'))) assert allclose(reread.cell, structure.cell) assert abs(reread.scale - structure.scale) < 1e-12 assert len(reread) == len(structure) for i in range(len(reread)): assert allclose(reread[i].pos, structure[i].pos) assert reread[i].type == structure[i].type def test_read_forces(tmpdir): from quantities import Ry, bohr_radius as a0 from numpy import allclose from pylada.espresso.structure_handling import read_structure string = """ &system ibrav=5, celldm = 1.0 0.0 0.0 0.5, / ATOMIC_POSITIONS alat A 0 0 0 B 1 2 3 ATOMIC_FORCES A 0 0 0 B 1 2 3 """ tmpdir.join('pos.in').write(string) structure = read_structure(str(tmpdir.join('pos.in'))) for atom in structure: assert hasattr(atom, 'force') assert atom.force.units == (Ry / a0) assert allclose(structure[0].force.magnitude, [0, 0, 0]) assert allclose(structure[1].force.magnitude, [1, 2, 3])
pylada/pylada-light
tests/espresso/test_structure.py
Python
gpl-3.0
6,911
[ "CRYSTAL", "ESPResSo", "VASP" ]
e88ebce100d051d0226aaf439d8185d0e0ea723a98941be1bd9a1769698122c0
#!/usr/bin/env python import cv2 from datetime import datetime from dateutil.tz import tzlocal import numpy as np import pyqtgraph as pg import scipy import os from pyqtgraph import FileDialog from pyqtgraph.Qt import QtGui from pyqtgraph.parametertree import Parameter, ParameterTree from scipy.sparse import csc_matrix import caiman as cm from caiman.source_extraction.cnmf.cnmf import load_CNMF from caiman.source_extraction.cnmf.params import CNMFParams # Always start by initializing Qt (only once per application) app = QtGui.QApplication([]) try: cv2.setNumThreads(1) except: print('Open CV is naturally single threaded') try: if __IPYTHON__: print(1) # this is used for debugging purposes only. allows to reload classes # when changed get_ipython().magic('load_ext autoreload') get_ipython().magic('autoreload 2') except NameError: print('Not launched under iPython') def make_color_img(img, gain=255, min_max=None, out_type=np.uint8): if min_max is None: min_ = img.min() max_ = img.max() else: min_, max_ = min_max img = (img-min_)/(max_-min_)*gain img = img.astype(out_type) img = np.dstack([img]*3) return img F = FileDialog() # load object saved by CNMF fpath = F.getOpenFileName(caption='Load CNMF Object', filter='HDF5 (*.h5 *.hdf5);;NWB (*.nwb)')[0] cnm_obj = load_CNMF(fpath) # movie if not os.path.exists(cnm_obj.mmap_file): M = FileDialog() cnm_obj.mmap_file = M.getOpenFileName(caption='Load memory mapped file', filter='*.mmap')[0] if fpath[-3:] == 'nwb': mov = cm.load(cnm_obj.mmap_file, var_name_hdf5='acquisition/TwoPhotonSeries') else: mov = cm.load(cnm_obj.mmap_file) estimates = cnm_obj.estimates params_obj = cnm_obj.params dims = estimates.dims #original dimension estimates.rotation = False # flag for rotation min_mov = np.min(mov) max_mov = np.max(mov) if not hasattr(estimates, 'Cn'): estimates.Cn = cm.local_correlations(mov, swap_dim=False) #Cn = estimates.Cn # We rotate our components 90 degrees right because of incompatiability of pyqtgraph and pyplot def rotate90(img, right=None, vector=None, sparse=False): # rotate the img 90 degrees # we first transpose the img then flip axis # If right is ture, then rotate 90 degrees right, otherwise, rotate left # If vector is True, then we first reshape the spatial 1D vector to 2D then rotate # If vector is False, then we directly rotate the matrix global dims a = int(right) if vector == False: img = img.transpose([1,0]) img = np.flip(img, axis=a) elif vector == True: if sparse == False: img = img.reshape((dims[1-a], dims[a], img.shape[1]), order='F') img = img.transpose([1,0,2]) img = np.flip(img, axis=a) img = img.reshape((dims[0]*dims[1], img.shape[2]), order='F') else: img = img.toarray() img = img.reshape((dims[1-a], dims[a], img.shape[1]), order='F') img = img.transpose([1,0,2]) img = np.flip(img, axis=a) img = img.reshape((dims[0]*dims[1], img.shape[2]), order='F') img = csc_matrix(img) return img estimates.Cn = rotate90(estimates.Cn, right=True, vector=False) estimates.A = rotate90(estimates.A, right=True, vector=True, sparse=True) estimates.b = rotate90(estimates.b, right=True, vector=True) estimates.dims = (estimates.dims[1], estimates.dims[0]) estimates.rotation = True # rotation flag becomes true after rotation min_mov_denoise = np.min(estimates.A)*estimates.C.min() max_mov_denoise = np.max(estimates.A)*estimates.C.max() background_num = -1 neuron_selected = False nr_index = 0 min_background = np.min(estimates.b, axis=0)*np.min(estimates.f, axis=1) max_background = np.max(estimates.b, axis=0)*np.max(estimates.f, axis=1) accepted_empty = True # check if accepted list exist and empty if hasattr(estimates, 'accepted_list'): accepted_empty = (len(estimates.accepted_list)==0) if (not hasattr(estimates, 'accepted_list')) or accepted_empty: # if estimates.discarded_components.A.shape[-1] > 0: # estimates.restore_discarded_components() estimates.accepted_list = np.array([], dtype=np.int) estimates.rejected_list = np.array([], dtype=np.int) estimates.img_components = estimates.A.toarray().reshape((estimates.dims[0], estimates.dims[1], -1), order='F').transpose([2,0,1]) estimates.cms = np.array([scipy.ndimage.measurements.center_of_mass(comp) for comp in estimates.img_components]) estimates.idx_components = np.arange(estimates.nr) estimates.idx_components_bad = np.array([]) estimates.background_image = make_color_img(estimates.Cn) # Generate image data estimates.img_components /= estimates.img_components.max(axis=(1, 2))[:, None, None] estimates.img_components *= 255 estimates.img_components = estimates.img_components.astype(np.uint8) def draw_contours_overall(md): if md == "reset": draw_contours() elif md == "neurons": if neuron_selected is True: # if a specific neuron has been selected, only one contour # should be changed while thrshcomp_line is changing if nr_index == 0: # if user does not start to move through the frames draw_contours_update(estimates.background_image, img) draw_contours_update(comp2_scaled, img2) else: draw_contours_update(raw_mov_scaled, img) draw_contours_update(frame_denoise_scaled, img2) else: # if no specific neuron has been selected, redraw all the contours draw_contours() else: # md is "background": return def draw_contours(): global thrshcomp_line, estimates, img bkgr_contours = estimates.background_image.copy() if len(estimates.idx_components) > 0: contours = [cv2.findContours(cv2.threshold(img, np.int(thrshcomp_line.value()), 255, 0)[1], cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0] for img in estimates.img_components[estimates.idx_components]] SNRs = np.array(estimates.r_values) iidd = np.array(estimates.idx_components) idx1 = np.where(SNRs[iidd] < 0.1)[0] idx2 = np.where((SNRs[iidd] >= 0.1) & (SNRs[iidd] < 0.25))[0] idx3 = np.where((SNRs[iidd] >= 0.25) & (SNRs[iidd] < 0.5))[0] idx4 = np.where((SNRs[iidd] >= 0.5) & (SNRs[iidd] < 0.75))[0] idx5 = np.where((SNRs[iidd] >= 0.75) & (SNRs[iidd] < 0.9))[0] idx6 = np.where(SNRs[iidd] >= 0.9)[0] cv2.drawContours(bkgr_contours, sum([contours[jj] for jj in idx1], []), -1, (255, 0, 0), 1) cv2.drawContours(bkgr_contours, sum([contours[jj] for jj in idx2], []), -1, (0, 255, 0), 1) cv2.drawContours(bkgr_contours, sum([contours[jj] for jj in idx3], []), -1, (0, 0, 255), 1) cv2.drawContours(bkgr_contours, sum([contours[jj] for jj in idx4], []), -1, (255, 255, 0), 1) cv2.drawContours(bkgr_contours, sum([contours[jj] for jj in idx5], []), -1, (255, 0, 255), 1) cv2.drawContours(bkgr_contours, sum([contours[jj] for jj in idx6], []), -1, (0, 255, 255), 1) img.setImage(bkgr_contours, autoLevels=False) pg.setConfigOptions(imageAxisOrder='col-major') def draw_contours_update(cf, im): global thrshcomp_line, estimates curFrame = cf.copy() if len(estimates.idx_components) > 0: contours = [cv2.findContours(cv2.threshold(img, np.int(thrshcomp_line.value()), 255, 0)[1], cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0] for img in estimates.img_components[estimates.idx_components]] SNRs = np.array(estimates.r_values) iidd = np.array(estimates.idx_components) idx1 = np.where(SNRs[iidd] < 0.1)[0] idx2 = np.where((SNRs[iidd] >= 0.1) & (SNRs[iidd] < 0.25))[0] idx3 = np.where((SNRs[iidd] >= 0.25) & (SNRs[iidd] < 0.5))[0] idx4 = np.where((SNRs[iidd] >= 0.5) & (SNRs[iidd] < 0.75))[0] idx5 = np.where((SNRs[iidd] >= 0.75) & (SNRs[iidd] < 0.9))[0] idx6 = np.where(SNRs[iidd] >= 0.9)[0] if min_dist_comp in idx1: cv2.drawContours(curFrame, contours[min_dist_comp], -1, (255, 0, 0), 1) if min_dist_comp in idx2: cv2.drawContours(curFrame, contours[min_dist_comp], -1, (0, 255, 0), 1) if min_dist_comp in idx3: cv2.drawContours(curFrame, contours[min_dist_comp], -1, (0, 0, 255), 1) if min_dist_comp in idx4: cv2.drawContours(curFrame, contours[min_dist_comp], -1, (255, 255, 0), 1) if min_dist_comp in idx5: cv2.drawContours(curFrame, contours[min_dist_comp], -1, (255, 0, 255), 1) if min_dist_comp in idx6: cv2.drawContours(curFrame, contours[min_dist_comp], -1, (0, 255, 255), 1) im.setImage(curFrame, autoLevels=False) # %% # Define a top-level widget to hold everything w = QtGui.QWidget() # Create some widgets to be placed inside btn = QtGui.QPushButton('press me') text = QtGui.QLineEdit('enter text') win = pg.GraphicsLayoutWidget() win.setMaximumWidth(300) win.setMinimumWidth(200) hist = pg.HistogramLUTItem() # Contrast/color control win.addItem(hist) p1 = pg.PlotWidget() p2 = pg.PlotWidget() p3 = pg.PlotWidget() t = ParameterTree() t_action = ParameterTree() action_layout = QtGui.QGridLayout() # Create a grid layout to manage the widgets size and position layout = QtGui.QGridLayout() w.setLayout(layout) # A plot area (ViewBox + axes) for displaying the image # p1 = win.addPlot(title="Image here") # Item for displaying image data img = pg.ImageItem() p1.addItem(img) img2 = pg.ImageItem() p3.addItem(img2) hist.setImageItem(img) # Draggable line for setting isocurve level thrshcomp_line = pg.InfiniteLine(angle=0, movable=True, pen='g') hist.vb.addItem(thrshcomp_line) hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier thrshcomp_line.setValue(100) thrshcomp_line.setZValue(1000) # bring iso line above contrast controls ## Add widgets to the layout in their proper positions layout.addWidget(win, 1, 0) # text edit goes in middle-left layout.addWidget(p3, 0, 2) # text edit goes in middle-left layout.addWidget(t, 0, 0) # button goes in upper-left layout.addWidget(t_action, 1, 2) # list widget goes in bottom-left layout.addWidget(p1, 0, 1) # plot goes on right side, spanning 2 rows layout.addWidget(p2, 1, 1) # plot goes on right side, spanning 2 rows #enable only horizontal zoom for the traces component p2.setMouseEnabled(x=True, y=False) draw_contours() hist.setLevels(estimates.background_image.min(), estimates.background_image.max()) # Another plot area for displaying ROI data #win.nextRow() #p2 = win.addPlot(colspan=2) p2.setMaximumHeight(250) #win.resize(800, 800) #win.show() # set position and scale of image img.scale(1, 1) # img.translate(-50, 0) # zoom to fit imageo p1.autoRange() mode = "reset" p2.setTitle("mode: %s" % (mode)) thrshcomp_line.sigDragged.connect(lambda: draw_contours_overall(mode)) def imageHoverEvent(event): # Show the position, pixel, and value under the mouse cursor. global x, y, i, j, val pos = event.pos() i, j = pos.y(), pos.x() i = int(np.clip(i, 0, estimates.background_image.shape[0] - 1)) j = int(np.clip(j, 0, estimates.background_image.shape[1] - 1)) val = estimates.background_image[i, j, 0] ppos = img.mapToParent(pos) x, y = ppos.x(), ppos.y() # Monkey-patch the image to use our custom hover function. # This is generally discouraged (you should subclass ImageItem instead), # but it works for a very simple use like this. img.hoverEvent = imageHoverEvent def mouseClickEvent(event): global mode global x, y, i, j, val pos = img.mapFromScene(event.pos()) x = int(pos.x()) y = int(pos.y()) if x < 0 or x > estimates.dims[0] or y < 0 or y > estimates.dims[1]: # if the user click outside of the movie, jump out of the function return i, j = pos.y(), pos.x() i = int(np.clip(i, 0, estimates.background_image.shape[0] - 1)) j = int(np.clip(j, 0, estimates.background_image.shape[1] - 1)) val = estimates.background_image[i, j, 0] if mode == "neurons": show_neurons_clicked() p1.mousePressEvent = mouseClickEvent # A general rule in Qt is that if you override one mouse event handler, you must override all of them. def release(event): pass p1.mouseReleaseEvent = release def move(event): pass p1.mouseMoveEvent = move ## PARAMS params = [{'name': 'min_cnn_thr', 'type': 'float', 'value': 0.99, 'limits': (0, 1),'step':0.01}, {'name': 'cnn_lowest', 'type': 'float', 'value': 0.1, 'limits': (0, 1),'step':0.01}, {'name': 'rval_thr', 'type': 'float', 'value': 0.85, 'limits': (-1, 1),'step':0.01}, {'name': 'rval_lowest', 'type': 'float', 'value': -1, 'limits': (-1, 1),'step':0.01}, {'name': 'min_SNR', 'type': 'float', 'value': 2, 'limits': (0, 20),'step':0.1}, {'name': 'SNR_lowest', 'type': 'float', 'value': 0, 'limits': (0, 20),'step':0.1}, {'name': 'RESET', 'type': 'action'}, {'name': 'SHOW BACKGROUND', 'type': 'action'}, {'name': 'SHOW NEURONS', 'type': 'action'} ] ## Create tree of Parameter objects pars = Parameter.create(name='params', type='group', children=params) params_action = [{'name': 'Filter components', 'type': 'bool', 'value': True, 'tip': "Filter components"}, {'name': 'View components', 'type': 'list', 'values': ['All','Accepted', 'Rejected', 'Unassigned'], 'value': 'All'}, {'name': 'ADD GROUP', 'type': 'action'}, {'name': 'REMOVE GROUP', 'type': 'action'}, {'name': 'ADD SINGLE', 'type': 'action'}, {'name': 'REMOVE SINGLE', 'type': 'action'}, {'name': 'SAVE OBJECT', 'type': 'action'} ] pars_action = Parameter.create(name='params_action', type='group', children=params_action) t_action.setParameters(pars_action, showTop=False) t_action.setWindowTitle('Parameter Action') def reset_button(): global mode mode = "reset" p2.setTitle("mode: %s" % (mode)) # clear the upper right image zeros = np.zeros(estimates.dims, order='F') img2.setImage(make_color_img(zeros), autoLevels=False) draw_contours() pars.param('RESET').sigActivated.connect(reset_button) def show_background_button(): global bg_vline, min_background, max_background, background_num global mode, background_first_frame_scaled # clear thhe upper right image zeros = np.zeros(estimates.dims, order='F') img2.setImage(make_color_img(zeros), autoLevels=False) background_num = (background_num + 1) % estimates.f.shape[0] mode = "background" p2.setTitle("mode: %s %d" % (mode,background_num)) # display the first frame of the background background_first_frame = estimates.b[:, background_num].reshape(estimates.dims, order='F') min_background_first_frame = np.min(background_first_frame) max_background_first_frame = np.max(background_first_frame) background_first_frame_scaled = make_color_img(background_first_frame, min_max=(min_background_first_frame, max_background_first_frame)) img.setImage(background_first_frame_scaled,autoLevels=False) # draw the trace and the infinite line trace_background = estimates.f[background_num] p2.plot(trace_background, clear=True) bg_vline = pg.InfiniteLine(angle=90, movable=True) p2.addItem(bg_vline, ignoreBounds=True) bg_vline.setValue(0) bg_vline.sigPositionChanged.connect(show_background_update) def show_background_update(): global bg_index, min_background, max_background, background_scaled bg_index = int(bg_vline.value()) if bg_index > -1 and bg_index < estimates.f.shape[-1]: # upper left component scrolls through the frames of the background background = estimates.b[:,background_num].dot(estimates.f[background_num,bg_index]).reshape(estimates.dims, order='F') background_scaled=make_color_img(background, min_max=(min_background[background_num], max_background[background_num])) img.setImage(background_scaled, autoLevels=False) pars.param('SHOW BACKGROUND').sigActivated.connect(show_background_button) def show_neurons_button(): global mode, neuron_selected mode = "neurons" neuron_selected = False p2.setTitle("mode: %s" % (mode)) # clear the upper right image zeros = np.zeros(estimates.dims, order='F') img2.setImage(make_color_img(zeros), autoLevels=False) def show_neurons_clicked(): global nr_vline, nr_index global x,y,i,j,val,min_dist_comp,contour_single, neuron_selected, comp2_scaled neuron_selected = True distances = np.sum(((x,y)-estimates.cms[estimates.idx_components])**2, axis=1)**0.5 min_dist_comp = np.argmin(distances) contour_all =[cv2.threshold(img, np.int(thrshcomp_line.value()), 255, 0)[1] for img in estimates.img_components[estimates.idx_components]] contour_single = contour_all[min_dist_comp] # draw the traces (lower left component) estimates.components_to_plot = estimates.idx_components[min_dist_comp] p2.plot(estimates.C[estimates.components_to_plot] + estimates.YrA[estimates.components_to_plot], clear=True) # plot img (upper left component) img.setImage(estimates.background_image, autoLevels=False) draw_contours_update(estimates.background_image, img) # plot img2 (upper right component) comp2 = np.multiply(estimates.Cn, contour_single > 0) comp2_scaled = make_color_img(comp2, min_max=(np.min(comp2), np.max(comp2))) img2.setImage(comp2_scaled,autoLevels=False) draw_contours_update(comp2_scaled, img2) # set title for the upper two components p3.setTitle("pos: (%0.1f, %0.1f) component: %d value: %g dist:%f" % (x, y, estimates.components_to_plot, val, distances[min_dist_comp])) p1.setTitle("pos: (%0.1f, %0.1f) component: %d value: %g dist:%f" % (x, y, estimates.components_to_plot, val, distances[min_dist_comp])) # draw the infinite line nr_vline = pg.InfiniteLine(angle=90, movable=True) p2.addItem(nr_vline, ignoreBounds=True) nr_vline.setValue(0) nr_vline.sigPositionChanged.connect(show_neurons_update) nr_index = 0 def show_neurons_update(): global nr_index, frame_denoise_scaled, estimates, raw_mov_scaled global min_mov, max_mov, min_mov_denoise, max_mov_denoise if neuron_selected is False: return nr_index = int(nr_vline.value()) if nr_index > 0 and nr_index < mov[:,0,0].shape[0]: # upper left compoenent scrolls through the raw movie raw_mov = rotate90(mov[nr_index,:,:], right=True, vector=False) raw_mov_scaled = make_color_img(raw_mov, min_max=(min_mov,max_mov)) img.setImage(raw_mov_scaled, autoLevels=False) draw_contours_update(raw_mov_scaled, img) # upper right component scrolls through the denoised movie frame_denoise = estimates.A[:,estimates.idx_components].dot(estimates.C[estimates.idx_components,nr_index]).reshape(estimates.dims, order='F') frame_denoise_scaled = make_color_img(frame_denoise, min_max=(min_mov_denoise,max_mov_denoise)) img2.setImage(frame_denoise_scaled,autoLevels=False) draw_contours_update(frame_denoise_scaled, img2) pars.param('SHOW NEURONS').sigActivated.connect(show_neurons_button) def add_group(): estimates.accepted_list = np.union1d(estimates.accepted_list,estimates.idx_components) estimates.rejected_list = np.setdiff1d(estimates.rejected_list,estimates.idx_components) change(None, None) pars_action.param('ADD GROUP').sigActivated.connect(add_group) def remove_group(): estimates.rejected_list = np.union1d(estimates.rejected_list,estimates.idx_components) estimates.accepted_list = np.setdiff1d(estimates.accepted_list,estimates.idx_components) change(None, None) pars_action.param('REMOVE GROUP').sigActivated.connect(remove_group) def add_single(): estimates.accepted_list = np.union1d(estimates.accepted_list,estimates.components_to_plot) estimates.rejected_list = np.setdiff1d(estimates.rejected_list,estimates.components_to_plot) change(None, None) pars_action.param('ADD SINGLE').sigActivated.connect(add_single) def remove_single(): estimates.rejected_list = np.union1d(estimates.rejected_list,estimates.components_to_plot) estimates.accepted_list = np.setdiff1d(estimates.accepted_list,estimates.components_to_plot) change(None, None) pars_action.param('REMOVE SINGLE').sigActivated.connect(remove_single) def save_object(): global estimates, cnm_obj, rotation_flag print('Saving') ffll = F.getSaveFileName(filter='HDF5 (*.hdf5);;NWB (*.nwb)') print(ffll[0]) # rotate back if estimates.rotation == True: estimates.Cn = rotate90(estimates.Cn, right=False, vector=False) estimates.A = rotate90(estimates.A, right=False, vector=True, sparse=True) estimates.b = rotate90(estimates.b, right=False, vector=True) estimates.dims = (estimates.dims[1], estimates.dims[0]) estimates.rotation = False cnm_obj.estimates = estimates if os.path.splitext(ffll[0])[1] == '.hdf5': cnm_obj.save(ffll[0]) elif os.path.splitext(ffll[0])[1] == '.nwb': from pynwb import NWBHDF5IO with NWBHDF5IO(fpath, 'r') as io: nwb = io.read() raw_data_file = nwb.acquisition['TwoPhotonSeries'].external_file[0] cnm_obj.estimates.save_NWB(ffll[0], imaging_rate=cnm_obj.params.data['fr'], session_start_time=datetime.now(tzlocal()), raw_data_file=raw_data_file) pars_action.param('SAVE OBJECT').sigActivated.connect(save_object) def action_pars_activated(param, changes): change(None, None) pars_action.sigTreeStateChanged.connect(action_pars_activated) # If anything changes in the tree, print a message def change(param, changes): global estimates, pars, pars_action set_par = pars.getValues() if pars_action.param('Filter components').value(): for keyy in set_par.keys(): params_obj.quality.update({keyy: set_par[keyy][0]}) else: params_obj.quality.update({'cnn_lowest': .1, 'min_cnn_thr': 0.99, 'rval_thr': 0.85, 'rval_lowest': -1, 'min_SNR': 2, 'SNR_lowest': 0}) estimates.filter_components(mov, params_obj, dview=None, select_mode=pars_action.param('View components').value()) if mode == "background": return else: draw_contours() pars.sigTreeStateChanged.connect(change) change(None, None) # set params to default t.setParameters(pars, showTop=False) t.setWindowTitle('Parameter Quality') # END PARAMS # Display the widget as a new window w.show() # Start the Qt event loop app.exec_() # Rotate back if estimates.rotation == True: estimates.Cn = rotate90(estimates.Cn, right=False, vector=False) estimates.A = rotate90(estimates.A, right=False, vector=True, sparse=True) estimates.b = rotate90(estimates.b, right=False, vector=True) estimates.dims = (estimates.dims[1], estimates.dims[0]) cnm_obj.estimates = estimates estimates.rotation = False
agiovann/Constrained_NMF
bin/caiman_gui.py
Python
gpl-2.0
24,280
[ "NEURON" ]
bebc0d8dda08200c0fec6e83b846e25ae28a528e766f8536de5421b08b56ce7a
# -*- coding: utf-8 -*- #!/usr/bin/python # # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2007 Thom Sturgill # Copyright (C) 2007-2009 Brian G. Matherly # Copyright (C) 2008-2011 Rob G. Healey <robhealey1@gmail.com> # Copyright (C) 2008 Jason Simanek # Copyright (C) 2010 Jakim Friant # Copyright (C) 2015- Serge Noiraud # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ Web Calendar generator. """ #------------------------------------------------------------------------ # python modules #------------------------------------------------------------------------ import os, shutil import datetime import time import calendar # Python module #------------------------------------------------------------------------ # Set up logging #------------------------------------------------------------------------ import logging _LOG = logging.getLogger(".WebPage") #------------------------------------------------------------------------ # Gramps module #------------------------------------------------------------------------ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext from gramps.gen.lib import Date, Name, NameType, Person from gramps.gen.lib.date import Today from gramps.gen.const import PROGRAM_NAME, URL_HOMEPAGE from gramps.version import VERSION from gramps.gen.constfunc import win from gramps.gen.config import config from gramps.gen.plug.report import Report from gramps.gen.plug.report import utils from gramps.gen.plug.report import MenuReportOptions from gramps.gen.plug.report import stdoptions from gramps.gen.plug.menu import (BooleanOption, NumberOption, StringOption, EnumeratedListOption, FilterOption, PersonOption, DestinationOption, NoteOption) from gramps.gen.utils.config import get_researcher from gramps.gen.utils.alive import probably_alive from gramps.gen.datehandler import displayer as _dd from gramps.gen.display.name import displayer as _nd import gramps.plugins.lib.libholiday as libholiday from gramps.plugins.lib.libhtml import Html, xml_lang from gramps.plugins.lib.libhtmlconst import _CHARACTER_SETS, _CC, _COPY_OPTIONS from gramps.gui.pluginmanager import GuiPluginManager from gramps.gen.lib.date import gregorian # import styled notes from # src/plugins/lib/libhtmlbackend.py from gramps.plugins.lib.libhtmlbackend import HtmlBackend #------------------------------------------------------------------------ # constants #------------------------------------------------------------------------ # full clear line for proper styling FULLCLEAR = Html("div", class_="fullclear", inline=True) # Web page filename extensions _WEB_EXT = ['.html', '.htm', '.shtml', '.php', '.php3', '.cgi'] # Calendar stylesheet names _CALENDARSCREEN = 'calendar-screen.css' _CALENDARPRINT = 'calendar-print.css' PLUGMAN = GuiPluginManager.get_instance() CSS = PLUGMAN.process_plugin_data('WEBSTUFF') def _escape(string): """ replace character in text that html shows correctly special characters: & < and > """ string = string.replace('&', '&amp;') # must be the first string = string.replace('<', '&lt;') string = string.replace('>', '&gt;') return string # pylint: disable=unused-variable # pylint: disable=unused-argument #------------------------------------------------------------------------ # # WebCalReport # #------------------------------------------------------------------------ class WebCalReport(Report): """ Create WebCalReport object that produces the report. """ def __init__(self, database, options, user): Report.__init__(self, database, options, user) self._user = user stdoptions.run_private_data_option(self, options.menu) # class to do conversion of styled notes to html markup self._backend = HtmlBackend() self.options = options mgobn = lambda name: options.menu.get_option_by_name(name).get_value() self.set_locale(options.menu.get_option_by_name('trans').get_value()) stdoptions.run_date_format_option(self, options.menu) self.rlocale = self._locale self._ = self.rlocale.translation.sgettext self.html_dir = mgobn('target') self.title_text = mgobn('title') filter_option = options.menu.get_option_by_name('filter') self.filter = filter_option.get_filter() self.name_format = mgobn('name_format') self.ext = mgobn('ext') self.copy = mgobn('cright') self.css = mgobn('css') self.country = mgobn('country') self.start_dow = mgobn('start_dow') self.multiyear = mgobn('multiyear') self.start_year = mgobn('start_year') self.end_year = mgobn('end_year') if not self.multiyear: self.end_year = self.start_year if self.end_year < self.start_year: self.end_year = self.start_year self.maiden_name = mgobn('maiden_name') self.alive = mgobn('alive') self.birthday = mgobn('birthdays') self.anniv = mgobn('anniversaries') self.home_link = mgobn('home_link') self.event_list = [] self.month_notes = [mgobn('note_' + month) for month in ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']] self.encoding = mgobn('encoding') self.fullyear = True self.makeoneday = mgobn('makeoneday') # identify researcher name and e-mail address # as NarrativeWeb already does researcher = get_researcher() self.author = researcher.name if self.author: self.author = self.author.replace(',,,', '') self.email = researcher.email # set to today's date self.today = Today() self.warn_dir = True # Only give warning once. self.link_to_narweb = mgobn('link_to_narweb') self.narweb_prefix = mgobn('prefix') # self.calendar is a dict; key is the month number # Each entry in the dict is also a dict; key is the day number. # The day dict is a list of things to display for that day. # These things are: birthdays and anniversaries self.calendar = {} self.holidays = {} calendar.setfirstweekday(DOW_GRAMPS2ISO[self.start_dow]) def get_note_format(self, note): """ will get the note from the database, and will return either the styled text or plain note """ # retrieve the body of the note note_text = note.get() # styled notes htmlnotetext = self.styled_note(note.get_styledtext(), note.get_format()) text = htmlnotetext or Html("p", note_text) # return text of the note to its callers return text ################################################# # Will produce styled notes for WebCal by using: # src/plugins/lib/libhtmlbackend.py ################################################# def styled_note(self, styledtext, format_type): """ styledtext : assumed a StyledText object to write format_type : = 0 : Flowed, = 1 : Preformatted style_name : name of the style to use for default presentation """ text = str(styledtext) if not text: return '' s_tags = styledtext.get_tags() #FIXME: following split should be regex to match \n\s*\n instead? markuptext = self._backend.add_markup_from_styled(text, s_tags, split='\n\n') htmllist = Html("div", id="grampsstylednote") if format_type == 1: #preformatted, retain whitespace. #so use \n\n for paragraph detection #FIXME: following split should be regex to match \n\s*\n instead? htmllist += Html('pre', indent=None, inline=True) for line in markuptext.split('\n\n'): htmllist += Html("p") for realline in line.split('\n'): htmllist += realline htmllist += Html('br') elif format_type == 0: #flowed #FIXME: following split should be regex to match \n\s*\n instead? for line in markuptext.split('\n\n'): htmllist += Html("p") htmllist += line return htmllist def copy_file(self, from_fname, to_fname, to_dir=''): """ Copy a file from a source to a (report) destination. If to_dir is not present and if the target is not an archive, then the destination directory will be created. Normally 'to_fname' will be just a filename, without directory path. 'to_dir' is the relative path name in the destination root. It will be prepended before 'to_fname'. """ dest = os.path.join(self.html_dir, to_dir, to_fname) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if from_fname != dest: shutil.copyfile(from_fname, dest) elif self.warn_dir: self._user.warn( _("Possible destination error") + "\n" + _("You appear to have set your target directory " "to a directory used for data storage. This " "could create problems with file management. " "It is recommended that you consider using " "a different directory to store your generated " "web pages.")) self.warn_dir = False config.set('paths.website-directory', os.path.dirname(self.html_dir) + os.sep) def add_day_item(self, text, year, month, day, event, age_at_death, dead_event_date): """ adds birthdays, anniversaries, and holidays to their perspective lists text -- line to be added year, month, day -- date to add the text to event -- one of 'BirthDay', 'Anniversary', or 'Holiday' age_at_death -- The age in text. ie : 68 years, 6 months dead_event_date -- The date of the event used to calculate the age_at_death """ # This may happen for certain "about" dates. # Use first day of the month if day == 0: day = 1 # determine which dictionary to use??? if event in ['Birthday', 'Anniversary']: month_dict = self.calendar.get(month, {}) else: month_dict = self.holidays.get(month, {}) day_list = month_dict.get(day, []) if month > 0: try: event_date = Date(year, month, day) except ValueError: event_date = Date.EMPTY else: event_date = Date.EMPTY # Incomplete date.... day_list.append((text, event, event_date, age_at_death, dead_event_date)) month_dict[day] = day_list # determine which dictionary to add it to??? if event in ['Birthday', 'Anniversary']: self.calendar[month] = month_dict else: self.holidays[month] = month_dict def __get_holidays(self, year): """ Get the holidays for the specified country and year """ # _('translation') with self._user.progress(_("Web Calendar Report"), _('Calculating Holidays for year %04d') % year, 365) as step: holiday_table = libholiday.HolidayTable() country = holiday_table.get_countries()[self.country] holiday_table.load_holidays(year, country) for month in range(1, 13): for day in range(1, 32): holiday_names = holiday_table.get_holidays(month, day) for holiday_name in holiday_names: self.add_day_item(holiday_name, year, month, day, 'Holiday', None, None) step() def copy_calendar_files(self): """ Copies all the necessary stylesheets and images for these calendars """ # Copy the screen stylesheet if self.css and self.css != 'No style sheet': fname = CSS[self.css]["filename"] self.copy_file(fname, _CALENDARSCREEN, "css") # copy Navigation Menu Layout if Blue or Visually is being used if CSS[self.css]["navigation"]: # copy horizontal menus... fname = CSS["Horizontal-Menus"]["filename"] self.copy_file(fname, "calendar-menus.css", "css") # copy print stylesheet fname = CSS["Print-Default"]["filename"] self.copy_file(fname, _CALENDARPRINT, "css") imgs = [] # Mainz stylesheet graphics # will only be used if Mainz is slected as the stylesheet imgs += CSS[self.css]["images"] # copy copyright image # the proper way would be to call "filename", but it is NOT working... if 0 < self.copy <= len(_CC): imgs += [CSS["Copyright"]["filename"]] # copy Gramps favicon #2 imgs += [CSS["favicon2"]["filename"]] for from_path in imgs: fdir, fname = os.path.split(from_path) self.copy_file(from_path, fname, "images") def create_file(self, fname, subdir): """ Create a file in the html_dir tree. If the directory does not exist, create it. fname -- filename to be created subdir -- any subdirs to be added """ fname = os.path.join(self.html_dir, subdir, fname) if not _has_webpage_extension(fname): fname += self.ext destdir = os.path.dirname(fname) if not os.path.isdir(destdir): os.makedirs(destdir) output_file = open(fname, 'w', encoding=self.encoding, errors='xmlcharrefreplace') return output_file def close_file(self, output_file): """ will close whatever filename is passed to it """ output_file.close() def write_header(self, nr_up, title, body_id=None, add_print=True): """ This creates the header for the Calendars 'nr_up' - number of directory levels up, started from current page, to the root of the directory tree (i.e. to self.html_dir). title -- to be inserted into page header section add_print -- whether to add printer stylesheet or not * only webcalendar() and one_day() only! """ # number of subdirectories up to reach root subdirs = ['..'] * nr_up # Header contants xmllang = xml_lang() _meta1 = 'name ="viewport" content="width=device-width, '\ 'initial-scale=1.0, maximum-scale=1.0, user-scalable=1"' _meta2 = 'name ="apple-mobile-web-app-capable" content="yes"' _meta3 = 'name="generator" content="%s %s %s"' % ( PROGRAM_NAME, VERSION, URL_HOMEPAGE) _meta4 = 'name="author" content="%s"' % self.author # create additional meta tags meta = Html("meta", attr=_meta1) + ( Html("meta", attr=_meta2, indent=False), Html("meta", attr=_meta3, indent=False), Html("meta", attr=_meta4, indent=False) ) # begin each html page... page, head, body = Html.page(title, self.encoding, xmllang) # add body id tag if not None if body_id is not None: body.attr = "id = '%(idtag)s'" % {'idtag' : body_id} # Gramps favicon fname1 = "/".join(subdirs + ["images", "favicon2.ico"]) # _CALENDARSCREEN stylesheet fname2 = "/".join(subdirs + ["css", _CALENDARSCREEN]) # links for Gramps favicon and stylesheets links = Html("link", rel='shortcut icon', href=fname1, type="image/x-icon") + ( Html("link", href=fname2, type="text/css", media="screen", rel="stylesheet", indent=False) ) # add horizontal menu if css == Blue or Visually because # there is no menus? if CSS[self.css]["navigation"]: fname = "/".join(subdirs + ["css", "calendar-menus.css"]) links.extend( Html("link", href=fname, type="text/css", media="screen", rel="stylesheet", indent=False) ) # add printer stylesheet to webcalendar() and one_day() only if add_print: fname = "/".join(subdirs + ["css", _CALENDARPRINT]) links.extend( Html("link", href=fname, type="text/css", media="print", rel="stylesheet", indent=False) ) # add meta tags and links to head section head += (meta, links) # start header section and page title... with Html("div", id="header", role="Title-n-Navigation") as header: header += Html("h1", title, id="SiteTitle", inline=True) # Created for ? msg = None if self.author and self.email: msg = self._('the "WebCal" will be the potential-email Subject|' 'Created for %(html_email_author_start)s' 'WebCal%(html_email_author_end)s') % { 'html_email_author_start' : '<a href="mailto:' + self.email + '?subject=', 'html_email_author_end' : '">' + self.author + '</a>'} elif self.author: msg = self._('Created for %(author)s') % { 'author' : self.author} if msg: header += Html("p", msg, id="CreatorInfo") body += header return page, body def year_navigation(self, nr_up, currentsection): """ This will create the year navigation menu bar for a total of seventeen (17) years nr_up = number of directories up to reach root directory currentsection = proper styling of this navigation bar """ # limit number of years to eighteen (18) years and only one row of years nyears = ((self.end_year - self.start_year) + 1) num_years = nyears if 0 < nyears < 19 else 18 self.end_year = (self.start_year + 17) if nyears > 18 else self.end_year # begin year division and begin unordered list with Html("div", id="subnavigation", role="subnavigation") as submenu: unordered = Html("ul") for cal_year in range(self.start_year, (self.start_year + num_years)): url = '' # begin subdir level subdirs = ['..'] * nr_up subdirs.append(str(cal_year)) # each year will link to current month. # this will always need an extension added month = int(self.today.get_month()) full_month_name = self.rlocale.date_displayer.long_months[month] full_month_name = full_month_name.lower() # Note. We use '/' here because it is a URL, not a OS dependent # pathname. url = '/'.join(subdirs + [full_month_name]) + self.ext hyper = Html("a", self.rlocale.get_date(Date(cal_year)), href=url, title=str(cal_year)) # Figure out if we need <li class="CurrentSection"> # or just plain <li> check_cs = str(cal_year) == currentsection and\ 'class = "CurrentSection"' or False if check_cs: unordered.extend( Html("li", hyper, attr=check_cs, inline=True) ) else: unordered.extend( Html("li", hyper, inline=True) ) submenu += unordered return submenu def month_navigation(self, nr_up, year, currentsection, add_home): """ Will create and display the navigation menu bar nr_up = number of directories up to reach root directory year = year being created currentsection = month name being created for proper CSS styling add_home = if creating a link to home -- a link to root directory of website """ navs = [] # An optional link to a home page if self.home_link: navs.append((self.home_link, self._('Home'), add_home)) navs.extend((self.rlocale.date_displayer.long_months[int(month)], self.rlocale.date_displayer.short_months[int(month)], True) for month in range(1, 13)) # Add a link for year_glance() if requested navs.append(('fullyearlinked', self._('Year Glance'), self.fullyear)) # remove menu items if they are not True navs = [(u, n) for u, n, c in navs if c] # begin month subnavigation with Html("div", class_="wrapper", id="nav", role="navigation") as navigation: with Html("div", class_="container") as container: unordered = Html("ul", class_="menu") for url_fname, nav_text in navs: # Note. We use '/' here because it is a URL, not a OS # dependent pathname need to leave home link alone, # so look for it ... url_fname = url_fname.lower() url = url_fname add_subdirs = False if not (url.startswith('http:') or url.startswith('/')): add_subdirs = not any(url.endswith(ext) for ext in _WEB_EXT) # whether to add subdirs or not??? if add_subdirs: subdirs = ['..'] * nr_up subdirs.append(str(year)) url = '/'.join(subdirs + [url_fname]) if not _has_webpage_extension(url): url += self.ext # Figure out if we need <li class="CurrentSection"> or # just plain <li> check_cs = url_fname == currentsection and \ 'class = "CurrentSection"' or False if url == self.home_link: mytitle = self._("NarrativeWeb Home") elif url_fname == 'fullyearlinked': mytitle = self._('Full year at a Glance') else: mytitle = self._(url_fname) hyper = Html("a", nav_text, href=url, name=url_fname, title=mytitle) if check_cs: unordered.extend( Html("li", hyper, attr=check_cs, inline=True) ) else: unordered.extend( Html("li", hyper, inline=True) ) container += unordered navigation += container return navigation def calendar_build(self, cal, year, month, clickable=False): """ This does the work of building the calendar @param: cal - either "yg" year_glance(), or "wc" webcalendar() @param: year -- year being created @param: month - month number 1, 2, .., 12 """ date_displayer = self.rlocale.date_displayer # define names for long and short month names full_month_name = date_displayer.long_months[int(month)] abbr_month_name = date_displayer.short_months[int(month)] # dow (day-of-week) uses Gramps numbering, sunday => 1, etc start_dow = self.start_dow col2day = [(x-1)%7+1 for x in range(start_dow, start_dow + 7)] def get_class_for_daycol(col): """ Translate a Gramps day number into a HTMLclass """ day = col2day[col] if day == 1: return "weekend sunday" elif day == 7: return "weekend saturday" return "weekday" def get_name_for_daycol(col): """ Translate a Gramps day number into a HTMLclass """ day = col2day[col] return day_names[day] # Note. gen.datehandler has sunday => 1, monday => 2, etc # We slice out the first empty element. day_names = date_displayer.long_days # use self._ldd.long_days when # set_locale is used ... def __get_previous_month_day(year, month, day_col): if month == 1: prevmonth = calendar.monthcalendar((year - 1), 12) else: prevmonth = calendar.monthcalendar(year, (month - 1)) num_weeks = len(prevmonth) lastweek_prevmonth = prevmonth[(num_weeks - 1)] previous_month_day = lastweek_prevmonth[day_col] # return previous month day number based on day_col # day_col is based on range(0 - 6) return previous_month_day def __get_next_month_day(year, month, day_col): if month == 12: nextmonth = calendar.monthcalendar((year + 1), 1) else: nextmonth = calendar.monthcalendar(year, (month + 1)) firstweek_nextmonth = nextmonth[0] next_month_day = firstweek_nextmonth[day_col] # return next month day number based on day_col # day_col is based on range(0 - 6) return next_month_day # Begin calendar head. We'll use the capitalized name, because here it # seems appropriate for most countries. month_name = full_month_name.capitalize() th_txt = month_name if cal == 'wc': # webcalendar() if not self.multiyear: th_txt = '%s %s' % (month_name, self._get_date(Date(year))) # localized # begin calendar table and table head with Html("table", class_="calendar", id=month_name, role="Calendar-Grid") as table: thead = Html("thead") table += thead if clickable: name = th_txt + self.ext url = name.lower() linkable = Html("a", th_txt, href=url, name=url, title=th_txt) else: linkable = th_txt if not self.multiyear: self.end_year = self.start_year if month > 1: full_month_name = date_displayer.long_months[month-1] url = full_month_name.lower() + self.ext prevm = Date(int(year), int(month-1), 0) my_title = Html("a", _escape("<"), href=url, title=date_displayer.display(prevm)) elif self.multiyear and year > self.start_year: full_month_name = date_displayer.long_months[12] url = full_month_name.lower() + self.ext dest = os.path.join("../", str(year-1), url) prevm = Date(int(year-1), 12, 0) my_title = Html("a", _escape("<"), href=dest, title=date_displayer.display(prevm)) else: full_month_name = date_displayer.long_months[12] url = full_month_name.lower() + self.ext dest = os.path.join("../", str(self.end_year), url) prevy = Date(self.end_year, 12, 0) my_title = Html("a", _escape("<"), href=dest, title=date_displayer.display(prevy)) my_title += Html("</a>&nbsp;") if month < 12: full_month_name = date_displayer.long_months[month+1] url = full_month_name.lower() + self.ext nextd = Date(int(year), int(month+1), 0) my_title += Html("a", _escape(">"), href=url, title=date_displayer.display(nextd)) elif self.multiyear and year < self.end_year: full_month_name = date_displayer.long_months[1] url = full_month_name.lower() + self.ext dest = os.path.join("../", str(year+1), url) nextd = Date(int(year+1), 1, 0) my_title += Html("a", _escape(">"), href=dest, title=date_displayer.display(nextd)) else: full_month_name = date_displayer.long_months[1] url = full_month_name.lower() + self.ext dest = os.path.join("../", str(self.start_year), url) nexty = Date(self.start_year, 1, 0) my_title += Html("a", _escape(">"), href=dest, title=date_displayer.display(nexty)) my_title += Html("</a>") trow = Html("tr") + ( Html("th", my_title, class_='monthName', colspan=7, inline=True) ) thead += trow trow = Html("tr") + ( Html("th", linkable, class_='monthName', colspan=7, inline=True) ) thead += trow # Calendar weekday names header trow = Html("tr") thead += trow for day_col in range(7): dayclass = get_class_for_daycol(day_col) dayname = self._(get_name_for_daycol(day_col)) trow += Html("th", class_=dayclass, inline=True) + ( Html('abbr', dayname[0], title=dayname)) # begin table body tbody = Html("tbody") table += tbody # get first of the month and month information current_date, current_ord, monthinfo = get_first_day_of_month(year, month) # begin calendar table rows, starting week0 nweeks = len(monthinfo) for week_row in range(0, nweeks): week = monthinfo[week_row] # if you look this up in wikipedia, the first week # is called week0 trow = Html("tr", class_="week%02d" % week_row) tbody += trow # begin calendar day column for day_col in range(0, 7): dayclass = get_class_for_daycol(day_col) # day number, can also be a zero -- a day before or # after month day = week[day_col] # start the beginning variable for <td>, table cell tcell_id = "%s%02d" % (abbr_month_name, day) # add calendar date division datediv = Html("div", day, class_="date", inline=True) ### a day in the previous or next month ### if day == 0: # day in previous/ next month specday = __get_previous_month_day(year, month, day_col ) if week_row == 0 \ else __get_next_month_day(year, month, day_col) specclass = "previous " if week_row == 0 else "next " specclass += dayclass # continue table cell, <td>, without id tag tcell = Html("td", class_=specclass, inline=True) + ( Html("div", specday, class_="date", inline=True)) # normal day number in current month else: thisday = datetime.date.fromordinal(current_ord) # Something this month if thisday.month == month: holiday_list = self.holidays.get(month, {}).get(thisday.day, []) bday_anniv_list = self.calendar.get(month, {}).get(thisday.day, []) # date is an instance because of subtracting # abilities in date.py event_date = Date(thisday.year, thisday.month, thisday.day) # get events for this day day_list = get_day_list(event_date, holiday_list, bday_anniv_list, rlocale=self.rlocale) # is there something this day? if day_list: hilightday = 'highlight ' + dayclass tcell = Html("td", id=tcell_id, class_=hilightday) # Year at a Glance if cal == "yg": # make one day pages and hyperlink if self.makeoneday: # create yyyymmdd date string for # "One Day" calendar page filename fname_date = '%04d%02d%02d' % (year, month, day) fname_date += self.ext # create hyperlink to one_day() tcell += Html("a", datediv, href=fname_date, inline=True) # only year_glance() needs this to # create the one_day() pages self.one_day(event_date, fname_date, day_list) # just year_glance(), but no one_day() pages else: # continue table cell, <td>, # without id tag tcell = Html("td", class_=hilightday, inline=True) + ( # adds date division Html("div", day, class_="date", inline=True) ) # WebCal else: # add date to table cell tcell += datediv # list the events unordered = Html("ul") tcell += unordered for (nyears, date, text, event, notused, notused) in day_list: unordered += Html("li", text, inline=False if event == 'Anniversary' else True) # no events for this day else: # create empty day with date tcell = Html("td", class_=dayclass, inline=True) + ( # adds date division Html("div", day, class_="date", inline=True) ) # nothing for this month else: tcell = Html("td", class_=dayclass) + ( # adds date division Html("div", day, class_="date", inline=True) ) # attach table cell to table row # close the day column trow += tcell # change day number current_ord += 1 if cal == "yg": for weeks in range(nweeks, 6): # each calendar must have six weeks for proper styling # and alignment with Html("tr", class_="week%02d" % (weeks + 1)) as six_weeks: tbody += six_weeks for emptydays in range(7): six_weeks += Html("td", class_="emptyDays", inline=True) # return calendar table to its callers return table def webcalendar(self, year): """ This method provides information and header/ footer to the calendar month year -- year being created """ # do some error correcting if needed if self.multiyear: if self.end_year < self.start_year: self.end_year = self.start_year nr_up = 1 # Number of directory levels up to get to self.html_dir / root with self._user.progress(_("Web Calendar Report"), _('Formatting months ...'), 12) as step: for month in range(1, 13): cal_fname = self.rlocale.date_displayer.long_months[int(month)] cal_fname = cal_fname.lower() open_file = self.create_file(cal_fname, str(year)) # Add xml, doctype, meta and stylesheets # body has already been added to webcal already once webcal, body = self.write_header(nr_up, self.title_text) # create Year Navigation menu if self.multiyear and ((self.end_year - self.start_year) > 0): body += self.year_navigation(nr_up, str(year)) # Create Month Navigation Menu # identify currentsection for proper highlighting currentsection = _dd.long_months[month] body += self.month_navigation(nr_up, year, currentsection, True) # build the calendar content = Html("div", class_="content", id="WebCal") body += content monthly_calendar = self.calendar_build("wc", year, month) content += monthly_calendar # create note section for webcalendar() # One has to be minused because the array starts at zero, # but January =1 note = self.month_notes[month-1].strip() if note: note = self.database.get_note_from_gramps_id(note) note = self.get_note_format(note) # table foot section cal_foot = Html("tfoot") monthly_calendar += cal_foot trow = Html("tr") + ( Html("td", note, colspan=7, inline=True) ) cal_foot += trow # create blank line for stylesheets # create footer division section footer = self.write_footer(nr_up) body += (FULLCLEAR, footer) # send calendar page to web output # and close the file self.XHTMLWriter(webcal, open_file) step() def year_glance(self, year): """ This method will create the Full Year At A Glance Page... year -- year being created """ self.event_list = [] prv = None nxt = None evdte = None for month in sorted(self.calendar): vals = sorted(self.calendar.get(month, {})) if month == 0: # why ? continue for day in vals: event_date = "%04d%02d%02d" % (year, month, day) if evdte is None: evdte = event_date elif nxt is None: nxt = event_date self.event_list.append((evdte, prv, nxt)) else: prv = evdte evdte = nxt nxt = event_date self.event_list.append((evdte, prv, nxt)) self.event_list.append((nxt, evdte, None)) nr_up = 1 # Number of directory levels up to get to root # generate progress pass for "Year At A Glance" with self._user.progress(_("Web Calendar Report"), _('Creating Year At A Glance calendar'), 12) as step: open_file = self.create_file('fullyearlinked', str(year)) # page title title = self._("%(year)d, At A Glance") % {'year' : year} # Create page header # body has already been added to yearglance already once yearglance, body = self.write_header(nr_up, title, "fullyearlinked", False) # create Year Navigation menu if self.multiyear and ((self.end_year - self.start_year) > 0): body += self.year_navigation(nr_up, str(year)) # Create Month Navigation Menu # identify currentsection for proper highlighting body += self.month_navigation(nr_up, year, "fullyearlinked", True) msg = (self._('This calendar is meant to give you access ' 'to all your data at a glance compressed into one page. ' 'Clicking on a date will take you to a page that shows all' ' the events for that date, if there are any.\n')) # page description content = Html("div", class_="content", id="YearGlance") body += content content += Html("p", msg, id='description') for month in range(1, 13): # build the calendar monthly_calendar = self.calendar_build("yg", year, month, clickable=True) content += monthly_calendar # increase progress bar step() # create blank line for stylesheets # write footer section footer = self.write_footer(nr_up) body += (FULLCLEAR, footer) # send calendar page to web output # and close the file self.XHTMLWriter(yearglance, open_file) def one_day(self, event_date, fname_date, day_list): """ This method creates the One Day page for "Year At A Glance" event_date -- date for the listed events fname_date -- filename date from calendar_build() day_list -- a combination of both dictionaries to be able to create one day nyears, date, text, event -- are necessary for figuring the age or years married for each year being created... """ nr_up = 1 # number of directory levels up to get to root # get year and month from event_date for use in this section year = event_date.get_year() month = event_date.get_month() one_day_file = self.create_file(fname_date, str(year)) # page title title = self._('One Day Within A Year') # create page header oneday, body = self.write_header(nr_up, title, "OneDay") # create Year Navigation menu if self.multiyear and ((self.end_year - self.start_year) > 0): body += self.year_navigation(nr_up, str(year)) # Create Month Navigation Menu # identify currentsection for proper highlighting currentsection = _dd.long_months[month] body += self.month_navigation(nr_up, year, currentsection, True) # set date display as in user prevferences content = Html("div", class_="content", id="OneDay") body += content evt = fname_date[:8] found = (evt, None, None) for event in self.event_list: if event[0] == evt: found = event break my_title = Html() url = "#" if found[1] is not None: url = event[1] + self.ext prevd = Date(int(event[1][:4]), int(event[1][4:6]), int(event[1][6:])) my_title = Html("a", _escape("<"), href=url, title=self.rlocale.get_date(prevd)) else: my_title = Html('<em>&nbsp;&nbsp;</em>') my_title += Html("</a>&nbsp;") if found[2] is not None: url = event[2] + self.ext nextd = Date(int(event[2][:4]), int(event[2][4:6]), int(event[2][6:])) my_title += Html("a", _escape(">"), href=url, title=self.rlocale.get_date(nextd)) else: my_title += Html('<b>&nbsp;&nbsp;</b>') my_title += Html("</a>") content += Html("h3", my_title, inline=True) my_title = Html("span", " ") my_title += self.rlocale.date_displayer.display(event_date) my_title += Html("span", " ") content += Html("h3", my_title, inline=True) # list the events ordered = Html("ol") content += ordered for (nyears, date, text, event, age_at_death, dead_event_date) in day_list: ordered += Html("li", text, inline=False if event == 'Anniversary' else True) # create blank line for stylesheets # write footer section footer = self.write_footer(nr_up) body += (FULLCLEAR, footer) # send calendar page to web output # and close the file self.XHTMLWriter(oneday, one_day_file) def build_url_fname_html(self, fname, subdir=None, prefix=None): """ build the url for the file name with sub directories and extension """ return self.build_url_fname(fname, subdir, prefix) + self.ext def build_url_fname(self, fname, subdir, prefix=None): """ Create part of the URL given the filename and optionally the subdirectory. If the subdirectory is given, then two extra levels of subdirectory are inserted between 'subdir' and the filename. The reason is to prevent directories with too many entries. If 'prefix' is set, then is inserted in front of the result. The extension is added to the filename as well. Notice that we do NOT use os.path.join() because we're creating a URL. Imagine we run gramps on Windows (heaven forbits), we don't want to see backslashes in the URL. """ if win(): fname = fname.replace('\\', "/") subdirs = self.build_subdirs(subdir, fname) return (prefix or '') + "/".join(subdirs + [fname]) def build_subdirs(self, subdir, fname): """ If subdir is given, then two extra levels of subdirectory are inserted between 'subdir' and the filename. The reason is to prevent directories with too many entries. For example, this may return ['ppl', '8', '1'] given 'ppl', "aec934857df74d36618" """ subdirs = [] if subdir: subdirs.append(subdir) subdirs.append(fname[-1].lower()) subdirs.append(fname[-2].lower()) return subdirs def get_name(self, person, maiden_name=None): """ Return person's name, unless maiden_name given, unless married_name listed. person -- person to get short name from maiden_name -- either a woman's maiden name or man's surname """ # Get all of a person's names: primary_name = person.primary_name married_name = None names = [primary_name] + person.get_alternate_names() for name in names: if int(name.get_type()) == NameType.MARRIED: married_name = name break # Now, decide which to use: if maiden_name is not None: if married_name is not None: name = Name(married_name) else: name = Name(primary_name) surname_obj = name.get_primary_surname() surname_obj.set_surname(maiden_name) else: name = Name(primary_name) name.set_display_as(self.name_format) return _nd.display_name(name) def collect_data(self, this_year): """ This method runs through the data, and collects the relevant dates and text. """ db = self.database people = db.iter_person_handles() people = self.filter.apply(db, people, user=self._user) with self._user.progress(_("Web Calendar Report"), _("Reading database..."), len(people)) as step: for person in map(db.get_person_from_handle, people): step() family_list = person.get_family_handle_list() birth_ref = person.get_birth_ref() birth_date = Date() if birth_ref: birth_event = db.get_event_from_handle(birth_ref.ref) birth_date = birth_event.get_date_object() death_ref = person.get_death_ref() person_death = Date() age_at_death = None if death_ref and birth_date: death_event = db.get_event_from_handle(death_ref.ref) death_date = death_event.get_date_object() person_death = death_date if (birth_date != Date() and birth_date.is_valid() and death_date): age_at_death = death_date - birth_date age_at_death = age_at_death.format(dlocale=self.rlocale) # determine birthday information??? if (self.birthday and birth_date is not Date() and birth_date.is_valid()): birth_date = gregorian(birth_date) year = birth_date.get_year() month = birth_date.get_month() day = birth_date.get_day() # date to figure if someone is still alive # current year of calendar, month nd day is their birth # month and birth day prob_alive_date = Date(this_year, month, day) # add some things to handle maiden name: father_surname = None # husband, actually if person.gender == Person.FEMALE: # get husband's last name: if self.maiden_name in ['spouse_first', 'spouse_last']: if family_list: if self.maiden_name == 'spouse_first': fhandle = family_list[0] else: fhandle = family_list[-1] fam = db.get_family_from_handle(fhandle) father_handle = fam.get_father_handle() mother_handle = fam.get_mother_handle() if mother_handle == person.handle: if father_handle: father = db.get_person_from_handle( father_handle) if father is not None: father_surname = _regular_surname( person.gender, father.get_primary_name()) short_name = self.get_name(person, father_surname) alive = probably_alive(person, db, prob_alive_date) if (self.alive and alive) or not self.alive: # add link to NarrativeWeb if self.link_to_narweb: prfx = self.narweb_prefix text = str(Html("a", short_name, href=self.build_url_fname_html( person.handle, "ppl", prefix=prfx))) else: text = short_name if age_at_death is None: self.add_day_item(text, year, month, day, 'Birthday', age_at_death, birth_date) else: self.add_day_item(text, year, month, day, 'Birthday', age_at_death, person_death) # add anniversary if requested if self.anniv: for fhandle in family_list: fam = db.get_family_from_handle(fhandle) father_handle = fam.get_father_handle() mother_handle = fam.get_mother_handle() if father_handle == person.handle: spouse_handle = mother_handle else: continue # with next person if this was # the marriage event if spouse_handle: spouse = db.get_person_from_handle(spouse_handle) if spouse: spouse_name = self.get_name(spouse) short_name = self.get_name(person) death_ref = spouse.get_death_ref() spouse_death = Date() if death_ref: death_event = db.get_event_from_handle( death_ref.ref) death_date = death_event.get_date_object() if (death_date != Date() and death_date.is_valid()): spouse_death = death_date first_died = Date() if person_death == Date(): first_died = spouse_death elif spouse_death != Date(): first_died = person_death if spouse_death\ > person_death else spouse_death else: first_died = person_death # will return a marriage event or False if not # married any longer marriage_event = get_marriage_event(db, fam) if marriage_event: event_date = marriage_event.get_date_object() if (event_date is not Date() and event_date.is_valid()): event_date = gregorian(event_date) year = event_date.get_year() month = event_date.get_month() day = event_date.get_day() # date to figure if someone is still alive prob_alive_date = Date(this_year, month, day) wedding_age = None if first_died != Date(): wedding_age = first_died - event_date wedding_age = wedding_age.format( dlocale=self.rlocale) if self.link_to_narweb: spouse_name = str(Html("a", spouse_name, href=self.build_url_fname_html( spouse_handle, 'ppl', prefix=self.narweb_prefix))) short_name = str(Html("a", short_name, href=self.build_url_fname_html( person.handle, 'ppl', prefix=self.narweb_prefix))) alive1 = probably_alive(person, db, prob_alive_date) alive2 = probably_alive(spouse, db, prob_alive_date) if first_died == Date(): first_died = Date(0, 0, 0) if ((self.alive and alive1 and alive2) or not self.alive): mg = self._('%(spouse)s and %(person)s') text = mg % {'spouse' : spouse_name, 'person' : short_name} self.add_day_item(text, year, month, day, 'Anniversary', wedding_age, first_died) def write_footer(self, nr_up): """ Writes the footer section of the pages 'nr_up' - number of directory levels up, started from current page, to the root of the directory tree (i.e. to self.html_dir). """ # begin calendar footer with Html("div", id="footer", role="Footer-End") as footer: # Display date as user set in preferences msg = self._('Generated by %(gramps_home_html_start)s' 'Gramps%(html_end)s on %(date)s') % { 'gramps_home_html_start' : '<a href="' + URL_HOMEPAGE + '">', 'html_end' : '</a>', 'date' : self.rlocale.date_displayer.display(Today())} footer += Html("p", msg, id='createdate') copy_nr = self.copy text = '' if copy_nr == 0: if self.author: text = "&copy; %s %s" % (self.today.get_year(), self.author) elif 0 < copy_nr < len(_CC): subdirs = ['..'] * nr_up # Note. We use '/' here because it is a URL, # not a OS dependent pathname fname = '/'.join(subdirs + ['images'] + ['somerights20.gif']) text = _CC[copy_nr] % {'gif_fname' : fname} else: text = "&copy; %s %s" % (self.today.get_year(), self.author) footer += Html("p", text, id='copyright') # return footer to its callers return footer def XHTMLWriter(self, page, open_file): """ This function is simply to make the web page look pretty and readable It is not for the browser, but for us, humans """ # writes the file out from the page variable; Html instance # This didn't work for some reason, but it does in NarWeb: #page.write(partial(print, file=of.write)) page.write(lambda line: open_file.write(line + '\n')) # close the file now... self.close_file(open_file) def write_report(self): """ The short method that runs through each month and creates a page. """ # get data from database for birthdays/ anniversaries self.collect_data(self.start_year) # Copy all files for the calendars being created self.copy_calendar_files() if self.multiyear: # limit number of years to eighteen (18) years and only one row # of years nyears = ((self.end_year - self.start_year) + 1) num_years = nyears if 0 < nyears < 19 else 18 for cal_year in range(self.start_year, (self.start_year + num_years)): # initialize the holidays dict to fill: self.holidays = {} # get the information, zero is equal to None if self.country != 0: self.__get_holidays(cal_year) # create webcalendar() calendar pages self.webcalendar(cal_year) # create "Year At A Glance" and # "One Day" calendar pages if self.fullyear: self.year_glance(cal_year) if self.home_link: self.create_page_index() # a single year else: cal_year = self.start_year self.holidays = {} # get the information, first from holidays: if self.country != 0: self.__get_holidays(cal_year) # create webcalendar() calendar pages self.webcalendar(cal_year) # create "Year At A Glance" and # "One Day" calendar pages if self.fullyear: self.year_glance(cal_year) if self.home_link: self.create_page_index() def create_page_index(self): """ Create the page index called by the narrativeweb. """ output_file = self.create_file('index', "") # page title title = self._("My Family Calendar") nr_up = 0 # Create page header # body has already been added to yearglance already once index, body = self.write_header(nr_up, title, "index", False) # create Year Navigation menu current_year = time.strftime("%Y", time.gmtime()) body += self.year_navigation(nr_up, str(current_year)) # create blank line for stylesheets # write footer section footer = self.write_footer(nr_up) body += (FULLCLEAR, footer) # send calendar page to web output # and close the file self.XHTMLWriter(index, output_file) # ----------------------------------------------------------------------------- # WebCalOptions; Creates the Menu #------------------------------------------------------------------------------ class WebCalOptions(MenuReportOptions): """ Defines options and provides handling interface. """ def __init__(self, name, dbase): self.__db = dbase self.__pid = None self.__filter = None self.__links = None self.__prefix = None MenuReportOptions.__init__(self, name, dbase) self.__multiyear = None self.__start_year = None self.__end_year = None def add_menu_options(self, menu): """ Add options to the menu for the web calendar. """ self.__add_report_options(menu) self.__add_report2_options(menu) self.__add_content_options(menu) self.__add_notes_options(menu) self.__add_advanced_options(menu) def __add_report_options(self, menu): """ Options on the "Report Options" tab. """ category_name = _("Report Options") dbname = self.__db.get_dbname() default_dir = dbname + "_WEBCAL" target = DestinationOption(_("Destination"), os.path.join(config.get('paths.website-directory'), default_dir)) target.set_help(_("The destination directory for the web files")) target.set_directory_entry(True) menu.add_option(category_name, "target", target) title = StringOption(_('Calendar Title'), _('My Family Calendar')) title.set_help(_("The title of the calendar")) menu.add_option(category_name, "title", title) self.__filter = FilterOption(_("Filter"), 0) self.__filter.set_help( _("Select filter to restrict people that appear on calendar")) menu.add_option(category_name, "filter", self.__filter) self.__filter.connect('value-changed', self.__filter_changed) self.__pid = PersonOption(_("Filter Person")) self.__pid.set_help(_("The center person for the filter")) menu.add_option(category_name, "pid", self.__pid) self.__pid.connect('value-changed', self.__update_filters) self.__update_filters() ext = EnumeratedListOption(_("File extension"), ".html") for etype in _WEB_EXT: ext.add_item(etype, etype) ext.set_help(_("The extension to be used for the web files")) menu.add_option(category_name, "ext", ext) cright = EnumeratedListOption(_('Copyright'), 0) for index, copt in enumerate(_COPY_OPTIONS): cright.add_item(index, copt) cright.set_help(_("The copyright to be used for the web files")) menu.add_option(category_name, "cright", cright) css_list = sorted([(CSS[key]["translation"], CSS[key]["id"]) for key in list(CSS.keys()) if CSS[key]["user"]]) css = EnumeratedListOption(_('StyleSheet'), css_list[0][1]) for css_item in css_list: css.add_item(css_item[1], css_item[0]) css.set_help(_('The stylesheet to be used for the web pages')) menu.add_option(category_name, "css", css) def __add_report2_options(self, menu): """ Options on the "Report Options (2)" tab. """ category_name = _("Report Options (2)") # We must figure out the value of the first option before we can # create the EnumeratedListOption fmt_list = _nd.get_name_format() defaultnum = _nd.get_default_format() default = 0 for ind, val in enumerate(fmt_list): if val[0] == defaultnum: default = ind break name_format = EnumeratedListOption(_("Name format"), fmt_list[default][0]) for num, name, fmt_str, act in fmt_list: name_format.add_item(num, name) name_format.set_help(_("Select the format to display names")) menu.add_option(category_name, "name_format", name_format) stdoptions.add_private_data_option(menu, category_name, default=False) alive = BooleanOption(_("Include only living people"), True) alive.set_help(_("Include only living people in the calendar")) menu.add_option(category_name, "alive", alive) locale_opt = stdoptions.add_localization_option(menu, category_name) stdoptions.add_date_format_option(menu, category_name, locale_opt) def __add_content_options(self, menu): """ Options on the "Content Options" tab. """ category_name = _("Content Options") # set to today's date for use in menu, etc. today = Today() self.__multiyear = BooleanOption(_('Create multiple year calendars'), False) self.__multiyear.set_help(_('Whether to create Multiple year ' 'calendars or not.')) menu.add_option(category_name, 'multiyear', self.__multiyear) self.__multiyear.connect('value-changed', self.__multiyear_changed) self.__start_year = NumberOption(_('Start Year for the Calendar(s)'), today.get_year(), 1900, 3000) self.__start_year.set_help(_('Enter the starting year for the calendars' ' between 1900 - 3000')) menu.add_option(category_name, 'start_year', self.__start_year) self.__end_year = NumberOption(_('End Year for the Calendar(s)'), today.get_year(), 1900, 3000) self.__end_year.set_help(_('Enter the ending year for the calendars ' 'between 1900 - 3000.')) menu.add_option(category_name, 'end_year', self.__end_year) self.__multiyear_changed() country = EnumeratedListOption(_('Country for holidays'), 0) holiday_table = libholiday.HolidayTable() countries = holiday_table.get_countries() countries.sort() if (len(countries) == 0 or (len(countries) > 0 and countries[0] != '')): countries.insert(0, '') count = 0 for cntry in countries: country.add_item(count, cntry) count += 1 country.set_help(_("Holidays will be included for the selected " "country")) menu.add_option(category_name, "country", country) # Default selection ???? start_dow = EnumeratedListOption(_("First day of week"), 1) for count in range(1, 8): start_dow.add_item(count, _dd.long_days[count].capitalize()) start_dow.set_help(_("Select the first day of the week " "for the calendar")) menu.add_option(category_name, "start_dow", start_dow) maiden_name = EnumeratedListOption(_("Birthday surname"), "own") maiden_name.add_item('spouse_first', _("Wives use husband's surname " "(from first family listed)")) maiden_name.add_item('spouse_last', _("Wives use husband's surname " "(from last family listed)")) maiden_name.add_item("own", _("Wives use their own surname")) maiden_name.set_help(_("Select married women's displayed surname")) menu.add_option(category_name, "maiden_name", maiden_name) dbname = self.__db.get_dbname() default_link = '../../' + dbname + "_NAVWEB/index.html" home_link = StringOption(_('Home link'), default_link) home_link.set_help(_("The link to be included to direct the user to " "the main page of the web site")) menu.add_option(category_name, "home_link", home_link) birthdays = BooleanOption(_("Include birthdays"), True) birthdays.set_help(_("Include birthdays in the calendar")) menu.add_option(category_name, "birthdays", birthdays) anniversaries = BooleanOption(_("Include anniversaries"), True) anniversaries.set_help(_("Include anniversaries in the calendar")) menu.add_option(category_name, "anniversaries", anniversaries) def __add_notes_options(self, menu): """ Options on the "Months Notes" tabs. """ category_name = _("Jan - Jun Notes") note_jan = NoteOption(_('January Note')) note_jan.set_help(_("The note for the month of January")) menu.add_option(category_name, "note_jan", note_jan) note_feb = NoteOption(_('February Note')) note_feb.set_help(_("The note for the month of February")) menu.add_option(category_name, "note_feb", note_feb) note_mar = NoteOption(_('March Note')) note_mar.set_help(_("The note for the month of March")) menu.add_option(category_name, "note_mar", note_mar) note_apr = NoteOption(_('April Note')) note_apr.set_help(_("The note for the month of April")) menu.add_option(category_name, "note_apr", note_apr) note_may = NoteOption(_('May Note')) note_may.set_help(_("The note for the month of May")) menu.add_option(category_name, "note_may", note_may) note_jun = NoteOption(_('June Note')) note_jun.set_help(_("The note for the month of June")) menu.add_option(category_name, "note_jun", note_jun) category_name = _("Jul - Dec Notes") note_jul = NoteOption(_('July Note')) note_jul.set_help(_("The note for the month of July")) menu.add_option(category_name, "note_jul", note_jul) note_aug = NoteOption(_('August Note')) note_aug.set_help(_("The note for the month of August")) menu.add_option(category_name, "note_aug", note_aug) note_sep = NoteOption(_('September Note')) note_sep.set_help(_("The note for the month of September")) menu.add_option(category_name, "note_sep", note_sep) note_oct = NoteOption(_('October Note')) note_oct.set_help(_("The note for the month of October")) menu.add_option(category_name, "note_oct", note_oct) note_nov = NoteOption(_('November Note')) note_nov.set_help(_("The note for the month of November")) menu.add_option(category_name, "note_nov", note_nov) note_dec = NoteOption(_('December Note')) note_dec.set_help(_("The note for the month of December")) menu.add_option(category_name, "note_dec", note_dec) def __add_advanced_options(self, menu): """ Options for the advanced menu """ category_name = _('Advanced Options') encoding = EnumeratedListOption(_('Character set encoding'), _CHARACTER_SETS[0][1]) for eopt in _CHARACTER_SETS: encoding.add_item(eopt[1], eopt[0]) encoding.set_help(_('The encoding to be used for the web files')) menu.add_option(category_name, "encoding", encoding) makeoneday = BooleanOption(_('Create one day event pages for' ' Year At A Glance calendar'), False) makeoneday.set_help(_('Whether to create one day pages or not')) menu.add_option(category_name, 'makeoneday', makeoneday) self.__links = BooleanOption(_('Link to Narrated Web Report'), False) self.__links.set_help(_('Whether to link data to web report or not')) menu.add_option(category_name, 'link_to_narweb', self.__links) self.__links.connect('value-changed', self.__links_changed) dbname = self.__db.get_dbname() default_prefix = '../../' + dbname + "_NAVWEB/" self.__prefix = StringOption(_('Link prefix'), default_prefix) self.__prefix.set_help(_("A Prefix on the links to take you to " "Narrated Web Report")) menu.add_option(category_name, "prefix", self.__prefix) self.__links_changed() def __update_filters(self): """ Update the filter list based on the selected person """ gid = self.__pid.get_value() person = self.__db.get_person_from_gramps_id(gid) filter_list = utils.get_person_filters(person, False) self.__filter.set_filters(filter_list) def __filter_changed(self): """ Handle filter change. If the filter is not specific to a person, disable the person option """ filter_value = self.__filter.get_value() if 1 <= filter_value <= 4: # Filters 1, 2, 3 and 4 rely on the center person self.__pid.set_available(True) else: # The rest don't self.__pid.set_available(False) def __multiyear_changed(self): """ Handles the ability to print multiple year calendars or not? """ mgobn = lambda name: self.menu.get_option_by_name(name) self.__multiyear = mgobn('multiyear') self.__start_year = mgobn('start_year') self.__end_year = mgobn('end_year') if self.__start_year: self.__start_year.set_available(True) if self.__multiyear.get_value(): self.__end_year.set_available(True) else: self.__end_year.set_available(False) def __links_changed(self): """ Handle checkbox change. """ if self.__links.get_value(): self.__prefix.set_available(True) else: self.__prefix.set_available(False) def _regular_surname(sex, name): """ Returns a name string built from the components of the Name instance. """ surname = name.get_surname() suffix = name.get_suffix() if suffix: # TODO for Arabic, should the next line's comma be translated? surname = surname + ", " + suffix return surname # Simple utility list to convert Gramps day-of-week numbering # to calendar.firstweekday numbering DOW_GRAMPS2ISO = [-1, calendar.SUNDAY, calendar.MONDAY, calendar.TUESDAY, calendar.WEDNESDAY, calendar.THURSDAY, calendar.FRIDAY, calendar.SATURDAY] def get_marriage_event(db, family): """ marriage_event will either be the marriage event or False """ marriage_event = False for event_ref in family.get_event_ref_list(): event = db.get_event_from_handle(event_ref.ref) if event.type.is_marriage: marriage_event = event elif event.type.is_divorce: continue # return the marriage event or False to it caller return marriage_event def get_first_day_of_month(year, month): """ Compute the first day to display for this month. It can also be a day in the previous month. """ # first day of the month current_date = datetime.date(year, month, 1) # monthinfo is filled using standard Python library # calendar.monthcalendar. It fills a list of 7-day-lists. The first day # of the 7-day-list is determined by calendar.firstweekday. monthinfo = calendar.monthcalendar(year, month) current_ord = current_date.toordinal() - monthinfo[0].count(0) return current_date, current_ord, monthinfo def _has_webpage_extension(url): """ determine if a filename has an extension or not... url = filename to be checked """ return any(url.endswith(ext) for ext in _WEB_EXT) def get_day_list(event_date, holiday_list, bday_anniv_list, rlocale=glocale): """ Will fill day_list and return it to its caller: calendar_build() holiday_list -- list of holidays for event_date bday_anniv_list -- list of birthdays and anniversaries for event_date event_date -- date for this day_list 'day_list' - a combination of both dictionaries to be able to create one day nyears, date, text, event --- are necessary for figuring the age or years married for each day being created... rlocale -- the locale to use """ trans_text = rlocale.translation.sgettext # initialize day_list day_list = [] ################################################################## # birthday/ anniversary on this day # Date.EMPTY signifies an incomplete date for an event. See add_day_item() bday_anniv_list = [(t, e, d, n, x) for t, e, d, n, x in bday_anniv_list if d != Date.EMPTY] # number of years have to be at least zero bday_anniv_list = [(t, e, d, n, x) for t, e, d, n, x in bday_anniv_list if (event_date.get_year() - d.get_year()) >= 0] # a holiday # zero will force holidays to be first in list nyears = 0 for text, event, date, notused, notused in holiday_list: day_list.append((nyears, date, text, event, notused, notused)) # birthday and anniversary list for text, event, date, age_at_death, dead_event_date in bday_anniv_list: # number of years married, ex: 10 nyears = (event_date.get_year() - date.get_year()) # number of years for birthday, ex: 10 years age_str = event_date - date #age_str.format(precision=1, as_age=False, dlocale=rlocale) age_str = age_str.format(precision=1, as_age=False, dlocale=rlocale) # a birthday if event == 'Birthday': if age_at_death is not None: death_symbol = "&#10014;" # latin cross for html code trans_date = trans_text("Died %(death_date)s.") translated_date = rlocale.get_date(dead_event_date) mess = trans_date % {'death_date' : translated_date} age = ", <font size='+1' ><b>%s</b></font> <em>%s (%s)" % ( death_symbol, mess, age_at_death) else: # TRANSLATORS: expands to smth like "12 years old", # where "12 years" is already localized to your language age = ', <em>' date_y = date.get_year() trans_date = trans_text("Born %(birth_date)s.") old_date = trans_text('%s old') tranlated_date = rlocale.get_date(dead_event_date) age += old_date % str(age_str) if date_y != 0 else \ trans_date % { 'birth_date' : translated_date} txt_str = (text + age + '</em>') # an anniversary elif event == "Anniversary": if nyears == 0: txt_str = trans_text('%(couple)s, <em>wedding</em>') % { 'couple' : text} else: if age_at_death is not None: age = '%s %s' % (trans_text("Married"), age_at_death) txt_str = "%s, <em>%s" % (text, age) if isinstance(dead_event_date, Date) and dead_event_date.get_year() > 0: txt_str += " (" + trans_text("Until") + " " txt_str += rlocale.get_date(dead_event_date) txt_str += ")</em>" else: txt_str += "</em>" else: age = '<em>%s' % nyears # translators: leave all/any {...} untranslated ngettext = rlocale.translation.ngettext txt_str = ngettext("{couple}, {years} year anniversary", "{couple}, {years} year anniversary", nyears).format(couple=text, years=age) txt_str += "</em>" txt_str = Html('span', txt_str, class_="yearsmarried") day_list.append((nyears, date, txt_str, event, age_at_death, dead_event_date)) # sort them based on number of years # holidays will always be on top of event list day_list = sorted(day_list, key=lambda x: (isinstance(x[0], str), x[0])) # return to its caller calendar_build() return day_list
dermoth/gramps
gramps/plugins/webreport/webcal.py
Python
gpl-2.0
85,396
[ "Brian" ]
f18ac3ab7886222841e061e89dce63ab1219537841beda4fb3b2b35326ce6996
import argparse parser = argparse.ArgumentParser() parser.add_argument("mapfile", help="filename of mapfile") args = parser.parse_args() import cogent.parse.bowtie data = cogent.parse.bowtie.BowtieOutputParser( args.mapfile ) count = 0 for row in data: print row count += 1 if count > 20: break
humberto-ortiz/dmel-ercc
cogent-test.py
Python
gpl-3.0
327
[ "Bowtie" ]
bca0a4d89880d0226bcba689ea0ae92fe966388d1a8e187bff92aad408e9df47
# ============================================================================= # File: firenzecard.py # Author: Io Flament # Created: July 2017 # Last Modified: October 2017 # Description: Runs Exploratory Analysis of Firenzecard data # ============================================================================= import sys import pandas as pd import numpy as np import plotly from plotly.graph_objs import * import plotly.plotly as py import plotly.graph_objs as go sys.path.append('../src/') #from IPython.core.debugger import Tracer def get_national_museums(db_connection, export_to_csv, export_path): """ Get national museum data from DB """ df = pd.read_sql('select * from optourism.state_national_museum_visits', con=db_connection) if export_to_csv: df.to_csv(f"{export_path}_nationalmuseums_raw.csv", index=False) return df def get_firenze_data(db_connection, export_to_csv, export_path): """ Get FirenzeCard logs from DB """ df = pd.read_sql('select * from optourism.firenze_card_logs', con=db_connection) if export_to_csv: df.to_csv(f"{export_path}_firenzedata_raw.csv", index=False) return df def get_firenze_locations(db_connection, export_to_csv, export_path): """ Get latitude and longitude fields from DB """ df = pd.read_sql('select * from optourism.firenze_card_locations', con=db_connection) if export_to_csv: df.to_csv(f"{export_path}_firenzedata_locations.csv", index=False) return df def extract_features(db_connection, path_firenzedata, path_firenzelocations_data, export_to_csv, export_path): """ Feature extraction for FirenzeCard data Parameters ---------- connection: postgres connection path_firenzedata: path to firenze logs data csv file path_firenzelocations_data: path to firenzelocations data csv file export_to_csv: boolean export_path: path to export data Returns ------- 1. Pandas dataframe with extracted features: - entry_is_adult: is the user an adult or not? - is_card_with_minors: is this a card used by minors? - time: time - date: date - hour: hour of day - day_of_week: day of the week - time_until_next_museum: how much time elapsed until next museum visit on a card? - duration_of_use: how many total days/hours was a card used? - (museum id column): per museum, a feature indicating whether a person was in that museum or not. column number is indicative of museum id. - number of museums visited so far - persons_per_card_per_museum - day of use """ if path_firenzedata: df = pd.read_csv(path_firenzedata) else: df = get_firenze_data(db_connection, True, f"{export_path}_firenzedata_raw.csv") if path_firenzelocations_data: df_locations = pd.read_csv(path_firenzelocations_data) else: df_locations = get_firenze_locations(db_connection, True, f"{export_path}_firenzedata_locations.csv") df = pd.merge(df_locations, df, on=['museum_id', 'museum_name'], how='inner') df['entry_time'] = pd.to_datetime(df['entry_time']) df['time'] = pd.to_datetime(df['entry_time']).dt.time df['date'] = pd.to_datetime(df['entry_time']).dt.date df['hour'] = pd.to_datetime(df['entry_time']).dt.hour df['day_of_week'] = df['entry_time'].dt.dayofweek df = df.sort_values('entry_time', ascending=True) df['total_people'] = df['total_adults'] + df['minors'] # todo remove overnights from time_since_previous museum - to only count on given days df['time_since_previous_museum'] = df.groupby('user_id')['entry_time'].diff() df['time_since_previous_museum'] = df['time_since_previous_museum'].apply( lambda x: pd.Timedelta(x) / pd.Timedelta('1 hour')) df = df.sort_values('entry_time', ascending=True) df['total_duration_card_use'] = df[df.user_id.notnull()].groupby( 'user_id')['entry_time'].transform(lambda x: x.iat[-1] - x.iat[0]) df['total_duration_card_use'] = df['total_duration_card_use'].apply( lambda x: pd.Timedelta(x) / pd.Timedelta('1 hour')) df['entry_is_adult'] = np.where(df['total_adults'] == 1, 1, 0) df['is_card_with_minors'] = np.where(df['minors'] == 1, 1, 0) entrances_per_card_per_museum = pd.DataFrame(df.groupby('user_id', as_index=True)['museum_id']. value_counts().rename('entrances_per_card_per_museum')) df = pd.merge(entrances_per_card_per_museum.reset_index(), df, on=['user_id', 'museum_id'], how='inner') for n in range(1, df['museum_id'].nunique()): df['is_in_museum_' + str(n)] = np.where(df['museum_id'] == n, 1, 0) if export_to_csv: df.to_csv(f"{export_path}_firenzedata_feature_extracted.csv", index=False) return df def interpolate_on_timedelta(df, groupby_object,timedelta, timedelta_range=, count_column,timeunit, start_date, end_date): """ Interpolate data on a given timedelta """ df_interpolated = pd.DataFrame() if timedelta == 'day_of_week' or timedelta == 'hour': data = pd.DataFrame({timedelta: range(timedelta_range), groupby_object: [id] * timedelta_range}) df_interpolated = data.merge(df, how='outer', left_on=[timedelta, groupby_object], right_on=[timedelta, groupby_object]) df_interpolated = df_interpolated.fillna(0) if timedelta == 'date': columns = [groupby_object, count_column] data = pd.DataFrame(0, np.arange(timedelta_range), columns) full_id_days = data.reindex(pd.MultiIndex.from_product([df[groupby_object].unique(), pd.date_range(start_date, end_date, freq=timeunit)]), fill_value=0) full_id_days = full_id_days.reset_index() full_id_days.columns = ['drop this', timedelta, groupby_object, count_column] full_id_days = full_id_days.drop('drop this', 1) df_interpolated = pd.merge(full_id_days, df, how='right', on=[groupby_object, count_column, timedelta]) return df_interpolated def get_museum_entries_per_timedelta_and_plot(df, museum_list, me_names, timedelta, start_date, end_date, export_to_csv, export_path, plot): """ Get museum timeseries for a given timedelta and plot """ timedelta_range, timeunit = get_timedelta_range(df, timedelta, start_date, end_date) museum_dfs = {} plot_urls = {} museum_list.append('All Museums') for museum_name in museum_list[:]: if museum_name not in me_names: print('Wrong museum name! Please enter one of the following museums:') print(me_names) if museum_name != 'All Museums': df2 = df[df['short_name'].str.contains(museum_name)] else: df2 = df df2 = df2.groupby(['museum_id', 'short_name', timedelta], as_index=False) ['entrances_per_card_per_museum'].sum() df_interpolated = interpolate_on_timedelta(df2, 'museum_id', timedelta, timedelta_range, 'entrances_per_card_per_museum', timeunit) df_interpolated = df_interpolated.rename(columns={'entrances_per_card_per_museum': 'total_entries'}) df_interpolated['total_entries'] = df_interpolated['total_entries'].fillna(0) if export_to_csv: df_interpolated.to_csv(f"{export_path} total_entries_{museum_name}_per_{timedelta}_.csv", index=False) df_interpolated = df_interpolated.groupby([timedelta, 'museum_id'], as_index=False)['total_entries'].sum() if plot: trace1 = go.Bar( x=df_interpolated[timedelta], y=df_interpolated['total_entries']) data = [trace1] layout = go.Layout( title=museum_name, xaxis=dict( title=timedelta, titlefont=dict(family='Courier New, monospace', size=18, color='#7f7f7f')), # rangeselector=dict(), # rangeslider=dict(), # type='date'), yaxis=dict( title='Number of Museum Entries', titlefont=dict(family='Courier New, monospace', size=18, color='#7f7f7f')) ) fig = dict(data, layout) plot_url = py.plot(fig, filename=f"{museum_name}_{timedelta}_{start_date}_{end_date}", sharing='private', auto_open=False) plot_urls[museum_name] = plot_url museum_dfs[museum_name] = df_interpolated return museum_dfs, plot_urls def get_timedelta_range(df, tdr_timedelta, start_date, end_date): """ Get timedelta range and unit for generating museum timeseries (called by get_museum_entries_per_timedelta_and_plot) """ timedelta_options = ['day_of_week', 'hour', 'date'] df = df[df['date'].isin(pd.date_range(start_date, end_date))] timeunit = pd.DataFrame() timedelta_range = pd.DataFrame() if tdr_timedelta not in timedelta_options: print("Wrong timedelta!") tdr_timedelta = input("Input a timedelta: 'hour', 'day_of_week' or 'date' ") timeunit, timedelta_range = get_timedelta_range(df, tdr_timedelta, start_date, end_date) if tdr_timedelta == 'day_of_week': timedelta_range = 7 timeunit = [] if tdr_timedelta == 'hour': timedelta_range = 24 timeunit = [] if tdr_timedelta == 'date': delta = pd.to_datetime(end_date) - pd.to_datetime(start_date) timedelta_range = delta.days timeunit = 'D' return timedelta_range, timeunit def get_correlation_matrix(df, lst, corr_method, cm_timedelta, timedelta_subset, timedeltamin, timedeltamax, below_threshold, above_threshold, export_to_csv, export_path): """ Get correlation matrix of museum correlations and inverse correlations, for a given timedelta, at given thresholds """ if timedelta_subset: df = df[(df[cm_timedelta] >= timedeltamin) & (df[cm_timedelta] <= timedeltamax)] df = df.pivot(cm_timedelta, columns='museum_id', values='total_entries') m = df.corr(corr_method).stack() corr_matrix = m[m.index.get_level_values(0) != m.index.get_level_values(1)] high = pd.DataFrame(corr_matrix[corr_matrix > above_threshold]) inverse = pd.DataFrame(corr_matrix[corr_matrix < below_threshold]) high_corr = pd.DataFrame() high_corr['high_combinations_1'] = high.index.get_level_values(0) high_corr['high_combinations_2'] = high.index.get_level_values(1) high_corr['values'] = high.values high_corr = high_corr[np.isfinite(high_corr['values'])] mask1 = high_corr['high_combinations_1'].isin(lst) mask2 = high_corr['high_combinations_2'].isin(lst) high_corr = high_corr[mask1] high_corr = high_corr[mask2] inverse_corr = pd.DataFrame() inverse_corr['inverse_combinations_1'] = inverse.index.get_level_values(0) inverse_corr['inverse_combinations_2'] = inverse.index.get_level_values(1) inverse_corr['values'] = inverse.values inverse_corr = inverse_corr[np.isfinite(inverse_corr['values'])] mask1 = inverse_corr['inverse_combinations_1'].isin(lst) mask2 = inverse_corr['inverse_combinations_2'].isin(lst) inverse_corr = inverse_corr[mask1] inverse_corr = inverse_corr[mask2] if export_to_csv: corr_matrix.to_csv(f"{export_path}_correlated_museums_{cm_timedelta}_.csv", index=False) return m, high_corr, inverse_corr def plot_national_museum_entries(db_connection, export_to_csv, export_path, plotname): """ Plot National Museum Entries """ data = get_national_museums(db_connection, export_to_csv, export_path) data = data[data['visit_month'].isin(['June', 'July', 'August', 'September'])] data = data.sort_values(['visit_month'], ascending=True) trace1 = Bar( x=data.museum_id, y=data.total_visitors, name='FirenzeCard', marker=dict(color='#CC171D'), ) fig = go.Figure(data=go.Data([trace1])) plot_url = py.iplot(fig, plotname, sharing='private') return data, plot_url def plot_geomap_timeseries(df, df_timeseries, geomap_timedelta, date_to_plot, plotname, mapbox_access_token, min_timedelta, max_timedelta): """ Plot geographical mapbox of timeseries data, for a given day """ df = df[df['date'] == date_to_plot] df = df[['museum_id', 'latitude', 'longitude', 'short_name']].drop_duplicates() df2 = pd.merge(df, df_timeseries, on=['museum_id'], how='inner') df2 = df2[[geomap_timedelta, "total_entries", 'latitude', 'longitude', 'short_name']] df2['short_name'][df2.total_entries == 0] = float('nan') df2['latitude'][df2.total_entries == 0] = float('nan') df2['longitude'][df2.total_entries == 0] = float('nan') df2.set_index('short_name', inplace=True) df2['short_name'] = df2.index df2['name_entries'] = df2['short_name'].astype(str) + ': ' + df2['total_entries'].astype(str) df2 = df2[df2.hour >= min_timedelta] df2 = df2[df2.hour <= max_timedelta] data = [] for hour in list(df2[geomap_timedelta].unique()): trace = dict( lat=df2[df2[geomap_timedelta] == hour]['latitude'], lon=df2[df2[geomap_timedelta] == hour]['longitude'], name=hour, mode='marker', marker=dict(size=7), text=df2[df2[geomap_timedelta] == hour]['name_entries'], type='scattermapbox', hoverinfo='text' ) data.append(trace) museums = list([ dict( args=[{ 'mapbox.center.lat': 43.768, 'mapbox.center.lon': 11.262, 'mapbox.zoom': 12, 'annotations[0].text': 'Museums in Florence' }], label='Florence', method='relayout' ) ]) m = df2[['latitude', 'longitude']].drop_duplicates() for museum, row in m.iterrows(): desc = [] for col in m.columns: if col not in ['latitude', 'longitude']: if str(row[col]) not in ['None', 'nan', '']: desc.append(col + ': ' + str(row[col]).strip("'")) desc.insert(0, museum) museums.append( dict( args=[{ 'mapbox.center.lat': row['latitude'], 'mapbox.center.lon': float(str(row['longitude']).strip("'")), 'mapbox.zoom': 14, }], label=museum, method='relayout' ) ) updatemenus = list([ dict( buttons=list([ dict( args=['mapbox.style', 'light'], label='Map', method='relayout' ), dict( args=['mapbox.style', 'satellite-streets'], label='Satellite', method='relayout' ) ]), direction='up', x=0.75, xanchor='left', y=0.05, yanchor='bottom', bgcolor='#ffffff', bordercolor='#000000', font=dict(size=11) ), ]) layout = Layout( showlegend=True, autosize=False, hovermode='closest', mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=dict( lat=43.768, lon=11.262 ), pitch=0, zoom=12 ), ) layout['updatemenus'] = updatemenus fig = dict(data=data, layout=layout) plot_url = py.iplot(fig, plotname, sharing='private', auto_open=False) return df2, plot_url def plot_fc_and_statemuseum_monthly_timeseries(df_date, db_connection, plotname): """ Plot Firenzecard and State Museum monthly aggregate timeseries. """ # Histogram of Monthly total museum entry data for Firenze Card and National State Museums statemuseum_data = get_national_museums(db_connection, export_to_csv=True, export_path='../src/output/') statemuseum_data = statemuseum_data[(statemuseum_data['visit_month'] == 'June') | (statemuseum_data['visit_month'] == 'July') | (statemuseum_data['visit_month'] == 'August') | (statemuseum_data['visit_month'] == 'September')] states_months = statemuseum_data.groupby('visit_month', as_index=False)['total_visitors'].sum().to_frame() # todo clean this up fc_june = df_date['All Museums'][(df_date['All Museums']['date'] > '2016-06-01') & (df_date['All Museums']['date'] < '2016-06-31')]['total_entries'].sum() fc_july = df_date['All Museums'][(df_date['All Museums']['date'] > '2016-07-01') & (df_date['All Museums']['date'] < '2016-07-31')]['total_entries'].sum() fc_august = df_date['All Museums'][(df_date['All Museums']['date'] > '2016-08-01') & (df_date['All Museums']['date'] < '2016-08-31')]['total_entries'].sum() fc_september = df_date['All Museums'][(df_date['All Museums']['date'] > '2016-09-01') & (df_date['All Museums']['date'] < '2016-09-30')]['total_entries'].sum() df2 = pd.DataFrame() df2['month'] = ['June', 'July', 'August', 'September'] df2['firenzecard_entries'] = [fc_june, fc_july, fc_august, fc_september] df2['state_entries'] = [states_months[states_months['visit_month'] == 'June']['total_visitors'], states_months[states_months['visit_month'] == 'July']['total_visitors'], states_months[states_months['visit_month'] == 'August']['total_visitors'], states_months[states_months['visit_month'] == 'September']['total_visitors']] trace1 = Bar( x=df2.month, y=df2.firenzecard_entries, name='FirenzeCard' ) trace2 = Bar( x=df2.month, y=df2.state_entries, name='State Museums' ) fig = go.Figure(data=go.Data([trace1, trace2])) plot_url = py.iplot(fig, plotname, sharing='private') return df2, plot_url def get_timelines_of_usage(df_hour, df_date, df_dow, hour_min, hour_max): """ Get timelines of usage of Firenzecard data. """ df_hour = df_hour[(df_hour['hour'] >= hour_min) & (df_hour['hour'] <= hour_max)] # How many users are there per day / hour / day-of-week on average across all museums, over the entire summer? df2_date = df_date.groupby('date', as_index=False)['total_entries'].mean() df2_hour = df_hour.groupby('hour', as_index=False)['total_entries'].mean() df2_dow = df_dow.groupby('day_of_week', as_index=False)['total_entries'].mean() return df2_hour, df2_dow, df2_date def plot_museum_aggregate_entries(df, plotname): """ Plot total museum entries over entries summer 2016, for each museum. """ df2 = df.groupby('short_name', as_index=True).sum()['total_people'].to_frame() df2.sort_values('total_people', inplace=True, ascending=True) trace = Bar( x=df2.index, y=df2['total_people'], marker=dict(color='#CC171D'), ) fig = go.Figure(data=go.Data([trace])) plot_url = py.iplot(fig, plotname, sharing='private', auto_open=False) return df2, plot_url def plot_museums_visited_per_card(df, plotname): """ Plot frequency plot of number of unique museums visited per card """ df2 = df[['user_id', 'entry_is_adult', 'museum_id', 'date']] df2 = df2.groupby(['user_id'], as_index=True).museum_id.nunique().rename('total_museums_per_card').to_frame() trace1 = go.Histogram(x=df2.total_museums_per_card, xbins=dict(start=np.min(df2.total_museums_per_card) - 0.25, size=0.5, end=np.max(df2.total_museums_per_card)), marker=dict(color='#CC171D')) layout = go.Layout( title="Total number of museums visited per card", legend=dict( traceorder='normal', font=dict( family='sans-serif', size=12, color='#000' ), bgcolor='#E2E2E2', bordercolor='#FFFFFF', borderwidth=2 ) ) fig = go.Figure(data=go.Data([trace1]), layout=layout) plot_url1 = py.iplot(fig, plotname, sharing='private', auto_open=False) return df2, plot_url1 def plot_day_of_activation(df, plotname): """ Plots Aggregate of Day of Activation. """ # todo sort order in logical day order dotw = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'} df2 = df[df['adults_first_use'] == 1][['user_id', 'day_of_week']] df2 = df2.groupby('user_id', as_index=False).mean()['day_of_week'].map(dotw).to_frame() df2 = df2['day_of_week'].value_counts().to_frame() # todo fix the X axis labeling so it's not hardcoded! trace = go.Bar(x=['Tuesday', 'Wednesday', 'Friday', 'Thursday', 'Satuday', 'Sunday', 'Monday'], y=df2.day_of_week, marker=dict(color='#CC171D')) layout = go.Layout( title="Day of Firenze Card Activation", xaxis=dict( title='Day of the Week', nticks=7, ticks='outside', ), yaxis=dict( title='Number of Cards Activated', ticks='outside', ) ) fig = go.Figure(data=go.Data([trace]), layout=layout) plot_url = py.iplot(fig, plotname, sharing='private', auto_open=False) return df2, plot_url
DSSG2017/florence
src/features/firenzecard.py
Python
mit
22,572
[ "VisIt" ]
549b2b95a324e3410b04daee5df0b288d35f98112284eb3db25d3f4669164204
from __future__ import print_function ############################################################################## # # Author: Alejandro Molina-Sanchez # Run real-time simulations with Yambo # # Warning: Real-time simulations requires several data folders for running # properly. Before using these scripts compulsively, it is recommended # to understand the different run levels. # # Instructions: # The dictionary 'job' stores the variable of the calculation # calculation : 'collisions', 'pump', 'dissipation' # folder-col : collision data # folder-run : results (only work if collisions have been previously calculated) # DG : True or False if we use the double-grid # nodes : cpu-dependent variable # cores : " # ############################################################################## #from __future__ import print_function from builtins import str from yambopy import * from schedulerpy import * import argparse # Select the run-level : 'collision', 'pump', 'dissipation' parser = argparse.ArgumentParser(description='Real-time simulation') parser.add_argument('-c' ,'--collisions' ,action="store_true") parser.add_argument('-p' ,'--pump' ,action="store_true") parser.add_argument('-d' ,'--dissipation',action="store_true") args = parser.parse_args() yambo_rt = 'yambo_rt' folder = 'rt-6x6' # Generation of the input file #os.system('cd %s; mkdir -p inputs' % folder) if args.collisions: print('Collisions') run = YamboIn('%s -r -e -v hsex'%yambo_rt,folder=folder) elif args.pump: print('Time-dependent with electric field') run = YamboIn('%s -q p'%yambo_rt,folder=folder) elif args.dissipation: print('Time-dependent with electric field and electron-phonon scattering') run = YamboIn('%s -s p -q p'%yambo_rt,folder=folder) else: print('Invalid calculation type') exit() # Proportionality constant of the DOS(T) def dos_temperature(temperature): ac, bc, cc = 0.506760, 0.000069, 0.000002 av, bv, cv = 0.437618, 0.000070, 0.000002 dos_c = ac + bc*temperature + cc*temperature**2 dos_v = av + bv*temperature + cv*temperature**2 return [dos_c,dos_v] job = dict() job['radiative'] = False job['folder-col'] = 'col-hxc' # name of collisions folder (path folder/folder-col) # the input file and run-folder names are defined at the end job['folder-gkkp'] = 'gkkp' job['DG'] = (False,'dg-60x60') # Double-grid (True|False) and DG folder job['nodes'] = 1 job['cores'] = 12 job['ppn'] = job['cores'] job['threads'] = job['cores']*job['nodes'] job['name'] = 'MoS2-dynamics' job['yambo_module'] = 'yambo/master-intel' job['temperature'] = 0 # System Common variables run['DBsIOoff'] = "GF P J" #run['DBsIOoff'] = "GF CARRIERs" run['RT_CPU'] = "%s.1.1.1" % (job['nodes']*job['cores']) # [PARALLEL] CPUs for each role run['RT_ROLEs'] = "k.b.q.qp" # [PARALLEL] CPUs roles (k,b,q,qp) run['HXC_Potential'] = "HARTREE+SEX" # [SC] SC HXC Potential #run['RT_Threads'] = 1 # Collision variables if args.collisions: run['FFTGvecs'] = [20 ,'Ha'] run['EXXRLvcs'] = [1000,'mHa'] # Equivalent to BSENGBlk in the BSE run-level run['HARRLvcs'] = [20 ,'Ha'] # Equivalent to BSENGexx in the BSE run-level run['CORRLvcs'] = [1000,'mHa'] # run['COLLBands'] = [25,28] run['NGsBlkXs'] = [1000,'mHa'] run['BndsRnXs'] = [1, 60] run['RandQpts'] = 1000000 # Only in layers run['RandGvec'] = [ 1 , 'RL' ] run['CUTGeo'] = 'box z' # Only in layers run['CUTBox'] = [0,0,38] run['X_all_q_CPU'] = "1.%d.1.1" % (job['nodes']*job['cores']) # [PARALLEL] CPUs for each role run['X_all_q_ROLEs'] = "q.k.c.v" # [PARALLEL] CPUs roles (q,k,c,v) #run.arguments.append('ALLGHAR') run.write('%s/collisions.in'%folder) # Common time-dependent variable if args.pump or args.dissipation: run['RTBands'] = [25,28] #run['GfnQP_Wv'] = [0.0,dos_temperature(job['temperature'])[1],0.00] # Only for dissipation #run['GfnQP_Wc'] = [0.0,dos_temperature(job['temperature'])[0],0.00] run['GfnQP_Wv'] = [0.025,0.0,0.0] run['GfnQP_Wc'] = [0.025,0.0,0.0] run['GfnQP_E'] = [1.04588, 1.00, 1.00] # [EXTQP BSK BSS] E parameters (c/v) eV|adim|adim # Time-propagation run['RTstep'] = [5.0,'as'] # Real-time step run['NETime'] = [600,'fs'] # Simulation duration run['Integrator'] = "RK2 RWA" run['IOtime'] = [ [ 50.0, 00.10, 1.00], 'fs' ] # [RT] Time between to consecutive I/O (J,P,CARRIERs - GF - OUTPUT) #run['IOtime'] = [ [ 0.10, 0.10, 1.00], 'fs' ] # [RT] Time between to consecutive I/O (J,P,CARRIERs - GF - OUTPUT) # Pump Pulse run['Field1_Int'] = [ 1E3 , 'kWLm2'] # Intensity pulse run['Field1_Dir'] = [0.0,1.0,0.0] # Polarization pulse run['Field1_Dir_circ'] = [1.0,0.0,0.0] # Polarization pulse (second axis for circular) run['Field1_pol'] = "linear" # Polarization type (linear or circular) run['Field1_kind'] = "QSSIN" # [RT Field1] Kind(SIN|RES|ANTIRES|GAUSS|DELTA|QSSIN) run['Field1_Damp'] = [ 70.0,'fs'] # Damping (width of pulse) run['Field1_Freq'] = [[2.0,2.0],'eV'] if job['radiative']: run.arguments.append('el_photon_scatt') # Pumping with finite pulse and electron-phonon dissipation if args.dissipation: # Interpolation run['BoseTemp'] = [ job['temperature'], 'K'] run['LifeExtrapSteps'] = [ [0.05,0.05], 'fs' ] # Extrapolation time for phonon-assisted dissipation run['ElPhModes'] = [ 1, 9] run.arguments.append('LifeExtrapolation') # Commented: Lifetimes are constant # Run -- Creating print('Collisions ',job['folder-col']) print('Number of nodes ',job['nodes']) print('Number of cores ',job['cores']) oarsub = oarsub(nodes=job['nodes'],core=job['cores'],dependent=0,name=job['name'],walltime="24:00:00") oarsub.add_command('module load %s'%job['yambo_module']) oarsub.add_command('export OMP_NUM_THREADS=1') # Collisions if args.collisions: oarsub.add_command('cd %s; mpirun -hostfile \$OAR_NODEFILE %s -F collisions.in -J %s -C %s'%(folder,yambo_rt,job['folder-col'],job['folder-col'])) oarsub.write('%s/collisions.ll' % folder ) oarsub.run() print('running yambo-collision') # Time-dependent without dissipation if args.pump: # name of run - change here if you want different variables if run['Field1_kind'] == 'DELTA': job['folder-run'] = 'DELTA-%.0e' % ( run['Field1_Int'][0]) else: job['folder-run'] = '%s' %(run['Field1_kind']) job['folder-run'] += '-%.0e-%sfs-%seV-%sK' % ( run['Field1_Int'][0], run['Field1_Damp'][0], run['Field1_Freq'][0][0],job['temperature']) # writing input file os.system('mkdir -p %s/%s'%(folder,job['folder-run'])) run.write('%s/%s/pulse.in'% (folder,job['folder-run'])) # submission script oarsub.add_command('cd %s/%s; mpirun -hostfile \$OAR_NODEFILE %s -F pulse.in -J \'pulse,..//%s\' -C pulse -I \'../\''%(folder,job['folder-run'],yambo_rt,job['folder-col']) ) oarsub.write('%s/%s/pulse.ll'%(folder,job['folder-run'])) oarsub.run() print('running Dynamics without dissipation in folder: ' + str(job['folder-run'])) # Time-dependent with dissipation if args.dissipation: # name of run - change here if you want different variables if run['Field1_kind'] == 'DELTA': job['folder-run'] = 'DELTA-D-%.0e' % ( run['Field1_Int'][0] ) else: job['folder-run'] = '%s' %(run['Field1_kind']) job['folder-run'] += '-D-%seV-%sK-%sfs' % ( run['Field1_Freq'][0][0],job['temperature'],run['LifeExtrapSteps'][0][0]) #job['folder-run'] += '-D-%.0e-%sfs-%seV-%sK' % ( run['Field1_Int'][0], run['Field1_Damp'][0], run['Field1_Freq'][0][0],job['temperature']) if job['DG'][0]: job['folder-run'] += '-DG' # writing input file os.system('mkdir -p %s/%s'%(folder,job['folder-run'])) run.write('%s/%s/pulse.in'% (folder,job['folder-run'])) # submission script if job['DG'][0]: oarsub.add_command('cd %s/%s; mpirun -hostfile \$OAR_NODEFILE %s -F pulse.in -J \'pulse,..//%s,..//%s,..//%s\' -C pulse -I \'../\''%(folder,job['folder-run'],yambo_rt,job['folder-col'],job['folder-gkkp'],job['DG'][1]) ) print('Double Grid enabled') else: oarsub.add_command('cd %s/%s; mpirun -hostfile \$OAR_NODEFILE %s -F pulse.in -J \'pulse,..//%s,..//%s\' -C pulse -I \'../\''%(folder,job['folder-run'],yambo_rt,job['folder-col'],job['folder-gkkp']) ) oarsub.write('%s/%s/pulse.ll'%(folder,job['folder-run'])) oarsub.run() print('running Dynamics with dissipation in folder: ' + str(job['folder-run']))
alexmoratalla/yambopy
scripts/realtime/rt-pulse.py
Python
bsd-3-clause
8,650
[ "Yambo" ]
dcdcf54f5ca3368413654d24e610b872666b1d6c634cac5c31ee7390e4876f22
# freeseer - vga/presentation capture software # # Copyright (C) 2011, 2013 Free and Open Source Software Learning Centre # http://fosslc.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # For support, questions, suggestions or any other inquiries, visit: # http://github.com/Freeseer/freeseer/ ''' Ogg Icecast ----------- A streaming plugin which records sends an Ogg stream to an icecast server. @author: Thanh Ha ''' # GStreamer import pygst pygst.require("0.10") import gst # PyQt from PyQt4.QtCore import SIGNAL # Freeseer from freeseer.framework.multimedia import Quality from freeseer.framework.plugin import IOutput from freeseer.framework.config import Config, options # .freeseer-plugin custom import widget class OggIcecastConfig(Config): """Configuration class for OggIcecast Plugin.""" ip = options.StringOption("127.0.0.1") port = options.IntegerOption(8000) password = options.StringOption("hackme") mount = options.StringOption("stream.ogg") audio_quality = options.FloatOption(0.3) video_bitrate = options.IntegerOption(2400) class OggIcecast(IOutput): name = "Ogg Icecast" os = ["linux", "linux2"] type = IOutput.BOTH recordto = IOutput.STREAM extension = "ogg" tags = None CONFIG_CLASS = OggIcecastConfig configurable = True AUDIO_MIN = -0.1 AUDIO_RANGE = 1.1 def get_output_bin(self, audio=True, video=True, metadata=None): bin = gst.Bin() if metadata is not None: self.set_metadata(metadata) # Muxer muxer = gst.element_factory_make("oggmux", "muxer") bin.add(muxer) icecast = gst.element_factory_make("shout2send", "icecast") icecast.set_property("ip", self.config.ip) icecast.set_property("port", self.config.port) icecast.set_property("password", self.config.password) icecast.set_property("mount", self.config.mount) bin.add(icecast) # # Setup Audio Pipeline # if audio: audioqueue = gst.element_factory_make("queue", "audioqueue") bin.add(audioqueue) audioconvert = gst.element_factory_make("audioconvert", "audioconvert") bin.add(audioconvert) audiocodec = gst.element_factory_make("vorbisenc", "audiocodec") audiocodec.set_property("quality", self.config.audio_quality) bin.add(audiocodec) # Setup metadata vorbistag = gst.element_factory_make("vorbistag", "vorbistag") # set tag merge mode to GST_TAG_MERGE_REPLACE merge_mode = gst.TagMergeMode.__enum_values__[2] if metadata is not None: # Only set tag if metadata is set vorbistag.merge_tags(self.tags, merge_mode) vorbistag.set_tag_merge_mode(merge_mode) bin.add(vorbistag) # Setup ghost pads audiopad = audioqueue.get_pad("sink") audio_ghostpad = gst.GhostPad("audiosink", audiopad) bin.add_pad(audio_ghostpad) # Link elements audioqueue.link(audioconvert) audioconvert.link(audiocodec) audiocodec.link(vorbistag) vorbistag.link(muxer) # # Setup Video Pipeline # if video: videoqueue = gst.element_factory_make("queue", "videoqueue") bin.add(videoqueue) videocodec = gst.element_factory_make("theoraenc", "videocodec") videocodec.set_property("bitrate", self.config.video_bitrate) bin.add(videocodec) videopad = videoqueue.get_pad("sink") video_ghostpad = gst.GhostPad("videosink", videopad) bin.add_pad(video_ghostpad) videoqueue.link(videocodec) videocodec.link(muxer) # # Link muxer to icecast # muxer.link(icecast) return bin def set_metadata(self, data): ''' Populate global tag list variable with file metadata for vorbistag audio element ''' self.tags = gst.TagList() for tag in data.keys(): if(gst.tag_exists(tag)): self.tags[tag] = data[tag] else: #self.core.logger.log.debug("WARNING: Tag \"" + str(tag) + "\" is not registered with gstreamer.") pass def get_widget(self): if self.widget is None: self.widget = widget.ConfigWidget() return self.widget def get_video_quality_layout(self): """Returns a layout with the video quality config widgets for configtool to use.""" return self.get_widget().get_video_quality_layout() def get_audio_quality_layout(self): """Returns a layout with the audio quality config widgets for configtool to use.""" return self.get_widget().get_audio_quality_layout() def __enable_connections(self): self.widget.connect(self.widget.lineedit_ip, SIGNAL('editingFinished()'), self.set_ip) self.widget.connect(self.widget.spinbox_port, SIGNAL('valueChanged(int)'), self.set_port) self.widget.connect(self.widget.lineedit_password, SIGNAL('editingFinished()'), self.set_password) self.widget.connect(self.widget.lineedit_mount, SIGNAL('editingFinished()'), self.set_mount) self.widget.connect(self.widget.spinbox_audio_quality, SIGNAL('valueChanged(double)'), self.audio_quality_changed) self.widget.connect(self.widget.spinbox_video_quality, SIGNAL('valueChanged(int)'), self.video_bitrate_changed) def widget_load_config(self, plugman): self.get_config() self.widget.lineedit_ip.setText(self.config.ip) self.widget.spinbox_port.setValue(self.config.port) self.widget.lineedit_password.setText(self.config.password) self.widget.lineedit_mount.setText(self.config.mount) # Finally enable connections self.__enable_connections() def set_ip(self): self.config.ip = str(self.widget.lineedit_ip.text()) self.config.save() def set_port(self, port): self.config.port = port self.config.save() def set_password(self): self.config.password = str(self.widget.lineedit_password.text()) self.config.save() def set_mount(self): self.config.mount = str(self.widget.lineedit_mount.text()) self.config.save() def audio_quality_changed(self): """Called when a change to the SpinBox for audio quality is made""" self.config.audio_quality = self.widget.spinbox_audio_quality.value() self.config.save() def set_audio_quality(self, quality): self.get_config() if quality == Quality.LOW: self.config.audio_quality = self.AUDIO_MIN + (self.AUDIO_RANGE * Quality.LOW_AUDIO_FACTOR) elif quality == Quality.MEDIUM: self.config.audio_quality = self.AUDIO_MIN + (self.AUDIO_RANGE * Quality.MEDIUM_AUDIO_FACTOR) elif quality == Quality.HIGH: self.config.audio_quality = self.AUDIO_MIN + (self.AUDIO_RANGE * Quality.HIGH_AUDIO_FACTOR) if self.widget_config_loaded: self.widget.spinbox_audio_quality.setValue(self.config.audio_quality) self.config.save() def video_bitrate_changed(self): """Called when a change to the SpinBox for video bitrate is made""" self.config.video_bitrate = self.widget.spinbox_video_quality.value() self.config.save() def set_video_bitrate(self, bitrate): self.get_config() if self.widget_config_loaded: self.widget.spinbox_video_quality.setValue(bitrate) self.config.video_bitrate = bitrate self.config.save() ### ### Translations ### def retranslate(self): self.widget.label_ip.setText(self.gui.app.translate('plugin-icecast', 'IP')) self.widget.label_port.setText(self.gui.app.translate('plugin-icecast', 'Port')) self.widget.label_password.setText(self.gui.app.translate('plugin-icecast', 'Password')) self.widget.label_mount.setText(self.gui.app.translate('plugin-icecast', 'Mount'))
Freeseer/freeseer
src/freeseer/plugins/output/ogg_icecast/__init__.py
Python
gpl-3.0
8,804
[ "VisIt" ]
6bac858ff9c6a1aaecc9142fd2b928edc549c275ae2db601d4eb860c10c221fc
# coding=utf-8 # Copyright 2022 The Google Research 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. # python3 """Defines the probit regression target spec.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools from typing import Callable import tensorflow.compat.v2 as tf import tensorflow_probability as tfp from hmc_swindles.targets import data from hmc_swindles.targets import joint_distribution_posterior from hmc_swindles.targets import target_spec tfd = tfp.distributions tfb = tfp.bijectors __all__ = [ 'probit_regression', ] def probit_regression( dataset_fn, name='probit_regression', ): """Bayesian probit regression with a Gaussian prior. Args: dataset_fn: A function to create a classification data set. The dataset must have binary labels. name: Name to prepend to ops created in this function, as well as to the `code_name` in the returned `TargetDensity`. Returns: target: `TargetDensity`. """ with tf.name_scope(name) as name: dataset = dataset_fn() num_train_points = dataset.train_features.shape[0] num_test_points = dataset.test_features.shape[0] have_test = num_test_points > 0 # Add bias. train_features = tf.concat( [dataset.train_features, tf.ones([num_train_points, 1])], axis=-1) train_labels = tf.convert_to_tensor(dataset.train_labels) test_features = tf.concat( [dataset.test_features, tf.ones([num_test_points, 1])], axis=-1) test_labels = tf.convert_to_tensor(dataset.test_labels) num_features = int(train_features.shape[1]) root = tfd.JointDistributionCoroutine.Root zero = tf.zeros(num_features) one = tf.ones(num_features) def model_fn(features): weights = yield root(tfd.Independent(tfd.Normal(zero, one), 1)) probits = tf.einsum('nd,...d->...n', features, weights) yield tfd.Independent(tfd.ProbitBernoulli(probits=probits), 1) train_joint_dist = tfd.JointDistributionCoroutine( functools.partial(model_fn, features=train_features)) test_joint_dist = tfd.JointDistributionCoroutine( functools.partial(model_fn, features=test_features)) dist = joint_distribution_posterior.JointDistributionPosterior( train_joint_dist, (None, train_labels)) expectations = { 'params': target_spec.expectation( fn=lambda params: params[0], human_name='Parameters', ) } if have_test: expectations['test_nll'] = target_spec.expectation( fn=lambda params: ( # pylint: disable=g-long-lambda -test_joint_dist.sample_distributions(value=params) [0][-1].log_prob(test_labels)), human_name='Test NLL', ) expectations['per_example_test_nll'] = target_spec.expectation( fn=lambda params: ( # pylint: disable=g-long-lambda -test_joint_dist.sample_distributions(value=params) [0][-1].distribution.log_prob(test_labels)), human_name='Per-example Test NLL', ) return target_spec.TargetDensity.from_distribution( distribution=dist, constraining_bijectors=(tfb.Identity(),), expectations=expectations, code_name='{}_{}'.format(dataset.code_name, name), human_name='{} Probit Regression'.format(dataset.human_name), )
google-research/google-research
hmc_swindles/targets/probit_regression.py
Python
apache-2.0
3,954
[ "Gaussian" ]
bacd26ca608e1de9c6f03dfb179800f13c16702887f4d537bbec98e0f3d733f4
# -*- coding: utf-8 -*- import pytest from io import StringIO from trapp.log import Log from trapp.importer import Importer from trapp.import_game import ImporterGames from trapp.import_goal import ImporterGoals from trapp.import_lineup import ImporterLineups from trapp.import_player import ImporterPlayers def test_importer_init(excel): log = Log('test.log') importer = Importer(excel, log) assert isinstance(importer, Importer) assert importer.log.name == 'test.log' def test_importer_correctValues(excel): log = Log('test.log') importer = Importer(excel, log) assert importer.correctValues() is True def test_importer_checkData_sheets(excel_sheets): with pytest.raises(RuntimeError) as excinfo: log = Log('test.log') importer = Importer(excel_sheets, log) assert 'more than one worksheet' in str(excinfo.value) def test_importer_checkFields_empty(excel_empty): with pytest.raises(RuntimeError) as excinfo: log = Log('test.log') importer = Importer(excel_empty, log) assert 'nothing to import' in str(excinfo.value) def test_importer_checkFields(excel): log = Log('test.log') importer = Importer(excel, log) requiredFields = (['foo', 'bar']) assert importer.checkFields(requiredFields) is True with pytest.raises(RuntimeError) as excinfo: requiredFields = (['foo', 'none']) importer.checkFields(requiredFields) assert 'missing the following columns' in str(excinfo.value) def test_importer_disambiguatePlayers(excel, monkeypatch): # Mocked user input mock_input = StringIO(u'1234\n') # Sample record record = { 'playername': 'Bogus Player' } # Run test log = Log('test.log') importer = ImporterGoals(excel, log) monkeypatch.setattr('sys.stdin', mock_input) result = importer.disambiguatePlayers(record, [0]) assert result == 1234 def test_importer_generic_importRecord(excel): log = Log('test.log') importer = Importer(excel, log) dummyRecord = 'Dummy Record' assert importer.importRecord(dummyRecord) is True # def test_importer_doImport(excel): # log = Log('test.log') # importer = Importer(excel, log) # assert importer.doImport() is True def test_importer_lookupPlayerID_valid(excel): log = Log('test.log') importer = ImporterGoals(excel, log) # We don't worry about invalid data formats, as those are caught by player object event = {'playername': 'Man', 'TeamID': 2, 'GameID': 1, 'Event': 1} event = importer.lookupPlayerID(event) assert event['PlayerID'] == 3 assert importer.skipped == 0 def test_importer_lookupPlayerID_owngoal(excel): log = Log('test.log') importer = ImporterGoals(excel, log) # We don't worry about invalid data formats, as those are caught by player object event = {'playername': 'Man', 'TeamID': 1, 'GameID': 1, 'Event': 6, 'OpponentID': 2} event = importer.lookupPlayerID(event) assert event['PlayerID'] == 3 assert importer.skipped == 0 def test_importer_lookupPlayerID_valid(excel, monkeypatch): # Mock user input mock_input = StringIO(u'0\n') # Sample record event = {'playername': 'Invalid Player', 'TeamID': 2, 'GameID': 1, 'Event': 1} # Run test log = Log('test.log') importer = ImporterGoals(excel, log) monkeypatch.setattr('sys.stdin', mock_input) assert importer.lookupPlayerID(event) is False assert importer.skipped == 1 def test_importer_lookupTeamID(excel): log = Log('test.log') importer = Importer(excel, log) needle = 'Columbus Crew' assert importer.lookupTeamID(needle) == 1 with pytest.raises(RuntimeError) as excinfo: needle = 'Columbus Magic' importer.lookupTeamID(needle) assert 'Team not found: ' in str(excinfo.value) with pytest.raises(RuntimeError) as excinfo: needle = 'Duplicate Sample Team' importer.lookupTeamID(needle) assert 'Ambiguous team name: ' in str(excinfo.value) def test_importer_parseAssists(excel): log = Log('test_parseAssists.log') importer = ImporterGoals(excel, log) game = 1 team = 1 # Test single assist record = [] minute = 78 assists = 'Player' assert importer.parseAssists(record, minute, assists, game, team) == [{'GameID': 1, 'TeamID': 1, 'playername': 'Player', 'MinuteID': 78, 'Event': 2, 'Notes': ''}] # Test two assists record = [] assists = 'Player,Potter' assert importer.parseAssists(record, minute, assists, game, team) == [{'GameID': 1, 'TeamID': 1, 'playername': 'Player', 'MinuteID': 78, 'Event': 2, 'Notes': ''}, {'GameID': 1, 'TeamID': 1, 'playername': 'Potter', 'MinuteID': 78, 'Event': 3, 'Notes': ''}] # Test too many assists record = [] assert importer.skipped == 0 assists = 'Player,Potter,Rains' assert importer.parseAssists(record, minute, assists, game, team) == [] assert importer.skipped == 1 def test_importer_parseOneGoal(excel): log = Log('test.log') importer = ImporterGoals(excel, log) game = 1 team = 1 opponent = 2 goals = "" # assert importer.parseGoals(goals) == [{}] goals = "Player (unassisted) 78" assert importer.parseOneGoal(goals, game, team, opponent) == [{'playername': 'Player', 'MinuteID': 78, 'Event': 1, 'Notes': '', 'GameID': 1, 'TeamID': 1, 'OpponentID': 2}] goals = "Player (penalty) 78" assert importer.parseOneGoal(goals, game, team, opponent) == [{'playername': 'Player', 'MinuteID': 78, 'Event': 1, 'Notes': 'penalty kick', 'GameID': 1, 'TeamID': 1, 'OpponentID': 2}] goals = "Player (Potter) 78" assert importer.parseOneGoal(goals, game, team, opponent) == [{'playername': 'Player', 'MinuteID': 78, 'Event': 1, 'Notes': '', 'GameID': 1, 'TeamID': 1, 'OpponentID': 2}, {'playername': 'Potter', 'MinuteID': 78, 'Event': 2, 'Notes': '', 'GameID': 1, 'TeamID': 1}] goals = "Player (Potter, Rains) 78" assert importer.parseOneGoal(goals, game, team, opponent) == [{'playername': 'Player', 'MinuteID': 78, 'Event': 1, 'Notes': '', 'GameID': 1, 'TeamID': 1, 'OpponentID': 2}, {'playername': 'Potter', 'MinuteID': 78, 'Event': 2, 'Notes': '', 'GameID': 1, 'TeamID': 1}, {'playername': 'Rains', 'MinuteID': 78, 'Event': 3, 'Notes': '', 'GameID': 1, 'TeamID': 1}] goals = "Player (own goal) 78" assert importer.parseOneGoal(goals, game, team, opponent) == [{'playername': 'Player', 'MinuteID': 78, 'Event': 6, 'Notes': 'own goal', 'GameID': 1, 'TeamID': 1, 'OpponentID': 2}] def test_importer_parseMinuteDoesNothing(excel): log = Log('test.log') importer = ImporterLineups(excel, log) assert importer.parseMinute(15) == 15 assert importer.parseMinute(str(45)) == 45 assert importer.parseMinute('89') == 89 def test_importer_parseMinuteRemovesSingleQuote(excel): log = Log('test.log') importer = ImporterLineups(excel, log) assert importer.parseMinute("64'") == 64 def test_importer_parseMinuteFixesStoppageTime(excel): log = Log('test.log') importer = ImporterLineups(excel, log) assert importer.parseMinute('46+') == 45 assert importer.parseMinute('91+') == 89 assert importer.parseMinute('106+') == 105 assert importer.parseMinute('122+') == 119 def test_importer_parseLineup(excel, lineup): game = 1 team = 1 duration = 90 log = Log('test.log') importer = ImporterLineups(excel, log) assert hasattr(importer, 'starters') is False importer.parseLineup(lineup, game, team, duration) assert hasattr(importer, 'starters') is True assert len(importer.starters) == 11 def test_importer_parseLineupFailsWhenShort(excel, lineup_short): game = 1 team = 1 duration = 90 log = Log('test.log') importer = ImporterLineups(excel, log) assert importer.errored == 0 importer.parseLineup(lineup_short, game, team, duration) assert importer.errored == 1 def test_importer_parsePlayer(excel, lineup): # Need to test parsePlayer's ability to deal with strings of player(s) game = 1 team = 1 duration = 90 log = Log('test.log') importer = ImporterLineups(excel, log) player = 'Sample Player' result = importer.parsePlayer(player, game, team, duration) assert len(result) == 1 assert result == [{'PlayerID': 15, 'PlayerName': 'Sample Player', 'TimeOn': 0, 'TimeOff': 90, 'Ejected': False, 'GameID': 1, 'TeamID': 1}] player = "Sample Player (Substitution 50')" result = importer.parsePlayer(player, game, team, duration) assert len(result) == 2 player = 'Sample Player (First Substitution 50 (Second Substitution 76))' result = importer.parsePlayer(player, game, team, duration) assert len(result) == 3 player = 'Sample Player (First Substitution 50 (Second Substitution 76 (Third Substitution 92+)))' result = importer.parsePlayer(player, game, team, duration) assert len(result) == 4 player = 'Sample Player (First Substitution 50 (Second Substitution 76 (Third Substitution 84 (sent off 88))))' result = importer.parsePlayer(player, game, team, duration) assert len(result) == 4 assert result[3]['PlayerName'] == 'Third Substitution' assert result[3]['Ejected'] is True assert result[3]['TimeOn'] == 84 assert result[3]['TimeOff'] == 88 def test_importer_parsePlayerRemoveTime(excel, lineup): log = Log('test.log') importer = ImporterLineups(excel, log) player = 'Sample Player' player = importer.parsePlayerRemoveTime(player) assert player == 'Sample Player' player = 'Sample Player 56' player = importer.parsePlayerRemoveTime(player) assert player == 'Sample Player' def test_importer_parsePlayerSplit(excel): log = Log('test.log') importer = ImporterLineups(excel, log) string = 'Player Name' assert importer.parsePlayerSplit(string) == ['Player Name'] string = 'Player Name (Substitute 63)' assert importer.parsePlayerSplit(string) == ['Player Name', 'Substitute 63'] string = 'Sample Player (First Substitution 50 (Second Substitution 76 (Third Substitution 84 (sent off 88))))' assert importer.parsePlayerSplit(string) == ['Sample Player', 'First Substitution 50', 'Second Substitution 76', 'Third Substitution 84', 'sent off 88'] def test_importer_processMissingRecords(excel): log = Log('test.log') importer = Importer(excel, log) assert len(importer.missing) == 0 assert importer.skipped == 0 importer.processMissingRecord('Missing Record', 0) assert len(importer.missing) == 1 assert importer.skipped == 1 importer.processMissingRecord('Another Missing Record', 0) assert len(importer.missing) == 2 assert importer.skipped == 2 importer.processMissingRecord('Missing Record', 0) assert len(importer.missing) == 2 assert importer.skipped == 3 def test_importer_reportStatus(excel): log = Log('test.log') importer = Importer(excel, log) # Still working out how best to test this method - all it does is write # content out to log files, no calculation assert importer.reportStatus() is True importer.missing = ['Missing Record'] assert importer.reportStatus() is True def test_importer_setLog(excel): log = Log('test.log') log2 = Log('test2.log') importer = Importer(excel, log) importer.setLog(log2) assert importer.log.name == 'test2.log' def test_importer_splitGoals(excel): log = Log('test.log') importer = ImporterGoals(excel, log) goals = "Player (Potter, Rains) 78" assert importer.splitGoals(goals) == ['Player (Potter, Rains) 78'] goals = "Player (unassisted) 78; Player (unassisted) 89" assert importer.splitGoals(goals) == ['Player (unassisted) 78', 'Player (unassisted) 89'] def test_importerGames(excel_games): log = Log('test.log') importer = ImporterGames(excel_games, log) requiredColumns = ([ 'MatchTime', 'MatchTypeID', 'HTeamID', 'ATeamID', 'VenueID' ]) assert importer.checkFields(requiredColumns) is True assert importer.doImport() is True def test_importerPlayers(excel_players): log = Log('test.log') importer = ImporterPlayers(excel_players, log) requiredColumns = ([ 'FirstName', 'LastName', 'Position', 'DOB', 'Hometown' ]) assert importer.checkFields(requiredColumns) is True assert importer.doImport() is True
matt-bernhardt/trapp
tests/test_importer.py
Python
gpl-2.0
12,458
[ "COLUMBUS" ]
0e8fc49c2502e6d536a627e9eca92dd4a9af80133241f35d813b2b24869abc41
""" Views for the verification flow """ import datetime import decimal import json import logging import urllib from pytz import UTC from ipware.ip import get_ip from django.conf import settings from django.contrib.auth.decorators import login_required from django.core.mail import send_mail from django.core.urlresolvers import reverse from django.db import transaction from django.http import HttpResponse, HttpResponseBadRequest, Http404 from django.contrib.auth.models import User from django.shortcuts import redirect from django.utils import timezone from django.utils.decorators import method_decorator from django.utils.translation import ugettext as _, ugettext_lazy from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from django.views.generic.base import View, RedirectView import analytics from eventtracking import tracker from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, UsageKey from commerce.utils import audit_log from course_modes.models import CourseMode from courseware.url_helpers import get_redirect_url from edx_rest_api_client.exceptions import SlumberBaseException from edxmako.shortcuts import render_to_response, render_to_string from embargo import api as embargo_api from microsite_configuration import microsite from openedx.core.djangoapps.commerce.utils import ecommerce_api_client from openedx.core.djangoapps.user_api.accounts import NAME_MIN_LENGTH from openedx.core.djangoapps.user_api.accounts.api import update_account_settings from openedx.core.djangoapps.user_api.errors import UserNotFound, AccountValidationError from openedx.core.djangoapps.credit.api import set_credit_requirement_status from student.models import CourseEnrollment from shoppingcart.models import Order, CertificateItem from shoppingcart.processors import ( get_signed_purchase_params, get_purchase_endpoint ) from lms.djangoapps.verify_student.ssencrypt import has_valid_signature from lms.djangoapps.verify_student.models import ( VerificationDeadline, SoftwareSecurePhotoVerification, VerificationCheckpoint, VerificationStatus, IcrvStatusEmailsConfiguration, ) from lms.djangoapps.verify_student.image import decode_image_data, InvalidImageData from util.json_request import JsonResponse from util.date_utils import get_default_time_display from util.db import outer_atomic from xmodule.modulestore.django import modulestore from django.contrib.staticfiles.storage import staticfiles_storage log = logging.getLogger(__name__) class PayAndVerifyView(View): """ View for the "verify and pay" flow. This view is somewhat complicated, because the user can enter it from a number of different places: * From the "choose your track" page. * After completing payment. * From the dashboard in order to complete verification. * From the dashboard in order to upgrade to a verified track. The page will display different steps and requirements depending on: * Whether the user has submitted a photo verification recently. * Whether the user has paid for the course. * How the user reached the page (mostly affects messaging) We are also super-paranoid about how users reach this page. If they somehow aren't enrolled, or the course doesn't exist, or they've unenrolled, or they've already paid/verified, ... then we try to redirect them to the page with the most appropriate messaging (including the dashboard). Note that this page does NOT handle re-verification (photo verification that was denied or had an error); that is handled by the "reverify" view. """ # Step definitions # # These represent the numbered steps a user sees in # the verify / payment flow. # # Steps can either be: # - displayed or hidden # - complete or incomplete # # For example, when a user enters the verification/payment # flow for the first time, the user will see steps # for both payment and verification. As the user # completes these steps (for example, submitting a photo) # the steps will be marked "complete". # # If a user has already verified for another course, # then the verification steps will be hidden, # since the user has already completed them. # # If a user re-enters the flow from another application # (for example, after completing payment through # a third-party payment processor), then the user # will resume the flow at an intermediate step. # INTRO_STEP = 'intro-step' MAKE_PAYMENT_STEP = 'make-payment-step' PAYMENT_CONFIRMATION_STEP = 'payment-confirmation-step' FACE_PHOTO_STEP = 'face-photo-step' ID_PHOTO_STEP = 'id-photo-step' REVIEW_PHOTOS_STEP = 'review-photos-step' ENROLLMENT_CONFIRMATION_STEP = 'enrollment-confirmation-step' ALL_STEPS = [ INTRO_STEP, MAKE_PAYMENT_STEP, PAYMENT_CONFIRMATION_STEP, FACE_PHOTO_STEP, ID_PHOTO_STEP, REVIEW_PHOTOS_STEP, ENROLLMENT_CONFIRMATION_STEP ] PAYMENT_STEPS = [ MAKE_PAYMENT_STEP, PAYMENT_CONFIRMATION_STEP ] VERIFICATION_STEPS = [ FACE_PHOTO_STEP, ID_PHOTO_STEP, REVIEW_PHOTOS_STEP, ENROLLMENT_CONFIRMATION_STEP ] # These steps can be skipped using the ?skip-first-step GET param SKIP_STEPS = [ INTRO_STEP, ] STEP_TITLES = { INTRO_STEP: ugettext_lazy("Intro"), MAKE_PAYMENT_STEP: ugettext_lazy("Make payment"), PAYMENT_CONFIRMATION_STEP: ugettext_lazy("Payment confirmation"), FACE_PHOTO_STEP: ugettext_lazy("Take photo"), ID_PHOTO_STEP: ugettext_lazy("Take a photo of your ID"), REVIEW_PHOTOS_STEP: ugettext_lazy("Review your info"), ENROLLMENT_CONFIRMATION_STEP: ugettext_lazy("Enrollment confirmation"), } # Messages # # Depending on how the user entered reached the page, # we will display different text messaging. # For example, we show users who are upgrading # slightly different copy than users who are verifying # for the first time. # FIRST_TIME_VERIFY_MSG = 'first-time-verify' VERIFY_NOW_MSG = 'verify-now' VERIFY_LATER_MSG = 'verify-later' UPGRADE_MSG = 'upgrade' PAYMENT_CONFIRMATION_MSG = 'payment-confirmation' # Requirements # # These explain to the user what he or she # will need to successfully pay and/or verify. # # These are determined by the steps displayed # to the user; for example, if the user does not # need to complete the verification steps, # then the photo ID and webcam requirements are hidden. # ACCOUNT_ACTIVATION_REQ = "account-activation-required" PHOTO_ID_REQ = "photo-id-required" WEBCAM_REQ = "webcam-required" STEP_REQUIREMENTS = { ID_PHOTO_STEP: [PHOTO_ID_REQ, WEBCAM_REQ], FACE_PHOTO_STEP: [WEBCAM_REQ], } # Deadline types VERIFICATION_DEADLINE = "verification" UPGRADE_DEADLINE = "upgrade" @method_decorator(login_required) def get( self, request, course_id, always_show_payment=False, current_step=None, message=FIRST_TIME_VERIFY_MSG ): """ Render the payment and verification flow. Arguments: request (HttpRequest): The request object. course_id (unicode): The ID of the course the user is trying to enroll in. Keyword Arguments: always_show_payment (bool): If True, show the payment steps even if the user has already paid. This is useful for users returning to the flow after paying. current_step (string): The current step in the flow. message (string): The messaging to display. Returns: HttpResponse Raises: Http404: The course does not exist or does not have a verified mode. """ # Parse the course key # The URL regex should guarantee that the key format is valid. course_key = CourseKey.from_string(course_id) course = modulestore().get_course(course_key) # Verify that the course exists if course is None: log.warn(u"Could not find course with ID %s.", course_id) raise Http404 # Check whether the user has access to this course # based on country access rules. redirect_url = embargo_api.redirect_if_blocked( course_key, user=request.user, ip_address=get_ip(request), url=request.path ) if redirect_url: return redirect(redirect_url) # If the verification deadline has passed # then show the user a message that he/she can't verify. # # We're making the assumptions (enforced in Django admin) that: # # 1) Only verified modes have verification deadlines. # # 2) If set, verification deadlines are always AFTER upgrade deadlines, because why would you # let someone upgrade into a verified track if they can't complete verification? # verification_deadline = VerificationDeadline.deadline_for_course(course.id) response = self._response_if_deadline_passed(course, self.VERIFICATION_DEADLINE, verification_deadline) if response is not None: log.info(u"Verification deadline for '%s' has passed.", course.id) return response # Retrieve the relevant course mode for the payment/verification flow. # # WARNING: this is technical debt! A much better way to do this would be to # separate out the payment flow and use the product SKU to figure out what # the user is trying to purchase. # # Nonetheless, for the time being we continue to make the really ugly assumption # that at some point there was a paid course mode we can query for the price. relevant_course_mode = self._get_paid_mode(course_key) # If we can find a relevant course mode, then log that we're entering the flow # Otherwise, this course does not support payment/verification, so respond with a 404. if relevant_course_mode is not None: if CourseMode.is_verified_mode(relevant_course_mode): log.info( u"Entering payment and verification flow for user '%s', course '%s', with current step '%s'.", request.user.id, course_id, current_step ) else: log.info( u"Entering payment flow for user '%s', course '%s', with current step '%s'", request.user.id, course_id, current_step ) else: # Otherwise, there has never been a verified/paid mode, # so return a page not found response. log.warn( u"No paid/verified course mode found for course '%s' for verification/payment flow request", course_id ) raise Http404 # If the user is trying to *pay* and the upgrade deadline has passed, # then they shouldn't be able to enter the flow. # # NOTE: This should match the availability dates used by the E-Commerce service # to determine whether a user can purchase a product. The idea is that if the service # won't fulfill the order, we shouldn't even let the user get into the payment flow. # user_is_trying_to_pay = message in [self.FIRST_TIME_VERIFY_MSG, self.UPGRADE_MSG] if user_is_trying_to_pay: upgrade_deadline = relevant_course_mode.expiration_datetime response = self._response_if_deadline_passed(course, self.UPGRADE_DEADLINE, upgrade_deadline) if response is not None: log.info(u"Upgrade deadline for '%s' has passed.", course.id) return response # Check whether the user has verified, paid, and enrolled. # A user is considered "paid" if he or she has an enrollment # with a paid course mode (such as "verified"). # For this reason, every paid user is enrolled, but not # every enrolled user is paid. # If the course mode is not verified(i.e only paid) then already_verified is always True already_verified = ( self._check_already_verified(request.user) if CourseMode.is_verified_mode(relevant_course_mode) else True ) already_paid, is_enrolled = self._check_enrollment(request.user, course_key) # Redirect the user to a more appropriate page if the # messaging won't make sense based on the user's # enrollment / payment / verification status. redirect_response = self._redirect_if_necessary( message, already_verified, already_paid, is_enrolled, course_key ) if redirect_response is not None: return redirect_response display_steps = self._display_steps( always_show_payment, already_verified, already_paid, relevant_course_mode ) requirements = self._requirements(display_steps, request.user.is_active) if current_step is None: current_step = display_steps[0]['name'] # Allow the caller to skip the first page # This is useful if we want the user to be able to # use the "back" button to return to the previous step. # This parameter should only work for known skip-able steps if request.GET.get('skip-first-step') and current_step in self.SKIP_STEPS: display_step_names = [step['name'] for step in display_steps] current_step_idx = display_step_names.index(current_step) if (current_step_idx + 1) < len(display_steps): current_step = display_steps[current_step_idx + 1]['name'] courseware_url = "" if not course.start or course.start < datetime.datetime.today().replace(tzinfo=UTC): courseware_url = reverse( 'course_root', kwargs={'course_id': unicode(course_key)} ) full_name = ( request.user.profile.name if request.user.profile.name else "" ) # If the user set a contribution amount on another page, # use that amount to pre-fill the price selection form. contribution_amount = request.session.get( 'donation_for_course', {} ).get(unicode(course_key), '') # Remember whether the user is upgrading # so we can fire an analytics event upon payment. request.session['attempting_upgrade'] = (message == self.UPGRADE_MSG) # Determine the photo verification status verification_good_until = self._verification_valid_until(request.user) # get available payment processors if relevant_course_mode.sku: # transaction will be conducted via ecommerce service processors = ecommerce_api_client(request.user).payment.processors.get() else: # transaction will be conducted using legacy shopping cart processors = [settings.CC_PROCESSOR_NAME] # Render the top-level page context = { 'contribution_amount': contribution_amount, 'course': course, 'course_key': unicode(course_key), 'checkpoint_location': request.GET.get('checkpoint'), 'course_mode': relevant_course_mode, 'courseware_url': courseware_url, 'current_step': current_step, 'disable_courseware_js': True, 'display_steps': display_steps, 'is_active': json.dumps(request.user.is_active), 'message_key': message, 'platform_name': settings.PLATFORM_NAME, 'processors': processors, 'requirements': requirements, 'user_full_name': full_name, 'verification_deadline': ( get_default_time_display(verification_deadline) if verification_deadline else "" ), 'already_verified': already_verified, 'verification_good_until': verification_good_until, 'capture_sound': staticfiles_storage.url("audio/camera_capture.wav"), 'nav_hidden': True, } return render_to_response("verify_student/pay_and_verify.html", context) def _redirect_if_necessary( self, message, already_verified, already_paid, is_enrolled, course_key ): """Redirect the user to a more appropriate page if necessary. In some cases, a user may visit this page with verification / enrollment / payment state that we don't anticipate. For example, a user may unenroll from the course after paying for it, then visit the "verify now" page to complete verification. When this happens, we try to redirect the user to the most appropriate page. Arguments: message (string): The messaging of the page. Should be a key in `MESSAGES`. already_verified (bool): Whether the user has submitted a verification request recently. already_paid (bool): Whether the user is enrolled in a paid course mode. is_enrolled (bool): Whether the user has an active enrollment in the course. course_key (CourseKey): The key for the course. Returns: HttpResponse or None """ url = None course_kwargs = {'course_id': unicode(course_key)} if already_verified and already_paid: # If they've already paid and verified, there's nothing else to do, # so redirect them to the dashboard. if message != self.PAYMENT_CONFIRMATION_MSG: url = reverse('dashboard') elif message in [self.VERIFY_NOW_MSG, self.VERIFY_LATER_MSG, self.PAYMENT_CONFIRMATION_MSG]: if is_enrolled: # If the user is already enrolled but hasn't yet paid, # then the "upgrade" messaging is more appropriate. if not already_paid: url = reverse('verify_student_upgrade_and_verify', kwargs=course_kwargs) else: # If the user is NOT enrolled, then send him/her # to the first time verification page. url = reverse('verify_student_start_flow', kwargs=course_kwargs) elif message == self.UPGRADE_MSG: if is_enrolled: if already_paid: # If the student has paid, but not verified, redirect to the verification flow. url = reverse('verify_student_verify_now', kwargs=course_kwargs) else: url = reverse('verify_student_start_flow', kwargs=course_kwargs) # Redirect if necessary, otherwise implicitly return None if url is not None: return redirect(url) def _get_paid_mode(self, course_key): """ Retrieve the paid course mode for a course. The returned course mode may or may not be expired. Unexpired modes are preferred to expired modes. Arguments: course_key (CourseKey): The location of the course. Returns: CourseMode tuple """ # Retrieve all the modes at once to reduce the number of database queries all_modes, unexpired_modes = CourseMode.all_and_unexpired_modes_for_courses([course_key]) # Retrieve the first mode that matches the following criteria: # * Unexpired # * Price > 0 # * Not credit for mode in unexpired_modes[course_key]: if mode.min_price > 0 and not CourseMode.is_credit_mode(mode): return mode # Otherwise, find the first expired mode for mode in all_modes[course_key]: if mode.min_price > 0: return mode # Otherwise, return None and so the view knows to respond with a 404. return None def _display_steps(self, always_show_payment, already_verified, already_paid, course_mode): """Determine which steps to display to the user. Includes all steps by default, but removes steps if the user has already completed them. Arguments: always_show_payment (bool): If True, display the payment steps even if the user has already paid. already_verified (bool): Whether the user has submitted a verification request recently. already_paid (bool): Whether the user is enrolled in a paid course mode. Returns: list """ display_steps = self.ALL_STEPS remove_steps = set() if already_verified or not CourseMode.is_verified_mode(course_mode): remove_steps |= set(self.VERIFICATION_STEPS) if already_paid and not always_show_payment: remove_steps |= set(self.PAYMENT_STEPS) else: # The "make payment" step doubles as an intro step, # so if we're showing the payment step, hide the intro step. remove_steps |= set([self.INTRO_STEP]) return [ { 'name': step, 'title': unicode(self.STEP_TITLES[step]), } for step in display_steps if step not in remove_steps ] def _requirements(self, display_steps, is_active): """Determine which requirements to show the user. For example, if the user needs to submit a photo verification, tell the user that she will need a photo ID and a webcam. Arguments: display_steps (list): The steps to display to the user. is_active (bool): If False, adds a requirement to activate the user account. Returns: dict: Keys are requirement names, values are booleans indicating whether to show the requirement. """ all_requirements = { self.ACCOUNT_ACTIVATION_REQ: not is_active, self.PHOTO_ID_REQ: False, self.WEBCAM_REQ: False, } display_steps = set(step['name'] for step in display_steps) for step, step_requirements in self.STEP_REQUIREMENTS.iteritems(): if step in display_steps: for requirement in step_requirements: all_requirements[requirement] = True return all_requirements def _verification_valid_until(self, user, date_format="%m/%d/%Y"): """ Check whether the user has a valid or pending verification. Arguments: user: date_format: optional parameter for formatting datetime object to string in response Returns: datetime object in string format """ photo_verifications = SoftwareSecurePhotoVerification.verification_valid_or_pending(user) # return 'expiration_datetime' of latest photo verification if found, # otherwise implicitly return '' if photo_verifications: return photo_verifications[0].expiration_datetime.strftime(date_format) return '' def _check_already_verified(self, user): """Check whether the user has a valid or pending verification. Note that this includes cases in which the user's verification has not been accepted (either because it hasn't been processed, or there was an error). This should return True if the user has done their part: submitted photos within the expiration period. """ return SoftwareSecurePhotoVerification.user_has_valid_or_pending(user) def _check_enrollment(self, user, course_key): """Check whether the user has an active enrollment and has paid. If a user is enrolled in a paid course mode, we assume that the user has paid. Arguments: user (User): The user to check. course_key (CourseKey): The key of the course to check. Returns: Tuple `(has_paid, is_active)` indicating whether the user has paid and whether the user has an active account. """ enrollment_mode, is_active = CourseEnrollment.enrollment_mode_for_user(user, course_key) has_paid = False if enrollment_mode is not None and is_active: all_modes = CourseMode.modes_for_course_dict(course_key, include_expired=True) course_mode = all_modes.get(enrollment_mode) has_paid = (course_mode and course_mode.min_price > 0) return (has_paid, bool(is_active)) def _response_if_deadline_passed(self, course, deadline_name, deadline_datetime): """ Respond with some error messaging if the deadline has passed. Arguments: course (Course): The course the user is trying to enroll in. deadline_name (str): One of the deadline constants. deadline_datetime (datetime): The deadline. Returns: HttpResponse or None """ if deadline_name not in [self.VERIFICATION_DEADLINE, self.UPGRADE_DEADLINE]: log.error("Invalid deadline name %s. Skipping check for whether the deadline passed.", deadline_name) return None deadline_passed = ( deadline_datetime is not None and deadline_datetime < datetime.datetime.now(UTC) ) if deadline_passed: context = { 'course': course, 'deadline_name': deadline_name, 'deadline': ( get_default_time_display(deadline_datetime) if deadline_datetime else "" ) } return render_to_response("verify_student/missed_deadline.html", context) def checkout_with_ecommerce_service(user, course_key, course_mode, processor): # pylint: disable=invalid-name """ Create a new basket and trigger immediate checkout, using the E-Commerce API. """ course_id = unicode(course_key) try: api = ecommerce_api_client(user) # Make an API call to create the order and retrieve the results result = api.baskets.post({ 'products': [{'sku': course_mode.sku}], 'checkout': True, 'payment_processor_name': processor }) # Pass the payment parameters directly from the API response. return result.get('payment_data') except SlumberBaseException: params = {'username': user.username, 'mode': course_mode.slug, 'course_id': course_id} log.exception('Failed to create order for %(username)s %(mode)s mode of %(course_id)s', params) raise finally: audit_log( 'checkout_requested', course_id=course_id, mode=course_mode.slug, processor_name=processor, user_id=user.id ) def checkout_with_shoppingcart(request, user, course_key, course_mode, amount): """ Create an order and trigger checkout using shoppingcart.""" cart = Order.get_cart_for_user(user) cart.clear() enrollment_mode = course_mode.slug CertificateItem.add_to_order(cart, course_key, amount, enrollment_mode) # Change the order's status so that we don't accidentally modify it later. # We need to do this to ensure that the parameters we send to the payment system # match what we store in the database. # (Ordinarily we would do this client-side when the user submits the form, but since # the JavaScript on this page does that immediately, we make the change here instead. # This avoids a second AJAX call and some additional complication of the JavaScript.) # If a user later re-enters the verification / payment flow, she will create a new order. cart.start_purchase() callback_url = request.build_absolute_uri( reverse("shoppingcart.views.postpay_callback") ) payment_data = { 'payment_processor_name': settings.CC_PROCESSOR_NAME, 'payment_page_url': get_purchase_endpoint(), 'payment_form_data': get_signed_purchase_params( cart, callback_url=callback_url, extra_data=[unicode(course_key), course_mode.slug] ), } return payment_data @require_POST @login_required def create_order(request): """ This endpoint is named 'create_order' for backward compatibility, but its actual use is to add a single product to the user's cart and request immediate checkout. """ course_id = request.POST['course_id'] course_id = CourseKey.from_string(course_id) donation_for_course = request.session.get('donation_for_course', {}) contribution = request.POST.get("contribution", donation_for_course.get(unicode(course_id), 0)) try: amount = decimal.Decimal(contribution).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN) except decimal.InvalidOperation: return HttpResponseBadRequest(_("Selected price is not valid number.")) current_mode = None sku = request.POST.get('sku', None) if sku: try: current_mode = CourseMode.objects.get(sku=sku) except CourseMode.DoesNotExist: log.exception(u'Failed to find CourseMode with SKU [%s].', sku) if not current_mode: # Check if there are more than 1 paid(mode with min_price>0 e.g verified/professional/no-id-professional) modes # for course exist then choose the first one paid_modes = CourseMode.paid_modes_for_course(course_id) if paid_modes: if len(paid_modes) > 1: log.warn(u"Multiple paid course modes found for course '%s' for create order request", course_id) current_mode = paid_modes[0] # Make sure this course has a paid mode if not current_mode: log.warn(u"Create order requested for course '%s' without a paid mode.", course_id) return HttpResponseBadRequest(_("This course doesn't support paid certificates")) if CourseMode.is_professional_mode(current_mode): amount = current_mode.min_price if amount < current_mode.min_price: return HttpResponseBadRequest(_("No selected price or selected price is below minimum.")) if current_mode.sku: # if request.POST doesn't contain 'processor' then the service's default payment processor will be used. payment_data = checkout_with_ecommerce_service( request.user, course_id, current_mode, request.POST.get('processor') ) else: payment_data = checkout_with_shoppingcart(request, request.user, course_id, current_mode, amount) if 'processor' not in request.POST: # (XCOM-214) To be removed after release. # the absence of this key in the POST payload indicates that the request was initiated from # a stale js client, which expects a response containing only the 'payment_form_data' part of # the payment data result. payment_data = payment_data['payment_form_data'] return HttpResponse(json.dumps(payment_data), content_type="application/json") class SubmitPhotosView(View): """ End-point for submitting photos for verification. """ @method_decorator(transaction.non_atomic_requests) def dispatch(self, *args, **kwargs): # pylint: disable=missing-docstring return super(SubmitPhotosView, self).dispatch(*args, **kwargs) @method_decorator(login_required) @method_decorator(outer_atomic(read_committed=True)) def post(self, request): """ Submit photos for verification. This end-point is used for the following cases: * Initial verification through the pay-and-verify flow. * Initial verification initiated from a checkpoint within a course. * Re-verification initiated from a checkpoint within a course. POST Parameters: face_image (str): base64-encoded image data of the user's face. photo_id_image (str): base64-encoded image data of the user's photo ID. full_name (str): The user's full name, if the user is requesting a name change as well. course_key (str): Identifier for the course, if initiated from a checkpoint. checkpoint (str): Location of the checkpoint in the course. """ # If the user already has an initial verification attempt, we can re-use the photo ID # the user submitted with the initial attempt. This is useful for the in-course reverification # case in which users submit only the face photo and have it matched against their ID photos # submitted with the initial verification. initial_verification = SoftwareSecurePhotoVerification.get_initial_verification(request.user) # Validate the POST parameters params, response = self._validate_parameters(request, bool(initial_verification)) if response is not None: return response # If necessary, update the user's full name if "full_name" in params: response = self._update_full_name(request.user, params["full_name"]) if response is not None: return response # Retrieve the image data # Validation ensures that we'll have a face image, but we may not have # a photo ID image if this is a reverification. face_image, photo_id_image, response = self._decode_image_data( params["face_image"], params.get("photo_id_image") ) if response is not None: return response # Submit the attempt attempt = self._submit_attempt(request.user, face_image, photo_id_image, initial_verification) # If this attempt was submitted at a checkpoint, then associate # the attempt with the checkpoint. submitted_at_checkpoint = "checkpoint" in params and "course_key" in params if submitted_at_checkpoint: checkpoint = self._associate_attempt_with_checkpoint( request.user, attempt, params["course_key"], params["checkpoint"] ) # If the submission came from an in-course checkpoint if initial_verification is not None and submitted_at_checkpoint: self._fire_event(request.user, "edx.bi.reverify.submitted", { "category": "verification", "label": unicode(params["course_key"]), "checkpoint": checkpoint.checkpoint_name, }) # Send a URL that the client can redirect to in order # to return to the checkpoint in the courseware. redirect_url = get_redirect_url(params["course_key"], params["checkpoint"]) return JsonResponse({"url": redirect_url}) # Otherwise, the submission came from an initial verification flow. else: self._fire_event(request.user, "edx.bi.verify.submitted", {"category": "verification"}) self._send_confirmation_email(request.user) redirect_url = None return JsonResponse({}) def _validate_parameters(self, request, has_initial_verification): """ Check that the POST parameters are valid. Arguments: request (HttpRequest): The request object. has_initial_verification (bool): Whether the user has an initial verification attempt. Returns: HttpResponse or None """ # Pull out the parameters we care about. params = { param_name: request.POST[param_name] for param_name in [ "face_image", "photo_id_image", "course_key", "checkpoint", "full_name" ] if param_name in request.POST } # If the user already has an initial verification attempt, then we don't # require the user to submit a photo ID image, since we can re-use the photo ID # image from the initial attempt. # If we don't have an initial verification OR a photo ID image, something has gone # terribly wrong in the JavaScript. Log this as an error so we can track it down. if "photo_id_image" not in params and not has_initial_verification: log.error( ( "User %s does not have an initial verification attempt " "and no photo ID image data was provided. " "This most likely means that the JavaScript client is not " "correctly constructing the request to submit photos." ), request.user.id ) return None, HttpResponseBadRequest( _("Photo ID image is required if the user does not have an initial verification attempt.") ) # The face image is always required. if "face_image" not in params: msg = _("Missing required parameter face_image") return None, HttpResponseBadRequest(msg) # If provided, parse the course key and checkpoint location if "course_key" in params: try: params["course_key"] = CourseKey.from_string(params["course_key"]) except InvalidKeyError: return None, HttpResponseBadRequest(_("Invalid course key")) if "checkpoint" in params: try: params["checkpoint"] = UsageKey.from_string(params["checkpoint"]).replace( course_key=params["course_key"] ) except InvalidKeyError: return None, HttpResponseBadRequest(_("Invalid checkpoint location")) return params, None def _update_full_name(self, user, full_name): """ Update the user's full name. Arguments: user (User): The user to update. full_name (unicode): The user's updated full name. Returns: HttpResponse or None """ try: update_account_settings(user, {"name": full_name}) except UserNotFound: return HttpResponseBadRequest(_("No profile found for user")) except AccountValidationError: msg = _( "Name must be at least {min_length} characters long." ).format(min_length=NAME_MIN_LENGTH) return HttpResponseBadRequest(msg) def _decode_image_data(self, face_data, photo_id_data=None): """ Decode image data sent with the request. Arguments: face_data (str): base64-encoded face image data. Keyword Arguments: photo_id_data (str): base64-encoded photo ID image data. Returns: tuple of (str, str, HttpResponse) """ try: # Decode face image data (used for both an initial and re-verification) face_image = decode_image_data(face_data) # Decode the photo ID image data if it's provided photo_id_image = ( decode_image_data(photo_id_data) if photo_id_data is not None else None ) return face_image, photo_id_image, None except InvalidImageData: msg = _("Image data is not valid.") return None, None, HttpResponseBadRequest(msg) def _submit_attempt(self, user, face_image, photo_id_image=None, initial_verification=None): """ Submit a verification attempt. Arguments: user (User): The user making the attempt. face_image (str): Decoded face image data. Keyword Arguments: photo_id_image (str or None): Decoded photo ID image data. initial_verification (SoftwareSecurePhotoVerification): The initial verification attempt. """ attempt = SoftwareSecurePhotoVerification(user=user) # We will always have face image data, so upload the face image attempt.upload_face_image(face_image) # If an ID photo wasn't submitted, re-use the ID photo from the initial attempt. # Earlier validation rules ensure that at least one of these is available. if photo_id_image is not None: attempt.upload_photo_id_image(photo_id_image) elif initial_verification is None: # Earlier validation should ensure that we never get here. log.error( "Neither a photo ID image or initial verification attempt provided. " "Parameter validation in the view should prevent this from happening!" ) # Submit the attempt attempt.mark_ready() attempt.submit(copy_id_photo_from=initial_verification) return attempt def _associate_attempt_with_checkpoint(self, user, attempt, course_key, usage_id): """ Associate the verification attempt with a checkpoint within a course. Arguments: user (User): The user making the attempt. attempt (SoftwareSecurePhotoVerification): The verification attempt. course_key (CourseKey): The identifier for the course. usage_key (UsageKey): The location of the checkpoint within the course. Returns: VerificationCheckpoint """ checkpoint = VerificationCheckpoint.get_or_create_verification_checkpoint(course_key, usage_id) checkpoint.add_verification_attempt(attempt) VerificationStatus.add_verification_status(checkpoint, user, "submitted") return checkpoint def _send_confirmation_email(self, user): """ Send an email confirming that the user submitted photos for initial verification. """ context = { 'full_name': user.profile.name, 'platform_name': microsite.get_value("PLATFORM_NAME", settings.PLATFORM_NAME) } subject = _("Verification photos received") message = render_to_string('emails/photo_submission_confirmation.txt', context) from_address = microsite.get_value('default_from_email', settings.DEFAULT_FROM_EMAIL) to_address = user.email try: send_mail(subject, message, from_address, [to_address], fail_silently=False) except: # pylint: disable=bare-except # We catch all exceptions and log them. # It would be much, much worse to roll back the transaction due to an uncaught # exception than to skip sending the notification email. log.exception("Could not send notification email for initial verification for user %s", user.id) def _fire_event(self, user, event_name, parameters): """ Fire an analytics event. Arguments: user (User): The user who submitted photos. event_name (str): Name of the analytics event. parameters (dict): Event parameters. Returns: None """ if settings.LMS_SEGMENT_KEY: tracking_context = tracker.get_tracker().resolve_context() context = { 'ip': tracking_context.get('ip'), 'Google Analytics': { 'clientId': tracking_context.get('client_id') } } analytics.track(user.id, event_name, parameters, context=context) def _compose_message_reverification_email( course_key, user_id, related_assessment_location, status, request ): # pylint: disable=invalid-name """ Compose subject and message for photo reverification email. Args: course_key(CourseKey): CourseKey object user_id(str): User Id related_assessment_location(str): Location of reverification XBlock photo_verification(QuerySet): Queryset of SoftwareSecure objects status(str): Approval status is_secure(Bool): Is running on secure protocol or not Returns: None if any error occurred else Tuple of subject and message strings """ try: usage_key = UsageKey.from_string(related_assessment_location) reverification_block = modulestore().get_item(usage_key) course = modulestore().get_course(course_key) redirect_url = get_redirect_url(course_key, usage_key.replace(course_key=course_key)) subject = "Re-verification Status" context = { "status": status, "course_name": course.display_name_with_default, "assessment": reverification_block.related_assessment } # Allowed attempts is 1 if not set on verification block allowed_attempts = reverification_block.attempts + 1 used_attempts = VerificationStatus.get_user_attempts(user_id, course_key, related_assessment_location) left_attempts = allowed_attempts - used_attempts is_attempt_allowed = left_attempts > 0 verification_open = True if reverification_block.due: verification_open = timezone.now() <= reverification_block.due context["left_attempts"] = left_attempts context["is_attempt_allowed"] = is_attempt_allowed context["verification_open"] = verification_open context["due_date"] = get_default_time_display(reverification_block.due) context['platform_name'] = settings.PLATFORM_NAME context["used_attempts"] = used_attempts context["allowed_attempts"] = allowed_attempts context["support_link"] = microsite.get_value('email_from_address', settings.CONTACT_EMAIL) re_verification_link = reverse( 'verify_student_incourse_reverify', args=( unicode(course_key), related_assessment_location ) ) context["course_link"] = request.build_absolute_uri(redirect_url) context["reverify_link"] = request.build_absolute_uri(re_verification_link) message = render_to_string('emails/reverification_processed.txt', context) log.info( "Sending email to User_Id=%s. Attempts left for this user are %s. " "Allowed attempts %s. " "Due Date %s", str(user_id), left_attempts, allowed_attempts, str(reverification_block.due) ) return subject, message # Catch all exception to avoid raising back to view except: # pylint: disable=bare-except log.exception("The email for re-verification sending failed for user_id %s", user_id) def _send_email(user_id, subject, message): """ Send email to given user Args: user_id(str): User Id subject(str): Subject lines of emails message(str): Email message body Returns: None """ from_address = microsite.get_value( 'email_from_address', settings.DEFAULT_FROM_EMAIL ) user = User.objects.get(id=user_id) user.email_user(subject, message, from_address) def _set_user_requirement_status(attempt, namespace, status, reason=None): """Sets the status of a credit requirement for the user, based on a verification checkpoint. """ checkpoint = None try: checkpoint = VerificationCheckpoint.objects.get(photo_verification=attempt) except VerificationCheckpoint.DoesNotExist: log.error("Unable to find checkpoint for user with id %d", attempt.user.id) if checkpoint is not None: try: set_credit_requirement_status( attempt.user.username, checkpoint.course_id, namespace, checkpoint.checkpoint_location, status=status, reason=reason, ) except Exception: # pylint: disable=broad-except # Catch exception if unable to add credit requirement # status for user log.error("Unable to add Credit requirement status for user with id %d", attempt.user.id) @require_POST @csrf_exempt # SS does its own message signing, and their API won't have a cookie value def results_callback(request): """ Software Secure will call this callback to tell us whether a user is verified to be who they said they are. """ body = request.body try: body_dict = json.loads(body) except ValueError: log.exception("Invalid JSON received from Software Secure:\n\n{}\n".format(body)) return HttpResponseBadRequest("Invalid JSON. Received:\n\n{}".format(body)) if not isinstance(body_dict, dict): log.error("Reply from Software Secure is not a dict:\n\n{}\n".format(body)) return HttpResponseBadRequest("JSON should be dict. Received:\n\n{}".format(body)) headers = { "Authorization": request.META.get("HTTP_AUTHORIZATION", ""), "Date": request.META.get("HTTP_DATE", "") } has_valid_signature( "POST", headers, body_dict, settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_ACCESS_KEY"], settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_SECRET_KEY"] ) _response, access_key_and_sig = headers["Authorization"].split(" ") access_key = access_key_and_sig.split(":")[0] # This is what we should be doing... #if not sig_valid: # return HttpResponseBadRequest("Signature is invalid") # This is what we're doing until we can figure out why we disagree on sigs if access_key != settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_ACCESS_KEY"]: return HttpResponseBadRequest("Access key invalid") receipt_id = body_dict.get("EdX-ID") result = body_dict.get("Result") reason = body_dict.get("Reason", "") error_code = body_dict.get("MessageType", "") try: attempt = SoftwareSecurePhotoVerification.objects.get(receipt_id=receipt_id) except SoftwareSecurePhotoVerification.DoesNotExist: log.error("Software Secure posted back for receipt_id %s, but not found", receipt_id) return HttpResponseBadRequest("edX ID {} not found".format(receipt_id)) if result == "PASS": log.debug("Approving verification for %s", receipt_id) attempt.approve() status = "approved" _set_user_requirement_status(attempt, 'reverification', 'satisfied') elif result == "FAIL": log.debug("Denying verification for %s", receipt_id) attempt.deny(json.dumps(reason), error_code=error_code) status = "denied" _set_user_requirement_status( attempt, 'reverification', 'failed', json.dumps(reason) ) elif result == "SYSTEM FAIL": log.debug("System failure for %s -- resetting to must_retry", receipt_id) attempt.system_error(json.dumps(reason), error_code=error_code) status = "error" log.error("Software Secure callback attempt for %s failed: %s", receipt_id, reason) else: log.error("Software Secure returned unknown result %s", result) return HttpResponseBadRequest( "Result {} not understood. Known results: PASS, FAIL, SYSTEM FAIL".format(result) ) checkpoints = VerificationCheckpoint.objects.filter(photo_verification=attempt).all() VerificationStatus.add_status_from_checkpoints(checkpoints=checkpoints, user=attempt.user, status=status) # Trigger ICRV email only if ICRV status emails config is enabled icrv_status_emails = IcrvStatusEmailsConfiguration.current() if icrv_status_emails.enabled and checkpoints: user_id = attempt.user.id course_key = checkpoints[0].course_id related_assessment_location = checkpoints[0].checkpoint_location subject, message = _compose_message_reverification_email( course_key, user_id, related_assessment_location, status, request ) _send_email(user_id, subject, message) return HttpResponse("OK!") class ReverifyView(View): """ Reverification occurs when a user's initial verification is denied or expires. When this happens, users can re-submit photos through the re-verification flow. Unlike in-course reverification, this flow requires users to submit *both* face and ID photos. In contrast, during in-course reverification, students submit only face photos, which are matched against the ID photo the user submitted during initial verification. """ @method_decorator(login_required) def get(self, request): """ Render the reverification flow. Most of the work is done client-side by composing the same Backbone views used in the initial verification flow. """ status, _ = SoftwareSecurePhotoVerification.user_status(request.user) if status in ["must_reverify", "expired"]: context = { "user_full_name": request.user.profile.name, "platform_name": settings.PLATFORM_NAME, "capture_sound": staticfiles_storage.url("audio/camera_capture.wav"), } return render_to_response("verify_student/reverify.html", context) else: context = { "status": status } return render_to_response("verify_student/reverify_not_allowed.html", context) class InCourseReverifyView(View): """ The in-course reverification view. In-course reverification occurs while a student is taking a course. At points in the course, students are prompted to submit face photos, which are matched against the ID photos the user submitted during their initial verification. Students are prompted to enter this flow from an "In Course Reverification" XBlock (courseware component) that course authors add to the course. See https://github.com/edx/edx-reverification-block for more details. """ @method_decorator(login_required) def get(self, request, course_id, usage_id): """Display the view for face photo submission. Args: request(HttpRequest): HttpRequest object course_id(str): A string of course id usage_id(str): Location of Reverification XBlock in courseware Returns: HttpResponse """ user = request.user course_key = CourseKey.from_string(course_id) course = modulestore().get_course(course_key) if course is None: log.error(u"Could not find course '%s' for in-course reverification.", course_key) raise Http404 try: checkpoint = VerificationCheckpoint.objects.get(course_id=course_key, checkpoint_location=usage_id) except VerificationCheckpoint.DoesNotExist: log.error( u"No verification checkpoint exists for the " u"course '%s' and checkpoint location '%s'.", course_key, usage_id ) raise Http404 initial_verification = SoftwareSecurePhotoVerification.get_initial_verification(user) if not initial_verification: return self._redirect_to_initial_verification(user, course_key, usage_id) # emit the reverification event self._track_reverification_events('edx.bi.reverify.started', user.id, course_id, checkpoint.checkpoint_name) context = { 'course_key': unicode(course_key), 'course_name': course.display_name_with_default, 'checkpoint_name': checkpoint.checkpoint_name, 'platform_name': settings.PLATFORM_NAME, 'usage_id': usage_id, 'capture_sound': staticfiles_storage.url("audio/camera_capture.wav"), } return render_to_response("verify_student/incourse_reverify.html", context) def _track_reverification_events(self, event_name, user_id, course_id, checkpoint): # pylint: disable=invalid-name """Track re-verification events for a user against a reverification checkpoint of a course. Arguments: event_name (str): Name of event being tracked user_id (str): The ID of the user course_id (unicode): ID associated with the course checkpoint (str): Checkpoint name Returns: None """ log.info( u"In-course reverification: event %s occurred for user '%s' in course '%s' at checkpoint '%s'", event_name, user_id, course_id, checkpoint ) if settings.LMS_SEGMENT_KEY: tracking_context = tracker.get_tracker().resolve_context() analytics.track( user_id, event_name, { 'category': "verification", 'label': unicode(course_id), 'checkpoint': checkpoint }, context={ 'ip': tracking_context.get('ip'), 'Google Analytics': { 'clientId': tracking_context.get('client_id') } } ) def _redirect_to_initial_verification(self, user, course_key, checkpoint): """ Redirect because the user does not have an initial verification. We will redirect the user to the initial verification flow, passing the identifier for this checkpoint. When the user submits a verification attempt, it will count for *both* the initial and checkpoint verification. Arguments: user (User): The user who made the request. course_key (CourseKey): The identifier for the course for which the user is attempting to re-verify. checkpoint (string): Location of the checkpoint in the courseware. Returns: HttpResponse """ log.info( u"User %s does not have an initial verification, so " u"he/she will be redirected to the \"verify later\" flow " u"for the course %s.", user.id, course_key ) base_url = reverse('verify_student_verify_now', kwargs={'course_id': unicode(course_key)}) params = urllib.urlencode({"checkpoint": checkpoint}) full_url = u"{base}?{params}".format(base=base_url, params=params) return redirect(full_url)
inares/edx-platform
lms/djangoapps/verify_student/views.py
Python
agpl-3.0
58,975
[ "VisIt" ]
40900e6ac510097f12525393043b7594744efe2c02a0509b13679b133250c7a7
# -*- coding: utf-8 -*- # import os import warnings from tempfile import TemporaryDirectory import numpy from dolfin import ( Constant, DirichletBC, Expression, FacetNormal, FiniteElement, Function, FunctionSpace, Mesh, MeshFunction, MixedElement, SubDomain, SubMesh, UserExpression, dot, grad, pi, ) import materials import meshio from maelstrom import heat as cyl_heat from . import meshes, my_materials, tecplot_reader DEBUG = False class Crucible: def __init__(self): GMSH_EPS = 1.0e-15 # https://fenicsproject.org/qa/12891/initialize-mesh-from-vertices-connectivities-at-once points, cells, point_data, cell_data, _ = meshes.crucible_with_coils.generate() # Convert the cell data to 'uint' so we can pick a size_t MeshFunction # below as usual. for k0 in cell_data: for k1 in cell_data[k0]: cell_data[k0][k1] = numpy.array( cell_data[k0][k1], dtype=numpy.dtype("uint") ) with TemporaryDirectory() as temp_dir: tmp_filename = os.path.join(temp_dir, "test.xml") meshio.write_points_cells( tmp_filename, points, cells, cell_data=cell_data, file_format="dolfin-xml", ) self.mesh = Mesh(tmp_filename) self.subdomains = MeshFunction( "size_t", self.mesh, os.path.join(temp_dir, "test_gmsh:physical.xml") ) self.subdomain_materials = { 1: my_materials.porcelain, 2: materials.argon, 3: materials.gallium_arsenide_solid, 4: materials.gallium_arsenide_liquid, 27: materials.air, } # coils for k in range(5, 27): self.subdomain_materials[k] = my_materials.ek90 # Define the subdomains which together form a single coil. self.coil_domains = [ [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26], ] self.wpi = 4 self.submesh_workpiece = SubMesh(self.mesh, self.subdomains, self.wpi) # http://fenicsproject.org/qa/2026/submesh-workaround-for-parallel-computation # submesh_parallel_bug_fixed = False # if submesh_parallel_bug_fixed: # submesh_workpiece = SubMesh(self.mesh, self.subdomains, self.wpi) # else: # # To get the mesh in parallel, we need to read it in from a file. # # Writing out can only happen in serial mode, though. :/ # base = os.path.join(current_path, # '../../meshes/2d/crucible-with-coils-submesh' # ) # filename = base + '.xml' # if not os.path.isfile(filename): # warnings.warn( # 'Submesh file \'{}\' does not exist. Creating... '.format( # filename # )) # if MPI.size(MPI.comm_world) > 1: # raise RuntimeError( # 'Can only write submesh in serial mode.' # ) # submesh_workpiece = \ # SubMesh(self.mesh, self.subdomains, self.wpi) # output_stream = File(filename) # output_stream << submesh_workpiece # # Read the mesh # submesh_workpiece = Mesh(filename) coords = self.submesh_workpiece.coordinates() ymin = min(coords[:, 1]) ymax = max(coords[:, 1]) # Find the top right point. k = numpy.argmax(numpy.sum(coords, 1)) topright = coords[k, :] # Initialize mesh function for boundary domains class Left(SubDomain): def inside(self, x, on_boundary): # Explicitly exclude the lowest and the highest point of the # symmetry axis. # It is necessary for the consistency of the pressure-Poisson # system in the Navier-Stokes solver that the velocity is # exactly 0 at the boundary r>0. Hence, at the corner points # (r=0, melt-crucible, melt-crystal) we must enforce u=0 # already and cannot have a component in z-direction. return ( on_boundary and x[0] < GMSH_EPS and x[1] < ymax - GMSH_EPS and x[1] > ymin + GMSH_EPS ) class Crucible(SubDomain): def inside(self, x, on_boundary): return on_boundary and ( (x[0] > GMSH_EPS and x[1] < ymax - GMSH_EPS) or (x[0] > topright[0] - GMSH_EPS and x[1] > topright[1] - GMSH_EPS) or (x[0] < GMSH_EPS and x[1] < ymin + GMSH_EPS) ) # At the top right part (boundary melt--gas), slip is allowed, so only # n.u=0 is enforced. Very weirdly, the PPE is consistent if and only if # the end points of UpperRight are in UpperRight. This contrasts # Left(), where the end points must NOT belong to Left(). Judging from # the experiments, these settings do the right thing. # TODO try to better understand the PPE system/dolfin's boundary # settings class Upper(SubDomain): def inside(self, x, on_boundary): return on_boundary and x[1] > ymax - GMSH_EPS class UpperRight(SubDomain): def inside(self, x, on_boundary): return ( on_boundary and x[1] > ymax - GMSH_EPS and x[0] > 0.038 - GMSH_EPS ) # The crystal boundary is taken to reach up to 0.038 where the # Dirichlet boundary data is about the melting point of the crystal, # 1511K. This setting gives pretty acceptable results when there is no # convection except the one induced by buoyancy. Is there is any more # stirring going on, though, the end point of the crystal with its # fixed temperature of 1511K might be the hottest point globally. This # looks rather unphysical. # TODO check out alternatives class UpperLeft(SubDomain): def inside(self, x, on_boundary): return ( on_boundary and x[1] > ymax - GMSH_EPS and x[0] < 0.038 + GMSH_EPS ) left = Left() crucible = Crucible() upper_left = UpperLeft() upper_right = UpperRight() self.wp_boundaries = MeshFunction( "size_t", self.submesh_workpiece, self.submesh_workpiece.topology().dim() - 1, ) self.wp_boundaries.set_all(0) left.mark(self.wp_boundaries, 1) crucible.mark(self.wp_boundaries, 2) upper_right.mark(self.wp_boundaries, 3) upper_left.mark(self.wp_boundaries, 4) if DEBUG: from dolfin import plot, interactive plot(self.wp_boundaries, title="Boundaries") interactive() submesh_boundary_indices = { "left": 1, "crucible": 2, "upper right": 3, "upper left": 4, } # Boundary conditions for the velocity. # # [1] Incompressible flow and the finite element method; volume two; # Isothermal Laminar Flow; # P.M. Gresho, R.L. Sani; # # For the choice of function space, [1] says: # "In 2D, the triangular elements P_2^+P_1 and P_2^+P_{-1} are very # good [...]. [...] If you wish to avoid bubble functions on # triangular elements, P_2P_1 is not bad, and P_2(P_1+P_0) is even # better [...]." # # It turns out that adding the bubble space significantly hampers the # convergence of the Stokes solver and also considerably increases the time it # takes to construct the Jacobian matrix of the Navier--Stokes problem if no # optimization is applied. V_element = FiniteElement("CG", self.submesh_workpiece.ufl_cell(), 2) with_bubbles = False if with_bubbles: V_element += FiniteElement("B", self.submesh_workpiece.ufl_cell(), 2) self.W_element = MixedElement(3 * [V_element]) self.W = FunctionSpace(self.submesh_workpiece, self.W_element) rot0 = Expression(("0.0", "0.0", "-2*pi*x[0] * 5.0/60.0"), degree=1) # rot0 = (0.0, 0.0, 0.0) rot1 = Expression(("0.0", "0.0", "2*pi*x[0] * 5.0/60.0"), degree=1) self.u_bcs = [ DirichletBC(self.W, rot0, crucible), DirichletBC(self.W.sub(0), 0.0, left), DirichletBC(self.W.sub(2), 0.0, left), # Make sure that u[2] is 0 at r=0. DirichletBC(self.W, rot1, upper_left), DirichletBC(self.W.sub(1), 0.0, upper_right), ] self.p_bcs = [] self.P_element = FiniteElement("CG", self.submesh_workpiece.ufl_cell(), 1) self.P = FunctionSpace(self.submesh_workpiece, self.P_element) self.Q_element = FiniteElement("CG", self.submesh_workpiece.ufl_cell(), 2) self.Q = FunctionSpace(self.submesh_workpiece, self.Q_element) # Dirichlet. # This is a bit of a tough call since the boundary conditions need to # be read from a Tecplot file here. filename = os.path.join( os.path.dirname(os.path.realpath(__file__)), "data/crucible-boundary.dat" ) data = tecplot_reader.read(filename) RZ = numpy.c_[ data["ZONE T"]["node data"]["r"], data["ZONE T"]["node data"]["z"] ] T_vals = data["ZONE T"]["node data"]["temp. [K]"] class TecplotDirichletBC(UserExpression): def eval(self, value, x): # Find on which edge x sits, and raise exception if it doesn't. edge_found = False for edge in data["ZONE T"]["element data"]: # Given a point X and an edge X0--X1, # # (1 - theta) X0 + theta X1, # # the minimum distance is assumed for # # argmin_theta ||(1-theta) X0 + theta X1 - X||^2 # = <X1 - X0, X - X0> / ||X1 - X0||^2. # # If the distance is 0 and 0<=theta<=1, we found the edge. # # Note that edges are 1-based in Tecplot. X0 = RZ[edge[0] - 1] X1 = RZ[edge[1] - 1] theta = numpy.dot(X1 - X0, x - X0) / numpy.dot(X1 - X0, X1 - X0) diff = (1.0 - theta) * X0 + theta * X1 - x if ( numpy.dot(diff, diff) < 1.0e-10 and 0.0 <= theta and theta <= 1.0 ): # Linear interpolation of the temperature value. value[0] = (1.0 - theta) * T_vals[edge[0] - 1] + theta * T_vals[ edge[1] - 1 ] edge_found = True break # This class is supposed to be used for Dirichlet boundary conditions. # For some reason, FEniCS also evaluates DirichletBC objects at # coordinates which do not sit on the boundary, see # <http://fenicsproject.org/qa/1033/dirichletbc-expressions-evaluated-away-from-the-boundary>. # The assigned values have no meaning though, so not assigning values[0] # here is okay. # # from matplotlib import pyplot as pp # pp.plot(x[0], x[1], 'xg') if not edge_found: value[0] = 0.0 if False: warnings.warn( "Coordinate ({:e}, {:e}) doesn't sit on edge.".format( x[0], x[1] ) ) # pp.plot(RZ[:, 0], RZ[:, 1], '.k') # pp.plot(x[0], x[1], 'xr') # pp.show() # raise RuntimeError('Input coordinate ' # '{} is not on boundary.'.format(x)) return tecplot_dbc = TecplotDirichletBC(degree=5) self.theta_bcs_d = [DirichletBC(self.Q, tecplot_dbc, upper_left)] self.theta_bcs_d_strict = [ DirichletBC(self.Q, tecplot_dbc, upper_right), DirichletBC(self.Q, tecplot_dbc, crucible), DirichletBC(self.Q, tecplot_dbc, upper_left), ] # Neumann dTdr_vals = data["ZONE T"]["node data"]["dTempdx [K/m]"] dTdz_vals = data["ZONE T"]["node data"]["dTempdz [K/m]"] class TecplotNeumannBC(UserExpression): def eval(self, value, x): # Same problem as above: This expression is not only evaluated at # boundaries. for edge in data["ZONE T"]["element data"]: X0 = RZ[edge[0] - 1] X1 = RZ[edge[1] - 1] theta = numpy.dot(X1 - X0, x - X0) / numpy.dot(X1 - X0, X1 - X0) dist = numpy.linalg.norm((1 - theta) * X0 + theta * X1 - x) if dist < 1.0e-5 and 0.0 <= theta and theta <= 1.0: value[0] = (1 - theta) * dTdr_vals[ edge[0] - 1 ] + theta * dTdr_vals[edge[1] - 1] value[1] = (1 - theta) * dTdz_vals[ edge[0] - 1 ] + theta * dTdz_vals[edge[1] - 1] break return def value_shape(self): return (2,) tecplot_nbc = TecplotNeumannBC(degree=5) n = FacetNormal(self.Q.mesh()) self.theta_bcs_n = { submesh_boundary_indices["upper right"]: dot(n, tecplot_nbc), submesh_boundary_indices["crucible"]: dot(n, tecplot_nbc), } self.theta_bcs_r = {} # It seems that the boundary conditions from above are inconsistent in # that solving with Dirichlet overall and mixed Dirichlet-Neumann give # different results; the value *cannot* correspond to one solution. # From looking at the solutions, the pure Dirichlet setting appears # correct, so extract the Neumann values directly from that solution. # Pick fixed coefficients roughly at the temperature that we expect. # This could be made less magic by having the coefficients depend on # theta and solving the quasilinear equation. temp_estimate = 1550.0 # Get material parameters wp_material = self.subdomain_materials[self.wpi] if isinstance(wp_material.specific_heat_capacity, float): cp = wp_material.specific_heat_capacity else: cp = wp_material.specific_heat_capacity(temp_estimate) if isinstance(wp_material.density, float): rho = wp_material.density else: rho = wp_material.density(temp_estimate) if isinstance(wp_material.thermal_conductivity, float): k = wp_material.thermal_conductivity else: k = wp_material.thermal_conductivity(temp_estimate) reference_problem = cyl_heat.Heat( self.Q, convection=None, kappa=k, rho=rho, cp=cp, source=Constant(0.0), dirichlet_bcs=self.theta_bcs_d_strict, ) theta_reference = reference_problem.solve_stationary() theta_reference.rename("theta", "temperature (Dirichlet)") # Create equivalent boundary conditions from theta_ref. This # makes sure that the potentially expensive Expression evaluation in # theta_bcs_* is replaced by something reasonably cheap. self.theta_bcs_d = [ # <https://www.allanswered.com/post/rraep/2018-1-dirichletbc-function_space-broken/> DirichletBC( FunctionSpace(bc.function_space()), theta_reference, bc.sub_domain ) for bc in self.theta_bcs_d ] # Adapt Neumann conditions. n = FacetNormal(self.Q.mesh()) self.theta_bcs_n = { k: dot(n, grad(theta_reference)) # k: Constant(1000.0) for k in self.theta_bcs_n } if DEBUG: # Solve the heat equation with the mixed Dirichlet-Neumann # boundary conditions and compare it to the Dirichlet-only # solution. theta_new = Function(self.Q, name="temperature (Neumann + Dirichlet)") from dolfin import Measure ds_workpiece = Measure("ds", subdomain_data=self.wp_boundaries) heat = cyl_heat.Heat( self.Q, convection=None, kappa=k, rho=rho, cp=cp, source=Constant(0.0), dirichlet_bcs=self.theta_bcs_d, neumann_bcs=self.theta_bcs_n, robin_bcs=self.theta_bcs_r, my_ds=ds_workpiece, ) theta_new = heat.solve_stationary() theta_new.rename("theta", "temperature (Neumann + Dirichlet)") from dolfin import plot, interactive, errornorm print( "||theta_new - theta_ref|| = {:e}".format( errornorm(theta_new, theta_reference) ) ) plot(theta_reference) plot(theta_new) plot(theta_reference - theta_new, title="theta_ref - theta_new") interactive() self.background_temp = 1400.0 # self.omega = 2 * pi * 10.0e3 self.omega = 2 * pi * 300.0 return
nschloe/maelstrom
examples/problems/crucible.py
Python
mit
18,298
[ "CRYSTAL" ]
7e394dda246cc7261006ec919eeeb7f52b607428ea0a03bdc5555142a13db943
from django.db import models, transaction # from django.db.models import get_model from edc_appointment.models import AppointmentMixin # from edc_base.audit_trail import AuditTrail from edc_base.model.models import BaseUuidModel from edc_base.model.validators import (datetime_not_before_study_start, datetime_not_future,) from edc_consent.models import RequiresConsentMixin from edc_constants.choices import YES_NO from edc_constants.constants import NO, YES from edc_export.models import ExportTrackingFieldsMixin from edc_offstudy.models import OffStudyMixin from edc_sync.models import SyncModelMixin # from ..managers import PostnatalEnrollmentManager from ..maternal_choices import LIVE_STILL_BIRTH # from .enrollment_helper import EnrollmentError # from .enrollment_mixin import EnrollmentMixin from .maternal_consent import MaternalConsent from tshilo_dikotla.constants import STILL_BIRTH class PostnatalEnrollment(SyncModelMixin, OffStudyMixin, AppointmentMixin, RequiresConsentMixin, ExportTrackingFieldsMixin, BaseUuidModel): consent_model = MaternalConsent off_study_model = ('td_maternal', 'MaternalOffStudy') weeks_base_field = 'gestation_wks_delivered' # for rapid test required calc report_datetime = models.DateTimeField( verbose_name="Report date", validators=[ datetime_not_before_study_start, datetime_not_future, ], help_text='') postpartum_days = models.IntegerField( verbose_name="How many days postpartum?", null=True, help_text="If more than 3days, not eligible") vaginal_delivery = models.CharField( verbose_name="Was this a vaginal delivery?", choices=YES_NO, max_length=3, help_text="INELIGIBLE if NO") gestation_wks_delivered = models.IntegerField( verbose_name="What was the gestational age of the newborn at birth?", help_text="ineligible if premature or born before 37weeks") delivery_status = models.CharField( verbose_name="Was this a live or still birth?", choices=LIVE_STILL_BIRTH, max_length=15, help_text='if still birth, not eligible') live_infants = models.IntegerField( verbose_name="How many live infants?", null=True, blank=True) # objects = PostnatalEnrollmentManager() # history = AuditTrail() def natural_key(self): return (self.report_datetime, self.registered_subject.natural_key()) def save(self, *args, **kwargs): self.update_with_common_fields_from_antenatal_enrollment() self.is_eligible_if_antenatal_exists_or_raise() super(PostnatalEnrollment, self).save(*args, **kwargs) def unenrolled_error_messages(self): """Returns a tuple (True, None) if mother is eligible otherwise (False, unenrolled_error_message) where error message is the reason enrollment failed.""" unenrolled_error_message = [] chronic_message = self.chronic_and_postpartum_unenrolled_error_messages() unenrolled_error_message.append(chronic_message) if chronic_message else None if self.will_breastfeed == NO: unenrolled_error_message.append('will not breastfeed') if self.will_remain_onstudy == NO: unenrolled_error_message.append('won\'t remain in study') if self.week32_test == NO: unenrolled_error_message.append('no week32 test') if self.evidence_hiv_status == NO: unenrolled_error_message.append('no HIV status evidence') if self.valid_regimen == NO: unenrolled_error_message.append('not on valid regimen') # if self.valid_regimen_duration == NO: # unenrolled_error_message.append('regimen duration invalid') if self.rapid_test_done == NO: unenrolled_error_message.append('rapid test not done') return (self.is_eligible, ', '.join(unenrolled_error_message)) def chronic_and_postpartum_unenrolled_error_messages(self): unenrolled_error_message = None if self.is_diabetic == YES: unenrolled_error_message = 'Diabetic' if self.on_tb_tx == YES: unenrolled_error_message = 'on TB treatment' if self.on_hypertension_tx == YES: unenrolled_error_message = 'Hypertensive' # postpartum if self.postpartum_days > 3: unenrolled_error_message = 'postpartum > 3days' if self.vaginal_delivery == NO: unenrolled_error_message = 'not vaginal delivery' if self.gestation_wks_delivered < 37: unenrolled_error_message = 'born before 37wks' if self.delivery_status == STILL_BIRTH: unenrolled_error_message = 'still birth' return unenrolled_error_message def get_registration_datetime(self): return self.report_datetime # def is_eligible_if_antenatal_exists_or_raise(self, exception_cls=None): # exception_cls = exception_cls or EnrollmentError # AntenatalEnrollment = get_model('mb_maternal', 'antenatalenrollment') # with transaction.atomic(): # try: # antenatal_enrollment = AntenatalEnrollment.objects.get( # registered_subject=self.registered_subject) # if not antenatal_enrollment.is_eligible: # raise EnrollmentError( # 'Subject was determined ineligible at Antenatal ' # 'Enrollment on {}. Cannot continue.'.format( # antenatal_enrollment.report_datetime)) # except AntenatalEnrollment.DoesNotExist: # pass # @property # def off_study_visit_code(self): # """Returns the visit code for the off-study visit if eligibility criteria fail. # # Returns either 1000M or, if Antenatal Enrollment exists, 2000M.""" # try: # AntenatalEnrollment = get_model('mb_maternal', 'antenatalenrollment') # AntenatalEnrollment.objects.get(registered_subject=self.registered_subject) # off_study_visit_code = '2000M' # except AntenatalEnrollment.DoesNotExist: # off_study_visit_code = '1000M' # return off_study_visit_code # def update_with_common_fields_from_antenatal_enrollment(self): # """Updates common field values from Antenatal Enrollment to # this instance if not already set. # # Only updates if AntenatalEnrollment.is_eligible=True.""" # AntenatalEnrollment = get_model('mb_maternal', 'antenatalenrollment') # try: # antenatal_enrollment = AntenatalEnrollment.objects.get( # registered_subject=self.registered_subject, # is_eligible=True) # for attrname in self.common_fields(): # if not getattr(self, attrname): # setattr(self, attrname, getattr(antenatal_enrollment, attrname)) # except AntenatalEnrollment.DoesNotExist: # pass # @property # def antenatal_enrollment(self): # """Is this ever used??""" # AntenatalEnrollment = get_model('mb_maternal', 'antenatalenrollment') # try: # return AntenatalEnrollment.objects.get(registered_subject=self.registered_subject) # except AntenatalEnrollment.DoesNotExist: # return None # return None class Meta: app_label = 'td_maternal' verbose_name = 'Postnatal Enrollment' verbose_name_plural = 'Postnatal Enrollment'
botswana-harvard/tshilo-dikotla
td_maternal/models/postnatal_enrollment.py
Python
gpl-2.0
7,617
[ "VisIt" ]
7150bba7b96ba3a5c1ecb7dac7cd4b8863908a4f2b52f7c734474755d6ccf93d
from ase import Atoms from gpaw import GPAW, PW a = 2.87 m = 2.2 fe = Atoms('Fe2', scaled_positions=[(0, 0, 0), (0.5, 0.5, 0.5)], magmoms=[m, -m], cell=(a, a, a), pbc=True) calc = GPAW(mode=PW(350), kpts=(6, 6, 6), txt='anti.txt') fe.set_calculator(calc) e = fe.get_potential_energy() calc.write('anti.gpw')
robwarm/gpaw-symm
doc/exercises/iron/anti.py
Python
gpl-3.0
409
[ "ASE", "GPAW" ]
8c165f8602a6e537923835bf966fbcf3e73273968ee706110675cebb2e40449a
# FermiLib plugin to interface with Psi4 # # Copyright (C) 2017 ProjectQ-Framework (www.projectq.ch) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Helper functions for parsing data files of different types.""" from __future__ import absolute_import import numpy from fermilib.ops import InteractionOperator def unpack_spatial_rdm(one_rdm_a, one_rdm_b, two_rdm_aa, two_rdm_ab, two_rdm_bb): """ Covert from spin compact spatial format to spin-orbital format for RDM. Note: the compact 2-RDM is stored as follows where A/B are spin up/down: RDM[pqrs] = <| a_{p, A}^\dagger a_{r, A}^\dagger a_{q, A} a_{s, A} |> for 'AA'/'BB' spins. RDM[pqrs] = <| a_{p, A}^\dagger a_{r, B}^\dagger a_{q, B} a_{s, A} |> for 'AB' spins. Args: one_rdm_a: 2-index numpy array storing alpha spin sector of 1-electron reduced density matrix. one_rdm_b: 2-index numpy array storing beta spin sector of 1-electron reduced density matrix. two_rdm_aa: 4-index numpy array storing alpha-alpha spin sector of 2-electron reduced density matrix. two_rdm_ab: 4-index numpy array storing alpha-beta spin sector of 2-electron reduced density matrix. two_rdm_bb: 4-index numpy array storing beta-beta spin sector of 2-electron reduced density matrix. Returns: one_rdm: 2-index numpy array storing 1-electron density matrix in full spin-orbital space. two_rdm: 4-index numpy array storing 2-electron density matrix in full spin-orbital space. """ # Initialize RDMs. n_orbitals = one_rdm_a.shape[0] n_qubits = 2 * n_orbitals one_rdm = numpy.zeros((n_qubits, n_qubits)) two_rdm = numpy.zeros((n_qubits, n_qubits, n_qubits, n_qubits)) # Unpack compact representation. for p in range(n_orbitals): for q in range(n_orbitals): # Populate 1-RDM. one_rdm[2 * p, 2 * q] = one_rdm_a[p, q] one_rdm[2 * p + 1, 2 * q + 1] = one_rdm_b[p, q] # Continue looping to unpack 2-RDM. for r in range(n_orbitals): for s in range(n_orbitals): # Handle case of same spin. two_rdm[2 * p, 2 * q, 2 * r, 2 * s] = ( two_rdm_aa[p, r, q, s]) two_rdm[2 * p + 1, 2 * q + 1, 2 * r + 1, 2 * s + 1] = ( two_rdm_bb[p, r, q, s]) # Handle case of mixed spin. two_rdm[2 * p, 2 * q + 1, 2 * r, 2 * s + 1] = ( two_rdm_ab[p, r, q, s]) two_rdm[2 * p, 2 * q + 1, 2 * r + 1, 2 * s] = ( -1. * two_rdm_ab[p, s, q, r]) two_rdm[2 * p + 1, 2 * q, 2 * r + 1, 2 * s] = ( two_rdm_ab[q, s, p, r]) two_rdm[2 * p + 1, 2 * q, 2 * r, 2 * s + 1] = ( -1. * two_rdm_ab[q, r, p, s]) # Map to physicist notation and return. two_rdm = numpy.einsum('pqsr', two_rdm) return one_rdm, two_rdm def parse_psi4_ccsd_amplitudes(number_orbitals, n_alpha_electrons, n_beta_electrons, psi_filename): """Parse coupled cluster singles and doubles amplitudes from psi4 file. Args: number_orbitals(int): Number of total spin orbitals in the system n_alpha_electrons(int): Number of alpha electrons in the system n_beta_electrons(int): Number of beta electrons in the system psi_filename(str): Filename of psi4 output file Returns: molecule(InteractionOperator): Molecular Operator instance holding ccsd amplitudes """ output_buffer = [line for line in open(psi_filename)] T1IA_index = None T1ia_index = None T2IJAB_index = None T2ijab_index = None T2IjAb_index = None # Find Start Indices for i, line in enumerate(output_buffer): if ('Largest TIA Amplitudes:' in line): T1IA_index = i elif ('Largest Tia Amplitudes:' in line): T1ia_index = i elif ('Largest TIJAB Amplitudes:' in line): T2IJAB_index = i elif ('Largest Tijab Amplitudes:' in line): T2ijab_index = i elif ('Largest TIjAb Amplitudes:' in line): T2IjAb_index = i T1IA_Amps = [] T1ia_Amps = [] T2IJAB_Amps = [] T2ijab_Amps = [] T2IjAb_Amps = [] # Read T1's if (T1IA_index is not None): for line in output_buffer[T1IA_index + 1:]: ivals = line.split() if not ivals: break T1IA_Amps.append([int(ivals[0]), int(ivals[1]), float(ivals[2])]) if (T1ia_index is not None): for line in output_buffer[T1ia_index + 1:]: ivals = line.split() if not ivals: break T1ia_Amps.append([int(ivals[0]), int(ivals[1]), float(ivals[2])]) # Read T2's if (T2IJAB_index is not None): for line in output_buffer[T2IJAB_index + 1:]: ivals = line.split() if not ivals: break T2IJAB_Amps.append([int(ivals[0]), int(ivals[1]), int(ivals[2]), int(ivals[3]), float(ivals[4])]) if (T2ijab_index is not None): for line in output_buffer[T2ijab_index + 1:]: ivals = line.split() if not ivals: break T2ijab_Amps.append([int(ivals[0]), int(ivals[1]), int(ivals[2]), int(ivals[3]), float(ivals[4])]) if (T2IjAb_index is not None): for line in output_buffer[T2IjAb_index + 1:]: ivals = line.split() if not ivals: break T2IjAb_Amps.append([int(ivals[0]), int(ivals[1]), int(ivals[2]), int(ivals[3]), float(ivals[4])]) # Determine if calculation is restricted / closed shell or otherwise restricted = T1ia_index is None and T2ijab_index is None # Store amplitudes with spin-orbital indexing, including appropriate # symmetry single_amplitudes = numpy.zeros((number_orbitals, ) * 2) double_amplitudes = numpy.zeros((number_orbitals, ) * 4) # Define local helper routines for clear indexing of orbitals def alpha_occupied(i): return 2 * i def alpha_unoccupied(i): return 2 * (i + n_alpha_electrons) def beta_occupied(i): return 2 * i + 1 def beta_unoccupied(i): return 2 * (i + n_beta_electrons) + 1 # Store singles for entry in T1IA_Amps: i, a, value = entry single_amplitudes[alpha_unoccupied(a), alpha_occupied(i)] = value if (restricted): single_amplitudes[beta_unoccupied(a), beta_occupied(i)] = value for entry in T1ia_Amps: i, a, value = entry single_amplitudes[beta_unoccupied(a), beta_occupied(i)] = value # Store doubles, include factor of 1/2 for convention for entry in T2IJAB_Amps: i, j, a, b, value = entry double_amplitudes[alpha_unoccupied(a), alpha_occupied(i), alpha_unoccupied(b), alpha_occupied(j)] = value / 2. if (restricted): double_amplitudes[beta_unoccupied(a), beta_occupied(i), beta_unoccupied(b), beta_occupied(j)] = value / 2. for entry in T2ijab_Amps: i, j, a, b, value = entry double_amplitudes[beta_unoccupied(a), beta_occupied(i), beta_unoccupied(b), beta_occupied(j)] = value / 2. for entry in T2IjAb_Amps: i, j, a, b, value = entry double_amplitudes[alpha_unoccupied(a), alpha_occupied(i), beta_unoccupied(b), beta_occupied(j)] = value / 2. if (restricted): double_amplitudes[beta_unoccupied(a), beta_occupied(i), alpha_unoccupied(b), alpha_occupied(j)] = value / 2. return single_amplitudes, double_amplitudes
ProjectQ-Framework/FermiLib-Plugin-Psi4
fermilibpluginpsi4/_psi4_conversion_functions.py
Python
lgpl-3.0
9,265
[ "Psi4" ]
36b8f2ea7be06e7e486df007e74b5d8b27feb4940f97a35cee0fbce6523f8573
"""Config flow for Elk-M1 Control integration.""" import logging from urllib.parse import urlparse import elkm1_lib as elkm1 import voluptuous as vol from homeassistant import config_entries, exceptions from homeassistant.const import ( CONF_ADDRESS, CONF_HOST, CONF_PASSWORD, CONF_PROTOCOL, CONF_TEMPERATURE_UNIT, CONF_USERNAME, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) from homeassistant.util import slugify from . import async_wait_for_elk_to_sync from .const import CONF_AUTO_CONFIGURE, CONF_PREFIX from .const import DOMAIN # pylint:disable=unused-import _LOGGER = logging.getLogger(__name__) PROTOCOL_MAP = {"secure": "elks://", "non-secure": "elk://", "serial": "serial://"} DATA_SCHEMA = vol.Schema( { vol.Required(CONF_PROTOCOL, default="secure"): vol.In( ["secure", "non-secure", "serial"] ), vol.Required(CONF_ADDRESS): str, vol.Optional(CONF_USERNAME, default=""): str, vol.Optional(CONF_PASSWORD, default=""): str, vol.Optional(CONF_PREFIX, default=""): str, vol.Optional(CONF_TEMPERATURE_UNIT, default=TEMP_FAHRENHEIT): vol.In( [TEMP_FAHRENHEIT, TEMP_CELSIUS] ), } ) VALIDATE_TIMEOUT = 35 async def validate_input(data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ userid = data.get(CONF_USERNAME) password = data.get(CONF_PASSWORD) prefix = data[CONF_PREFIX] url = _make_url_from_data(data) requires_password = url.startswith("elks://") if requires_password and (not userid or not password): raise InvalidAuth elk = elkm1.Elk( {"url": url, "userid": userid, "password": password, "element_list": ["panel"]} ) elk.connect() timed_out = False if not await async_wait_for_elk_to_sync(elk, VALIDATE_TIMEOUT): _LOGGER.error( "Timed out after %d seconds while trying to sync with ElkM1 at %s", VALIDATE_TIMEOUT, url, ) timed_out = True elk.disconnect() if timed_out: raise CannotConnect if elk.invalid_auth: raise InvalidAuth device_name = data[CONF_PREFIX] if data[CONF_PREFIX] else "ElkM1" # Return info that you want to store in the config entry. return {"title": device_name, CONF_HOST: url, CONF_PREFIX: slugify(prefix)} def _make_url_from_data(data): host = data.get(CONF_HOST) if host: return host protocol = PROTOCOL_MAP[data[CONF_PROTOCOL]] address = data[CONF_ADDRESS] return f"{protocol}{address}" class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Elk-M1 Control.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH def __init__(self): """Initialize the elkm1 config flow.""" self.importing = False async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: if self._url_already_configured(_make_url_from_data(user_input)): return self.async_abort(reason="address_already_configured") try: info = await validate_input(user_input) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" if "base" not in errors: await self.async_set_unique_id(user_input[CONF_PREFIX]) self._abort_if_unique_id_configured() if self.importing: return self.async_create_entry(title=info["title"], data=user_input) return self.async_create_entry( title=info["title"], data={ CONF_HOST: info[CONF_HOST], CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], CONF_AUTO_CONFIGURE: True, CONF_TEMPERATURE_UNIT: user_input[CONF_TEMPERATURE_UNIT], CONF_PREFIX: info[CONF_PREFIX], }, ) return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors ) async def async_step_import(self, user_input): """Handle import.""" self.importing = True return await self.async_step_user(user_input) def _url_already_configured(self, url): """See if we already have a elkm1 matching user input configured.""" existing_hosts = { urlparse(entry.data[CONF_HOST]).hostname for entry in self._async_current_entries() } return urlparse(url).hostname in existing_hosts class CannotConnect(exceptions.HomeAssistantError): """Error to indicate we cannot connect.""" class InvalidAuth(exceptions.HomeAssistantError): """Error to indicate there is invalid auth."""
tchellomello/home-assistant
homeassistant/components/elkm1/config_flow.py
Python
apache-2.0
5,265
[ "Elk" ]
dd8d385d7866fc82bdfa2e25c9b9fd14cec68859ecc42f4ad944374e107bcc27
#!/usr/bin/env python # -*- coding: latin-1 -*- """ Geo functions for distances, bearings, speeds, latitudes and longitudes """ from math import radians, degrees, sin, cos, tan, asin, atan2 from math import sqrt, pi, log from time import strftime def km_h(speed_in_m_s): """km_h(10) = 36 <=> 10 m/s = 36 km/h""" return 3.6 * speed_in_m_s def m_s(speed_in_km_h): """m_s(36) = 10 <=> 36 km/h = 10 m/s""" return speed_in_km_h / 3.6 def distance(lat1, lon1, lat2, lon2): """in km using haversine formula""" # convert decimal degrees to radians lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2]) # haversine formula d_lat = lat2 - lat1 d_lon = lon2 - lon1 a = sin(d_lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(d_lon / 2) ** 2 c = 2 * asin(sqrt(a)) # 6367 km is the radius of the Earth km = 6367 * c return km def bearing(lat1, lon1, lat2, lon2): """Bearing = direction, in degrees""" # convert decimal degrees to radians lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2]) direction = atan2(asin(cos(lat1) * sin((lon2 - lon1) / 2)), lat2 - lat1) return (degrees(direction) + 360) % 360 def decdeg2dms(dd): """60.5 -> (60, 30, 0.0)""" mnt, sec = divmod(dd * 3600, 60) deg, mnt = divmod(mnt, 60) return int(deg), int(mnt), sec def dms2decdeg(deg, mnt, sec): """60, 30, 0.0 -> 60.5""" return deg + mnt / float(60) + sec / float(3600) def lat_ns(lat_dd): """N or S""" return "N" if lat_dd > 0 else "S" def lon_we(lon_dd): """W or E""" return "E" if lon_dd > 0 else "W" def lat_dms_fmt(lat_dd): """60°11′35″N""" (lat_d, lat_m, lat_s) = decdeg2dms(lat_dd) ns = lat_ns(lat_dd) return "%s°%s′%s″%s" % (lat_d, lat_m, "{:.0f}".format(lat_s), ns) def lon_dms_fmt(lon_dd): """ 21°54′25″E""" (lon_d, lon_m, lon_s) = decdeg2dms(lon_dd) we = lon_we(lon_dd) return "%s°%s′%s″%s" % (lon_d, lon_m, "{:.0f}".format(lon_s), we) def lat_lon_5(lat_or_lon): """Cut off after 5 decimals""" return "{:.5f}".format(lat_or_lon) def lat2y(lat_dd): """Mercator""" return log(tan(pi / 4 + radians(lat_dd) / 2)) def lon2x(lon_dd): """Mercator""" return radians(lon_dd) def lat2canvasy(lat, min_lat, max_lat, ymin, ymax, y_center): """ Project on canvas""" lat, min_lat, max_lat = map(lat2y, [lat, min_lat, max_lat]) return (ymax - y_center - (lat - min_lat) * (ymax - ymin - 2 * y_center) / (max_lat - min_lat)) def lon2canvasx(lon, min_lon, max_lon, xmin, xmax, x_center): """ Project on canvas""" lon, min_lon, max_lon = map(lon2x, [lon, min_lon, max_lon]) return (xmin + x_center + (lon - min_lon) * (xmax - xmin - 2 * x_center) / (max_lon - min_lon)) def km2lat_diff(km): """km to latitude difference""" return float(km) / 10000 * 90 # 10000 km from equator to pole is divided into 90 degrees def km2lon_diff(km, lat): return km2lat_diff(km) / sin(radians(90 - lat)) def lat_diff2km(lat_diff): return float(lat_diff) * 10000 / 90 def lon_diff2km(lon_diff, lat): return lon_diff * sin(radians(90 - lat)) * 10000 / 90 def calc_nwse(tp_list): max_lat = -90 max_lon = -180 min_lat = 90 min_lon = 180 for tp in tp_list: max_lat = max(max_lat, tp.lat) max_lon = max(max_lon, tp.lon) min_lat = min(min_lat, tp.lat) min_lon = min(min_lon, tp.lon) mid_lat = (max_lat + min_lat) / 2 mid_lon = (max_lon + min_lon) / 2 return {'min': {'lat': min_lat, 'lon': min_lon}, 'max': {'lat': max_lat, 'lon': max_lon}, 'mid': {'lat': mid_lat, 'lon': mid_lon}} class KML(object): """Output class for KML""" def __init__(self): self.heading_level = 0 self.stamp = "" def doc_header(self, doc_name, version="2.1"): self.stamp = "Copyright green-elk.com %s" % strftime("%d.%m.%Y %H:%M") if version == "2.2": xmlns = """xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom" """ else: xmlns = 'xmlns:kml21="http://earth.google.com/kml/2.1"' k = """\ <?xml version="1.0" ?> <kml xmlns="http://www.opengis.net/kml/2.2" %s> <!-- %s -->\n <Document><name>%s</name>\n\n""" return k % (xmlns, self.stamp, doc_name) @staticmethod def tour_header(doc_name, pt): k = """\ <Folder> <name>Tour %s</name> <open>1</open> <description><![CDATA[In cities, turn on the 3D building layer]]> </description> %s <gx:Tour> <name>Start the tour here</name> <gx:Playlist>\n""" return k % (doc_name, KML.look_at(pt)) @staticmethod def tour_footer(): k = """\ </gx:Playlist> </gx:Tour> </Folder>""" return k @staticmethod def doc_footer(): return ("</Document><!-- %s -->\n</kml>\n" % "-") # self.logger.lib.response_time() def _indent(self): return " " * self.heading_level def visibility_0(self, visibility): # visibility = 0 => don't show return ("" if visibility is None else "%s<visibility>%s</visibility>\n" % (self._indent(), visibility)) def begin_section(self, heading, visibility=None, comment=""): self.heading_level += 1 h = "%s<Folder><name>%s</name>%s%s\n" comment = "<!--KML.begin_section %s %s -->" % (self.heading_level, comment) return h % (self._indent(), heading, self.visibility_0(visibility), comment) def end_section(self, comment=""): blanks = self._indent() comment = "<!--KML.end_section %s %s -->" % (self.heading_level, comment) self.heading_level -= 1 return "%s</Folder>%s\n" % (blanks, comment) def placemark_header(self, name="Placemark name", visibility=None): # visibility = 0 => don't show h = "%s<Placemark><name>%s</name>%s\n" return h % (self._indent(), name, self.visibility_0(visibility)) def placemark_footer(self): return "%s</Placemark>\n" % self._indent() def linestyle_header_footer(self, color="ff0000ff", width=4): h = "%s<Style><LineStyle><color>%s</color>" h += "%s<width>%s</width></LineStyle></Style>\n" return h % (self._indent(), color, self._indent(), width) @staticmethod def linestring_pure_header(): return "<LineString><tessellate>1</tessellate><coordinates>\n" def linestring_header(self, color="ff0000ff", width=4, visibility=None): h = "<Style><LineStyle><color>%s</color>" h += "<width>%s</width></LineStyle></Style>\n" h += " <LineString><tessellate>1</tessellate>%s<coordinates>\n" return h % (color, width, self.visibility_0(visibility)) @staticmethod def linestring_footer(): return "</coordinates></LineString>\n" @staticmethod def point_header_footer(coordinates, icon_url, label_scale=0.5, icon_scale=0.5, label_color="FFFFFFFF"): h = """<Style><LabelStyle><scale>%s</scale></LabelStyle> <IconStyle><color>%s</color><scale>%s</scale> <Icon><href>%s</href></Icon></IconStyle></Style> <Point><coordinates>%s</coordinates></Point>\n""" return h % (label_scale, label_color, icon_scale, icon_url, coordinates) @staticmethod def placemark_description(descr): return "<description><![CDATA[%s]]></description>\n" % descr @staticmethod def multigeometry_header(): """Can contain many <LineString> tags (not usable in Google Maps)""" return "<MultiGeometry>\n" @staticmethod def multigeometry_footer(): return "</MultiGeometry>\n" @staticmethod def look_at(pt): k = """<LookAt><!-- %s --> <longitude>%s</longitude> <latitude>%s</latitude> <altitude>0</altitude> <heading>%s</heading> <tilt>%s</tilt> <range>%s</range> <altitudeMode>relativeToGround</altitudeMode> </LookAt>""" return k % (pt.text, pt.lon, pt.lat, pt.heading, pt.tilt, pt.range) @staticmethod def fly_to(duration, pt, wait=""): gx_wait = ("" if wait == "" else "<gx:Wait><gx:duration>%s</gx:duration></gx:Wait>\n" % wait) k = """\t\t<gx:FlyTo> <gx:duration>%s</gx:duration> <gx:flyToMode>smooth</gx:flyToMode> %s </gx:FlyTo> %s""" return k % (duration, KML.look_at(pt), gx_wait) @staticmethod def overlay(): return """ <ScreenOverlay> <name>Left</name> <Icon> <href>https://lh3.googleusercontent.com/-HlQY-Cq_Ij8/VWWfdMCxPlI/AAAAAAAAUyY/VAAAWiGU_F0/s144/Green-Elk-Round_plus_URL-white-tv.png</href> </Icon> <overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/> <screenXY x="0.02" y="0.98" xunits="fraction" yunits="fraction"/> </ScreenOverlay>\n"""
Green-Elk/kajgps
kajgeo.py
Python
gpl-3.0
9,364
[ "Elk" ]
c497d069f2038a246b5e38cdf4825deba7a725447cf39e9d51a2935c48c92543
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, Ansible RedHat, Inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: set_stats short_description: Set stats for the current ansible run description: - This module allows setting/accumulating stats on the current ansible run, either per host or for all hosts in the run. - This module is also supported for Windows targets. author: Brian Coca (@bcoca) options: data: description: - A dictionary of which each key represents a stat (or variable) you want to keep track of. type: dict required: true per_host: description: - whether the stats are per host or for all hosts in the run. type: bool default: no aggregate: description: - Whether the provided value is aggregated to the existing stat C(yes) or will replace it C(no). type: bool default: yes notes: - In order for custom stats to be displayed, you must set C(show_custom_stats) in C(ansible.cfg) or C(ANSIBLE_SHOW_CUSTOM_STATS) to C(yes). - This module is also supported for Windows targets. version_added: "2.3" ''' EXAMPLES = r''' # Aggregating packages_installed stat per host - set_stats: data: packages_installed: 31 per_host: yes # Aggregating random stats for all hosts using complex arguments - set_stats: data: one_stat: 11 other_stat: "{{ local_var * 2 }}" another_stat: "{{ some_registered_var.results | map(attribute='ansible_facts.some_fact') | list }}" per_host: no # setting stats (not aggregating) - set_stats: data: the_answer: 42 aggregate: no '''
ilpianista/ansible
lib/ansible/modules/utilities/logic/set_stats.py
Python
gpl-3.0
1,930
[ "Brian" ]
b0198409580ab211ba36179920ced74e0e6da877d1e619c631bf329bb22fa79b
""" Run some VASP tests to ensure that the VASP calculator works. This is conditional on the existence of the VASP_COMMAND or VASP_SCRIPT environment variables """ from ase.test.vasp import installed assert installed() from ase import Atoms from ase.io import write from ase.calculators.vasp import Vasp import numpy as np def array_almost_equal(a1, a2, tol=np.finfo(type(1.0)).eps): """Replacement for old numpy.testing.utils.array_almost_equal.""" return (np.abs(a1 - a2) < tol).all() d = 1.14 co = Atoms('CO', positions=[(0, 0, 0), (0, 0, d)], pbc=True) co.center(vacuum=5.) calc = Vasp( xc = 'PBE', prec = 'Low', algo = 'Fast', ismear= 0, sigma = 1., istart = 0, lwave = False, lcharg = False) co.set_calculator(calc) en = co.get_potential_energy() write('vasp_co.traj', co) assert abs(en + 14.918933) < 5e-3 # Secondly, check that restart from the previously created VASP output works calc2 = Vasp(restart=True) co2 = calc2.get_atoms() # Need tolerance of 1e-14 because VASP itself changes coordinates # slightly between reading POSCAR and writing CONTCAR even if no ionic # steps are made. assert array_almost_equal(co.positions, co2.positions, 1e-14) assert en - co2.get_potential_energy() == 0. assert array_almost_equal(calc.get_stress(co), calc2.get_stress(co2)) assert array_almost_equal(calc.get_forces(co), calc2.get_forces(co2)) assert array_almost_equal(calc.get_eigenvalues(), calc2.get_eigenvalues()) assert calc.get_number_of_bands() == calc2.get_number_of_bands() assert calc.get_xc_functional() == calc2.get_xc_functional() # Cleanup calc.clean()
grhawk/ASE
tools/ase/test/vasp/vasp_co.py
Python
gpl-2.0
1,698
[ "ASE", "VASP" ]
6c2a3511a5b7d57c776c10c8ddf0470883d131811277eb4f30e14abd2659309c
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2001 Jesper Zedlitz # Copyright (C) 2004-2006 Donald Allingham # Copyright (C) 2007 Johan Gonqvist <johan.gronqvist@gmail.com> # Copyright (C) 2008,2012 Brian G. Matherly # Copyright (C) 2010 Jakim Friant # Copyright (C) 2013-2014 Paul Franklin # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """Reports/Text Reports /Number of Ancestors Report""" #------------------------------------------------------------------------ # # standard python modules # #------------------------------------------------------------------------ import math #------------------------------------------------------------------------ # # Gramps modules # #------------------------------------------------------------------------ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext from gramps.gen.errors import ReportError from gramps.gen.plug.menu import PersonOption from gramps.gen.plug.docgen import (IndexMark, FontStyle, ParagraphStyle, FONT_SANS_SERIF, PARA_ALIGN_CENTER, INDEX_TYPE_TOC) from gramps.gen.plug.report import Report from gramps.gen.plug.report import utils from gramps.gen.plug.report import MenuReportOptions from gramps.gen.plug.report import stdoptions from gramps.gen.display.name import displayer as _nd #------------------------------------------------------------------------ # # NumberOfAncestorsReport # #------------------------------------------------------------------------ class NumberOfAncestorsReport(Report): """ This report counts all the ancestors of the specified person. """ def __init__(self, database, options, user): """ Create the NumberOfAncestorsReport object that produces the report. The arguments are: database - the GRAMPS database instance options - instance of the Options class for this report user - a gen.user.User() instance Menu options: name_format - Preferred format to display names incl_private - Whether to include private data """ Report.__init__(self, database, options, user) stdoptions.run_private_data_option(self, options.menu) self.__db = self.database pid = options.menu.get_option_by_name('pid').get_value() self.__person = self.__db.get_person_from_gramps_id(pid) if self.__person is None: raise ReportError(_("Person %s is not in the Database") % pid) lang = options.menu.get_option_by_name('trans').get_value() self._locale = self.set_locale(lang) stdoptions.run_name_format_option(self, options.menu) def write_report(self): """ The routine that actually creates the report. At this point, the document is opened and ready for writing. """ thisgen = {} all_people = {} total_theoretical = 0 thisgen[self.__person.get_handle()] = 1 ngettext = self._locale.translation.ngettext # to see "nearby" comments self.doc.start_paragraph("NOA-Title") name = self._name_display.display(self.__person) # feature request 2356: avoid genitive form title = self._("Number of Ancestors for %s") % name mark = IndexMark(title, INDEX_TYPE_TOC, 1) self.doc.write_text(title, mark) self.doc.end_paragraph() thisgensize = 1 gen = 0 while thisgensize > 0: thisgensize = 0 if thisgen != {}: thisgensize = len(thisgen) gen += 1 theoretical = math.pow(2, (gen - 1)) total_theoretical += theoretical percent = '(%s%%)' % self._locale.format( '%3.2f', ((sum(thisgen.values()) / theoretical) * 100)) # TC # English return something like: # Generation 3 has 2 individuals. (50.00%) # translators: leave all/any {...} untranslated text = ngettext( "Generation {number} has {count} individual. {percent}", "Generation {number} has {count} individuals. {percent}", thisgensize).format(number=gen, count=thisgensize, percent=percent) self.doc.start_paragraph('NOA-Normal') self.doc.write_text(text) self.doc.end_paragraph() temp = thisgen thisgen = {} for person_handle, person_data in temp.items(): person = self.__db.get_person_from_handle(person_handle) family_handle = person.get_main_parents_family_handle() if family_handle: family = self.__db.get_family_from_handle(family_handle) father_handle = family.get_father_handle() mother_handle = family.get_mother_handle() if father_handle: thisgen[father_handle] = ( thisgen.get(father_handle, 0) + person_data ) all_people[father_handle] = ( all_people.get(father_handle, 0) + person_data ) if mother_handle: thisgen[mother_handle] = ( thisgen.get(mother_handle, 0) + person_data ) all_people[mother_handle] = ( all_people.get(mother_handle, 0) + person_data ) if total_theoretical != 1: percent = '(%3.2f%%)' % ( (sum(all_people.values()) / (total_theoretical-1)) * 100) else: percent = 0 # TC # English return something like: # Total ancestors in generations 2 to 3 is 4. (66.67%) text = self._("Total ancestors in generations %(second_generation)d " "to %(last_generation)d is %(count)d. %(percent)s" ) % {'second_generation': 2, 'last_generation' : gen, 'count' : len(all_people), 'percent' : percent} self.doc.start_paragraph('NOA-Normal') self.doc.write_text(text) self.doc.end_paragraph() #------------------------------------------------------------------------ # # NumberOfAncestorsOptions # #------------------------------------------------------------------------ class NumberOfAncestorsOptions(MenuReportOptions): """ Defines options for the NumberOfAncestorsReport. """ def __init__(self, name, dbase): self.__db = dbase self.__pid = None MenuReportOptions.__init__(self, name, dbase) def get_subject(self): """ Return a string that describes the subject of the report. """ gid = self.__pid.get_value() person = self.__db.get_person_from_gramps_id(gid) return _nd.display(person) def add_menu_options(self, menu): """ Add options to the menu for the Number of Ancestors report. """ category_name = _("Report Options") self.__pid = PersonOption(_("Center Person")) self.__pid.set_help(_("The center person for the report")) menu.add_option(category_name, "pid", self.__pid) stdoptions.add_name_format_option(menu, category_name) stdoptions.add_private_data_option(menu, category_name) stdoptions.add_localization_option(menu, category_name) def make_default_style(self, default_style): """Make the default output style for the Number of Ancestors Report.""" font = FontStyle() font.set_size(16) font.set_type_face(FONT_SANS_SERIF) font.set_bold(1) para = ParagraphStyle() para.set_header_level(1) para.set_bottom_border(1) para.set_bottom_margin(utils.pt2cm(8)) para.set_font(font) para.set_alignment(PARA_ALIGN_CENTER) para.set_description(_("The style used for the title of the page.")) default_style.add_paragraph_style("NOA-Title", para) font = FontStyle() font.set_size(12) para = ParagraphStyle() para.set_font(font) para.set_description(_('The basic style used for the text display.')) default_style.add_paragraph_style("NOA-Normal", para)
beernarrd/gramps
gramps/plugins/textreport/numberofancestorsreport.py
Python
gpl-2.0
9,325
[ "Brian" ]
0d6f19c4ac2d8966fe574b198cc828e2493b638c06422207e48be332660df0ed
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import json import os import unittest from monty.serialization import loadfn from pymatgen.analysis.defects.core import DefectEntry from pymatgen.analysis.defects.thermodynamics import DefectPhaseDiagram from pymatgen.core import Element from pymatgen.electronic_structure.dos import CompleteDos from pymatgen.util.testing import PymatgenTest class DefectsThermodynamicsTest(PymatgenTest): @classmethod def setUpClass(cls): cls.vbm_val = 2.6682 cls.gap = 1.5 cls.entries = list(loadfn(os.path.join(os.path.dirname(__file__), "GaAs_test_defentries.json")).values()) for entry in cls.entries: entry.parameters.update({"vbm": cls.vbm_val}) cls.pd = DefectPhaseDiagram(cls.entries, cls.vbm_val, cls.gap) cls.mu_elts = {Element("As"): -4.658070555, Element("Ga"): -3.7317319750000006} # make Vac_As (q= -2) only defect test single-stable-charge exceptions cls.extra_entry = DefectEntry(cls.entries[5].defect.copy(), 100.0) sep_entries = [ ent for ent in cls.entries if not (ent.name == "Vac_As_mult4" and ent.charge in [-2, -1, 0, 1, 2]) ] sep_entries.append(cls.extra_entry.copy()) cls.sep_pd = DefectPhaseDiagram(sep_entries, cls.vbm_val, cls.gap) # make Vac_As (q= -2) is incompatible for larger supercell ls_entries = cls.entries[:] for entry in ls_entries: if entry.name == "Vac_As_mult4" and entry.charge == -2.0: entry.parameters["is_compatible"] = False cls.pd_ls_fcTrue = DefectPhaseDiagram(ls_entries, cls.vbm_val, cls.gap, filter_compatible=True) cls.pd_ls_fcFalse = DefectPhaseDiagram(ls_entries, cls.vbm_val, cls.gap, filter_compatible=False) # load complete dos for fermi energy solving with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "complete_dos.json")) as f: dos_dict = json.load(f) cls.dos = CompleteDos.from_dict(dos_dict) def test_good_test_data(self): self.assertEqual(len(self.entries), 48) def test_suggest_charges(self): suggested_charges = self.pd.suggest_charges() for k in [ "Vac_As_mult4@0-1-2-3-4-5", "Sub_Ga_on_As_mult4@6-7-8-9-10-11", "Vac_Ga_mult4@12-13-14-15", "Sub_As_on_Ga_mult4@16-17-18-19-20-21", "Int_Ga_mult1@22-23-24-25", "Int_As_mult1@26-27-28-29-30-31-32-33-34", "Int_As_mult1@35-36-37-38-39-40-41-42-43", "Int_Ga_mult1@44-45-46-47", ]: self.assertTrue( len(suggested_charges[k]) > 0, f"Could not find any suggested charges for {k} with band_gap of {self.pd.band_gap}", ) pd = DefectPhaseDiagram(self.entries, 2.6682, 1.0) suggested_charges = self.pd.suggest_charges() for k in ["Vac_As_mult4@0-1-2-3-4-5", "Vac_Ga_mult4@12-13-14-15"]: self.assertTrue( len(suggested_charges[k]) > 0, f"Could not find any suggested charges for {k} with band_gap of {pd.band_gap}", ) # test again but with only one charge state stable for Vac_As suggested_charges = self.sep_pd.suggest_charges() self.assertEqual(set(suggested_charges["Vac_As_mult4@0-43"]), {-4}) def test_suggest_larger_supercells(self): suggested_larger_cells = self.pd_ls_fcFalse.suggest_larger_supercells() self.assertEqual(suggested_larger_cells["Vac_As_mult4@0-1-2-3-4-5"], [-2]) # raise error if filter_compatibile = True self.assertRaises(ValueError, self.pd_ls_fcTrue.suggest_larger_supercells) def test_entries(self): all_stable_entries = self.pd.all_stable_entries self.assertEqual(len(self.pd.defect_types), 8) self.assertEqual( len(all_stable_entries), sum(len(v) for v in self.pd.stable_charges.values()), ) # test again but with only one charge state stable for Vac_As self.assertEqual(len(self.sep_pd.transition_level_map["Vac_As_mult4@0-43"]), 0) self.assertEqual(len(self.sep_pd.stable_entries["Vac_As_mult4@0-43"]), 1) self.assertEqual(len(self.sep_pd.finished_charges["Vac_As_mult4@0-43"]), 2) def test_solve_for_fermi_energy(self): fermi_energy = self.pd.solve_for_fermi_energy(100.0, self.mu_elts, self.dos) self.assertAlmostEqual(fermi_energy, 0.8334775317578078, 3) fermi_energy = self.pd.solve_for_fermi_energy(1000.0, self.mu_elts, self.dos) self.assertAlmostEqual(fermi_energy, 0.74139553, 3) def test_solve_for_non_equilibrium_fermi_energy(self): fermi_energy = self.pd.solve_for_non_equilibrium_fermi_energy(300.0, 1000.0, self.mu_elts, self.dos) self.assertAlmostEqual(fermi_energy, 0.29500637, 3) fermi_energy = self.pd.solve_for_non_equilibrium_fermi_energy(1000.0, 1000.0, self.mu_elts, self.dos) self.assertAlmostEqual(fermi_energy, 0.7413955908839398, 3) def test_get_dopability_limits(self): lower_lim, upper_lim = self.pd.get_dopability_limits(self.mu_elts) self.assertAlmostEqual(lower_lim, -0.39996272) self.assertAlmostEqual(upper_lim, 1.064193047) # raise error if defects are negative across gap bad_mu_elts = self.mu_elts.copy() bad_mu_elts[Element("Ga")] += 10.0 lower_lim, upper_lim = self.pd.get_dopability_limits(bad_mu_elts) self.assertIsNone(lower_lim) self.assertIsNone(upper_lim) # def test_plot(self): # # simple test that plot is produced # p = self.pd.plot(saved=False) # self.assertTrue(p) if __name__ == "__main__": unittest.main()
vorwerkc/pymatgen
pymatgen/analysis/defects/tests/test_thermodynamics.py
Python
mit
5,831
[ "pymatgen" ]
4ede8fdc21b5ebdfc2ff4c792f0ceb91662ab088af78ddd2f61720f0f74c8ecf
from sympy import (meijerg, I, S, integrate, Integral, oo, gamma, cosh, hyperexpand, exp, simplify, sqrt, pi, erf, sin, cos, exp_polar, polygamma, hyper, log, expand_func) from sympy.integrals.meijerint import (_rewrite_single, _rewrite1, meijerint_indefinite, _inflate_g, _create_lookup_table, meijerint_definite, meijerint_inversion) from sympy.utilities import default_sort_key from sympy.utilities.pytest import slow from sympy.utilities.randtest import (verify_numerically, random_complex_number as randcplx) from sympy.core.compatibility import range from sympy.abc import x, y, a, b, c, d, s, t, z def test_rewrite_single(): def t(expr, c, m): e = _rewrite_single(meijerg([a], [b], [c], [d], expr), x) assert e is not None assert isinstance(e[0][0][2], meijerg) assert e[0][0][2].argument.as_coeff_mul(x) == (c, (m,)) def tn(expr): assert _rewrite_single(meijerg([a], [b], [c], [d], expr), x) is None t(x, 1, x) t(x**2, 1, x**2) t(x**2 + y*x**2, y + 1, x**2) tn(x**2 + x) tn(x**y) def u(expr, x): from sympy import Add, exp, exp_polar r = _rewrite_single(expr, x) e = Add(*[res[0]*res[2] for res in r[0]]).replace( exp_polar, exp) # XXX Hack? assert verify_numerically(e, expr, x) u(exp(-x)*sin(x), x) # The following has stopped working because hyperexpand changed slightly. # It is probably not worth fixing #u(exp(-x)*sin(x)*cos(x), x) # This one cannot be done numerically, since it comes out as a g-function # of argument 4*pi # NOTE This also tests a bug in inverse mellin transform (which used to # turn exp(4*pi*I*t) into a factor of exp(4*pi*I)**t instead of # exp_polar). #u(exp(x)*sin(x), x) assert _rewrite_single(exp(x)*sin(x), x) == \ ([(-sqrt(2)/(2*sqrt(pi)), 0, meijerg(((-S(1)/2, 0, S(1)/4, S(1)/2, S(3)/4), (1,)), ((), (-S(1)/2, 0)), 64*exp_polar(-4*I*pi)/x**4))], True) def test_rewrite1(): assert _rewrite1(x**3*meijerg([a], [b], [c], [d], x**2 + y*x**2)*5, x) == \ (5, x**3, [(1, 0, meijerg([a], [b], [c], [d], x**2*(y + 1)))], True) def test_meijerint_indefinite_numerically(): def t(fac, arg): g = meijerg([a], [b], [c], [d], arg)*fac subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(), d: randcplx()} integral = meijerint_indefinite(g, x) assert integral is not None assert verify_numerically(g.subs(subs), integral.diff(x).subs(subs), x) t(1, x) t(2, x) t(1, 2*x) t(1, x**2) t(5, x**S('3/2')) t(x**3, x) t(3*x**S('3/2'), 4*x**S('7/3')) def test_meijerint_definite(): v, b = meijerint_definite(x, x, 0, 0) assert v.is_zero and b is True v, b = meijerint_definite(x, x, oo, oo) assert v.is_zero and b is True def test_inflate(): subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(), d: randcplx(), y: randcplx()/10} def t(a, b, arg, n): from sympy import Mul m1 = meijerg(a, b, arg) m2 = Mul(*_inflate_g(m1, n)) # NOTE: (the random number)**9 must still be on the principal sheet. # Thus make b&d small to create random numbers of small imaginary part. return verify_numerically(m1.subs(subs), m2.subs(subs), x, b=0.1, d=-0.1) assert t([[a], [b]], [[c], [d]], x, 3) assert t([[a, y], [b]], [[c], [d]], x, 3) assert t([[a], [b]], [[c, y], [d]], 2*x**3, 3) def test_recursive(): from sympy import symbols, refine a, b, c = symbols('a b c', positive=True) r = exp(-(x - a)**2)*exp(-(x - b)**2) e = integrate(r, (x, 0, oo), meijerg=True) assert simplify(e.expand()) == ( sqrt(2)*sqrt(pi)*( (erf(sqrt(2)*(a + b)/2) + 1)*exp(-a**2/2 + a*b - b**2/2))/4) e = integrate(exp(-(x - a)**2)*exp(-(x - b)**2)*exp(c*x), (x, 0, oo), meijerg=True) assert simplify(e) == ( sqrt(2)*sqrt(pi)*(erf(sqrt(2)*(2*a + 2*b + c)/4) + 1)*exp(-a**2 - b**2 + (2*a + 2*b + c)**2/8)/4) assert simplify(integrate(exp(-(x - a - b - c)**2), (x, 0, oo), meijerg=True)) == \ sqrt(pi)/2*(1 + erf(a + b + c)) assert simplify(refine(integrate(exp(-(x + a + b + c)**2), (x, 0, oo), meijerg=True))) == \ sqrt(pi)/2*(1 - erf(a + b + c)) @slow def test_meijerint(): from sympy import symbols, expand, arg s, t, mu = symbols('s t mu', real=True) assert integrate(meijerg([], [], [0], [], s*t) *meijerg([], [], [mu/2], [-mu/2], t**2/4), (t, 0, oo)).is_Piecewise s = symbols('s', positive=True) assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo)) == \ gamma(s + 1) assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=True) == gamma(s + 1) assert isinstance(integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=False), Integral) assert meijerint_indefinite(exp(x), x) == exp(x) # TODO what simplifications should be done automatically? # This tests "extra case" for antecedents_1. a, b = symbols('a b', positive=True) assert simplify(meijerint_definite(x**a, x, 0, b)[0]) == \ b**(a + 1)/(a + 1) # This tests various conditions and expansions: meijerint_definite((x + 1)**3*exp(-x), x, 0, oo) == (16, True) # Again, how about simplifications? sigma, mu = symbols('sigma mu', positive=True) i, c = meijerint_definite(exp(-((x - mu)/(2*sigma))**2), x, 0, oo) assert simplify(i) == sqrt(pi)*sigma*(erf(mu/(2*sigma)) + 1) assert c == True i, _ = meijerint_definite(exp(-mu*x)*exp(sigma*x), x, 0, oo) # TODO it would be nice to test the condition assert simplify(i) == 1/(mu - sigma) # Test substitutions to change limits assert meijerint_definite(exp(x), x, -oo, 2) == (exp(2), True) # Note: causes a NaN in _check_antecedents assert expand(meijerint_definite(exp(x), x, 0, I)[0]) == exp(I) - 1 assert expand(meijerint_definite(exp(-x), x, 0, x)[0]) == \ 1 - exp(-exp(I*arg(x))*abs(x)) # Test -oo to oo assert meijerint_definite(exp(-x**2), x, -oo, oo) == (sqrt(pi), True) assert meijerint_definite(exp(-abs(x)), x, -oo, oo) == (2, True) assert meijerint_definite(exp(-(2*x - 3)**2), x, -oo, oo) == \ (sqrt(pi)/2, True) assert meijerint_definite(exp(-abs(2*x - 3)), x, -oo, oo) == (1, True) assert meijerint_definite(exp(-((x - mu)/sigma)**2/2)/sqrt(2*pi*sigma**2), x, -oo, oo) == (1, True) # Test one of the extra conditions for 2 g-functinos assert meijerint_definite(exp(-x)*sin(x), x, 0, oo) == (S(1)/2, True) # Test a bug def res(n): return (1/(1 + x**2)).diff(x, n).subs(x, 1)*(-1)**n for n in range(6): assert integrate(exp(-x)*sin(x)*x**n, (x, 0, oo), meijerg=True) == \ res(n) # This used to test trigexpand... now it is done by linear substitution assert simplify(integrate(exp(-x)*sin(x + a), (x, 0, oo), meijerg=True) ) == sqrt(2)*sin(a + pi/4)/2 # Test the condition 14 from prudnikov. # (This is besselj*besselj in disguise, to stop the product from being # recognised in the tables.) a, b, s = symbols('a b s') from sympy import And, re assert meijerint_definite(meijerg([], [], [a/2], [-a/2], x/4) *meijerg([], [], [b/2], [-b/2], x/4)*x**(s - 1), x, 0, oo) == \ (4*2**(2*s - 2)*gamma(-2*s + 1)*gamma(a/2 + b/2 + s) /(gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1) *gamma(a/2 + b/2 - s + 1)), And(0 < -2*re(4*s) + 8, 0 < re(a/2 + b/2 + s), re(2*s) < 1)) # test a bug assert integrate(sin(x**a)*sin(x**b), (x, 0, oo), meijerg=True) == \ Integral(sin(x**a)*sin(x**b), (x, 0, oo)) # test better hyperexpand assert integrate(exp(-x**2)*log(x), (x, 0, oo), meijerg=True) == \ (sqrt(pi)*polygamma(0, S(1)/2)/4).expand() # Test hyperexpand bug. from sympy import lowergamma n = symbols('n', integer=True) assert simplify(integrate(exp(-x)*x**n, x, meijerg=True)) == \ lowergamma(n + 1, x) # Test a bug with argument 1/x alpha = symbols('alpha', positive=True) assert meijerint_definite((2 - x)**alpha*sin(alpha/x), x, 0, 2) == \ (sqrt(pi)*alpha*gamma(alpha + 1)*meijerg(((), (alpha/2 + S(1)/2, alpha/2 + 1)), ((0, 0, S(1)/2), (-S(1)/2,)), alpha**S(2)/16)/4, True) # test a bug related to 3016 a, s = symbols('a s', positive=True) assert simplify(integrate(x**s*exp(-a*x**2), (x, -oo, oo))) == \ a**(-s/2 - S(1)/2)*((-1)**s + 1)*gamma(s/2 + S(1)/2)/2 def test_bessel(): from sympy import besselj, besseli assert simplify(integrate(besselj(a, z)*besselj(b, z)/z, (z, 0, oo), meijerg=True, conds='none')) == \ 2*sin(pi*(a/2 - b/2))/(pi*(a - b)*(a + b)) assert simplify(integrate(besselj(a, z)*besselj(a, z)/z, (z, 0, oo), meijerg=True, conds='none')) == 1/(2*a) # TODO more orthogonality integrals assert simplify(integrate(sin(z*x)*(x**2 - 1)**(-(y + S(1)/2)), (x, 1, oo), meijerg=True, conds='none') *2/((z/2)**y*sqrt(pi)*gamma(S(1)/2 - y))) == \ besselj(y, z) # Werner Rosenheinrich # SOME INDEFINITE INTEGRALS OF BESSEL FUNCTIONS assert integrate(x*besselj(0, x), x, meijerg=True) == x*besselj(1, x) assert integrate(x*besseli(0, x), x, meijerg=True) == x*besseli(1, x) # TODO can do higher powers, but come out as high order ... should they be # reduced to order 0, 1? assert integrate(besselj(1, x), x, meijerg=True) == -besselj(0, x) assert integrate(besselj(1, x)**2/x, x, meijerg=True) == \ -(besselj(0, x)**2 + besselj(1, x)**2)/2 # TODO more besseli when tables are extended or recursive mellin works assert integrate(besselj(0, x)**2/x**2, x, meijerg=True) == \ -2*x*besselj(0, x)**2 - 2*x*besselj(1, x)**2 \ + 2*besselj(0, x)*besselj(1, x) - besselj(0, x)**2/x assert integrate(besselj(0, x)*besselj(1, x), x, meijerg=True) == \ -besselj(0, x)**2/2 assert integrate(x**2*besselj(0, x)*besselj(1, x), x, meijerg=True) == \ x**2*besselj(1, x)**2/2 assert integrate(besselj(0, x)*besselj(1, x)/x, x, meijerg=True) == \ (x*besselj(0, x)**2 + x*besselj(1, x)**2 - besselj(0, x)*besselj(1, x)) # TODO how does besselj(0, a*x)*besselj(0, b*x) work? # TODO how does besselj(0, x)**2*besselj(1, x)**2 work? # TODO sin(x)*besselj(0, x) etc come out a mess # TODO can x*log(x)*besselj(0, x) be done? # TODO how does besselj(1, x)*besselj(0, x+a) work? # TODO more indefinite integrals when struve functions etc are implemented # test a substitution assert integrate(besselj(1, x**2)*x, x, meijerg=True) == \ -besselj(0, x**2)/2 def test_inversion(): from sympy import piecewise_fold, besselj, sqrt, sin, cos, Heaviside def inv(f): return piecewise_fold(meijerint_inversion(f, s, t)) assert inv(1/(s**2 + 1)) == sin(t)*Heaviside(t) assert inv(s/(s**2 + 1)) == cos(t)*Heaviside(t) assert inv(exp(-s)/s) == Heaviside(t - 1) assert inv(1/sqrt(1 + s**2)) == besselj(0, t)*Heaviside(t) # Test some antcedents checking. assert meijerint_inversion(sqrt(s)/sqrt(1 + s**2), s, t) is None assert inv(exp(s**2)) is None assert meijerint_inversion(exp(-s**2), s, t) is None @slow def test_lookup_table(): from random import uniform, randrange from sympy import Add from sympy.integrals.meijerint import z as z_dummy table = {} _create_lookup_table(table) for _, l in sorted(table.items()): for formula, terms, cond, hint in sorted(l, key=default_sort_key): subs = {} for a in list(formula.free_symbols) + [z_dummy]: if hasattr(a, 'properties') and a.properties: # these Wilds match positive integers subs[a] = randrange(1, 10) else: subs[a] = uniform(1.5, 2.0) if not isinstance(terms, list): terms = terms(subs) # First test that hyperexpand can do this. expanded = [hyperexpand(g) for (_, g) in terms] assert all(x.is_Piecewise or not x.has(meijerg) for x in expanded) # Now test that the meijer g-function is indeed as advertised. expanded = Add(*[f*x for (f, x) in terms]) a, b = formula.n(subs=subs), expanded.n(subs=subs) r = min(abs(a), abs(b)) if r < 1: assert abs(a - b).n() <= 1e-10 else: assert (abs(a - b)/r).n() <= 1e-10 def test_branch_bug(): from sympy import powdenest, lowergamma # TODO combsimp cannot prove that the factor is unity assert powdenest(integrate(erf(x**3), x, meijerg=True).diff(x), polar=True) == 2*erf(x**3)*gamma(S(2)/3)/3/gamma(S(5)/3) assert integrate(erf(x**3), x, meijerg=True) == \ 2*x*erf(x**3)*gamma(S(2)/3)/(3*gamma(S(5)/3)) \ - 2*gamma(S(2)/3)*lowergamma(S(2)/3, x**6)/(3*sqrt(pi)*gamma(S(5)/3)) def test_linear_subs(): from sympy import besselj assert integrate(sin(x - 1), x, meijerg=True) == -cos(1 - x) assert integrate(besselj(1, x - 1), x, meijerg=True) == -besselj(0, 1 - x) @slow def test_probability(): # various integrals from probability theory from sympy.abc import x, y from sympy import symbols, Symbol, Abs, expand_mul, combsimp, powsimp, sin mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True) sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True, finite=True, positive=True) rate = Symbol('lambda', real=True, positive=True, finite=True) def normal(x, mu, sigma): return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2) def exponential(x, rate): return rate*exp(-rate*x) assert integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == 1 assert integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == \ mu1 assert integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \ == mu1**2 + sigma1**2 assert integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \ == mu1**3 + 3*mu1*sigma1**2 assert integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 assert integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1 assert integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu2 assert integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1*mu2 assert integrate((x + y + 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 + mu1 + mu2 assert integrate((x + y - 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == \ -1 + mu1 + mu2 i = integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) assert not i.has(Abs) assert simplify(i) == mu1**2 + sigma1**2 assert integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == \ sigma2**2 + mu2**2 assert integrate(exponential(x, rate), (x, 0, oo), meijerg=True) == 1 assert integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True) == \ 1/rate assert integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True) == \ 2/rate**2 def E(expr): res1 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (x, 0, oo), (y, -oo, oo), meijerg=True) res2 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (y, -oo, oo), (x, 0, oo), meijerg=True) assert expand_mul(res1) == expand_mul(res2) return res1 assert E(1) == 1 assert E(x*y) == mu1/rate assert E(x*y**2) == mu1**2/rate + sigma1**2/rate ans = sigma1**2 + 1/rate**2 assert simplify(E((x + y + 1)**2) - E(x + y + 1)**2) == ans assert simplify(E((x + y - 1)**2) - E(x + y - 1)**2) == ans assert simplify(E((x + y)**2) - E(x + y)**2) == ans # Beta' distribution alpha, beta = symbols('alpha beta', positive=True) betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \ /gamma(alpha)/gamma(beta) assert integrate(betadist, (x, 0, oo), meijerg=True) == 1 i = integrate(x*betadist, (x, 0, oo), meijerg=True, conds='separate') assert (combsimp(i[0]), i[1]) == (alpha/(beta - 1), 1 < beta) j = integrate(x**2*betadist, (x, 0, oo), meijerg=True, conds='separate') assert j[1] == (1 < beta - 1) assert combsimp(j[0] - i[0]**2) == (alpha + beta - 1)*alpha \ /(beta - 2)/(beta - 1)**2 # Beta distribution # NOTE: this is evaluated using antiderivatives. It also tests that # meijerint_indefinite returns the simplest possible answer. a, b = symbols('a b', positive=True) betadist = x**(a - 1)*(-x + 1)**(b - 1)*gamma(a + b)/(gamma(a)*gamma(b)) assert simplify(integrate(betadist, (x, 0, 1), meijerg=True)) == 1 assert simplify(integrate(x*betadist, (x, 0, 1), meijerg=True)) == \ a/(a + b) assert simplify(integrate(x**2*betadist, (x, 0, 1), meijerg=True)) == \ a*(a + 1)/(a + b)/(a + b + 1) assert simplify(integrate(x**y*betadist, (x, 0, 1), meijerg=True)) == \ gamma(a + b)*gamma(a + y)/gamma(a)/gamma(a + b + y) # Chi distribution k = Symbol('k', integer=True, positive=True) chi = 2**(1 - k/2)*x**(k - 1)*exp(-x**2/2)/gamma(k/2) assert powsimp(integrate(chi, (x, 0, oo), meijerg=True)) == 1 assert simplify(integrate(x*chi, (x, 0, oo), meijerg=True)) == \ sqrt(2)*gamma((k + 1)/2)/gamma(k/2) assert simplify(integrate(x**2*chi, (x, 0, oo), meijerg=True)) == k # Chi^2 distribution chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2) assert powsimp(integrate(chisquared, (x, 0, oo), meijerg=True)) == 1 assert simplify(integrate(x*chisquared, (x, 0, oo), meijerg=True)) == k assert simplify(integrate(x**2*chisquared, (x, 0, oo), meijerg=True)) == \ k*(k + 2) assert combsimp(integrate(((x - k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)) == 2*sqrt(2)/sqrt(k) # Dagum distribution a, b, p = symbols('a b p', positive=True) # XXX (x/b)**a does not work dagum = a*p/x*(x/b)**(a*p)/(1 + x**a/b**a)**(p + 1) assert simplify(integrate(dagum, (x, 0, oo), meijerg=True)) == 1 # XXX conditions are a mess arg = x*dagum assert simplify(integrate(arg, (x, 0, oo), meijerg=True, conds='none') ) == a*b*gamma(1 - 1/a)*gamma(p + 1 + 1/a)/( (a*p + 1)*gamma(p)) assert simplify(integrate(x*arg, (x, 0, oo), meijerg=True, conds='none') ) == a*b**2*gamma(1 - 2/a)*gamma(p + 1 + 2/a)/( (a*p + 2)*gamma(p)) # F-distribution d1, d2 = symbols('d1 d2', positive=True) f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \ /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2) assert simplify(integrate(f, (x, 0, oo), meijerg=True)) == 1 # TODO conditions are a mess assert simplify(integrate(x*f, (x, 0, oo), meijerg=True, conds='none') ) == d2/(d2 - 2) assert simplify(integrate(x**2*f, (x, 0, oo), meijerg=True, conds='none') ) == d2**2*(d1 + 2)/d1/(d2 - 4)/(d2 - 2) # TODO gamma, rayleigh # inverse gaussian lamda, mu = symbols('lamda mu', positive=True) dist = sqrt(lamda/2/pi)*x**(-S(3)/2)*exp(-lamda*(x - mu)**2/x/2/mu**2) mysimp = lambda expr: simplify(expr.rewrite(exp)) assert mysimp(integrate(dist, (x, 0, oo))) == 1 assert mysimp(integrate(x*dist, (x, 0, oo))) == mu assert mysimp(integrate((x - mu)**2*dist, (x, 0, oo))) == mu**3/lamda assert mysimp(integrate((x - mu)**3*dist, (x, 0, oo))) == 3*mu**5/lamda**2 # Levi c = Symbol('c', positive=True) assert integrate(sqrt(c/2/pi)*exp(-c/2/(x - mu))/(x - mu)**S('3/2'), (x, mu, oo)) == 1 # higher moments oo # log-logistic distn = (beta/alpha)*x**(beta - 1)/alpha**(beta - 1)/ \ (1 + x**beta/alpha**beta)**2 assert simplify(integrate(distn, (x, 0, oo))) == 1 # NOTE the conditions are a mess, but correctly state beta > 1 assert simplify(integrate(x*distn, (x, 0, oo), conds='none')) == \ pi*alpha/beta/sin(pi/beta) # (similar comment for conditions applies) assert simplify(integrate(x**y*distn, (x, 0, oo), conds='none')) == \ pi*alpha**y*y/beta/sin(pi*y/beta) # weibull k = Symbol('k', positive=True) n = Symbol('n', positive=True) distn = k/lamda*(x/lamda)**(k - 1)*exp(-(x/lamda)**k) assert simplify(integrate(distn, (x, 0, oo))) == 1 assert simplify(integrate(x**n*distn, (x, 0, oo))) == \ lamda**n*gamma(1 + n/k) # rice distribution from sympy import besseli nu, sigma = symbols('nu sigma', positive=True) rice = x/sigma**2*exp(-(x**2 + nu**2)/2/sigma**2)*besseli(0, x*nu/sigma**2) assert integrate(rice, (x, 0, oo), meijerg=True) == 1 # can someone verify higher moments? # Laplace distribution mu = Symbol('mu', real=True) b = Symbol('b', positive=True) laplace = exp(-abs(x - mu)/b)/2/b assert integrate(laplace, (x, -oo, oo), meijerg=True) == 1 assert integrate(x*laplace, (x, -oo, oo), meijerg=True) == mu assert integrate(x**2*laplace, (x, -oo, oo), meijerg=True) == \ 2*b**2 + mu**2 # TODO are there other distributions supported on (-oo, oo) that we can do? # misc tests k = Symbol('k', positive=True) assert combsimp(expand_mul(integrate(log(x)*x**(k - 1)*exp(-x)/gamma(k), (x, 0, oo)))) == polygamma(0, k) def test_expint(): """ Test various exponential integrals. """ from sympy import (expint, unpolarify, Symbol, Ci, Si, Shi, Chi, sin, cos, sinh, cosh, Ei) assert simplify(unpolarify(integrate(exp(-z*x)/x**y, (x, 1, oo), meijerg=True, conds='none' ).rewrite(expint).expand(func=True))) == expint(y, z) assert integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(1, z) assert integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(2, z).rewrite(Ei).rewrite(expint) assert integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(3, z).rewrite(Ei).rewrite(expint).expand() t = Symbol('t', positive=True) assert integrate(-cos(x)/x, (x, t, oo), meijerg=True).expand() == Ci(t) assert integrate(-sin(x)/x, (x, t, oo), meijerg=True).expand() == \ Si(t) - pi/2 assert integrate(sin(x)/x, (x, 0, z), meijerg=True) == Si(z) assert integrate(sinh(x)/x, (x, 0, z), meijerg=True) == Shi(z) assert integrate(exp(-x)/x, x, meijerg=True).expand().rewrite(expint) == \ I*pi - expint(1, x) assert integrate(exp(-x)/x**2, x, meijerg=True).rewrite(expint).expand() \ == expint(1, x) - exp(-x)/x - I*pi u = Symbol('u', polar=True) assert integrate(cos(u)/u, u, meijerg=True).expand().as_independent(u)[1] \ == Ci(u) assert integrate(cosh(u)/u, u, meijerg=True).expand().as_independent(u)[1] \ == Chi(u) assert integrate(expint(1, x), x, meijerg=True ).rewrite(expint).expand() == x*expint(1, x) - exp(-x) assert integrate(expint(2, x), x, meijerg=True ).rewrite(expint).expand() == \ -x**2*expint(1, x)/2 + x*exp(-x)/2 - exp(-x)/2 assert simplify(unpolarify(integrate(expint(y, x), x, meijerg=True).rewrite(expint).expand(func=True))) == \ -expint(y + 1, x) assert integrate(Si(x), x, meijerg=True) == x*Si(x) + cos(x) assert integrate(Ci(u), u, meijerg=True).expand() == u*Ci(u) - sin(u) assert integrate(Shi(x), x, meijerg=True) == x*Shi(x) - cosh(x) assert integrate(Chi(u), u, meijerg=True).expand() == u*Chi(u) - sinh(u) assert integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True) == pi/4 assert integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True) == log(2)/2 def test_messy(): from sympy import (laplace_transform, Si, Shi, Chi, atan, Piecewise, acoth, E1, besselj, acosh, asin, And, re, fourier_transform, sqrt) assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi/2)/s, 0, True) assert laplace_transform(Shi(x), x, s) == (acoth(s)/s, 1, True) # where should the logs be simplified? assert laplace_transform(Chi(x), x, s) == \ ((log(s**(-2)) - log((s**2 - 1)/s**2))/(2*s), 1, True) # TODO maybe simplify the inequalities? assert laplace_transform(besselj(a, x), x, s)[1:] == \ (0, And(S(0) < re(a/2) + S(1)/2, S(0) < re(a/2) + 1)) # NOTE s < 0 can be done, but argument reduction is not good enough yet assert fourier_transform(besselj(1, x)/x, x, s, noconds=False) == \ (Piecewise((0, 4*abs(pi**2*s**2) > 1), (2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0) # TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons) # - folding could be better assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \ log(1 + sqrt(2)) assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \ log(S(1)/2 + sqrt(2)/2) assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \ Piecewise((-acosh(1/x), 1 < abs(x**(-2))), (I*asin(1/x), True)) def test_issue_6122(): assert integrate(exp(-I*x**2), (x, -oo, oo), meijerg=True) == \ -I*sqrt(pi)*exp(I*pi/4) def test_issue_6252(): expr = 1/x/(a + b*x)**(S(1)/3) anti = integrate(expr, x, meijerg=True) assert not expr.has(hyper) # XXX the expression is a mess, but actually upon differentiation and # putting in numerical values seems to work... def test_issue_6348(): assert integrate(exp(I*x)/(1 + x**2), (x, -oo, oo)).simplify().rewrite(exp) \ == pi*exp(-1) def test_fresnel(): from sympy import fresnels, fresnelc assert expand_func(integrate(sin(pi*x**2/2), x)) == fresnels(x) assert expand_func(integrate(cos(pi*x**2/2), x)) == fresnelc(x) def test_issue_6860(): assert meijerint_indefinite(x**x**x, x) is None def test_issue_8368(): assert meijerint_indefinite(cosh(x)*exp(-x*t), x) == ( (-t - 1)*exp(x) + (-t + 1)*exp(-x))*exp(-t*x)/2/(t**2 - 1)
ga7g08/sympy
sympy/integrals/tests/test_meijerint.py
Python
bsd-3-clause
27,483
[ "Gaussian" ]
9bebb60dd01b1564e3abde3da47e86159996614c01d1338d75c3e1adb459bcb1
import pytest from pytest_bdd import scenario, given, when, then from webapp.apprunner import start, stop @pytest.yield_fixture def app(): yield start() stop() @scenario('website.feature', 'I visit the website') def test_website(): pass @given("The server is running") def server(app): """ start server """ pass @when("I visit the site") def visit_site(browser, app): """ load the site in the browser""" browser.visit(app) @then("I see a webpage") def page_visible(browser): assert browser.status_code.is_success() assert not browser.find_by_tag('h1').is_empty()
bitterjug/munger
tests/functional/setup/test_website.py
Python
gpl-2.0
609
[ "VisIt" ]
4c241c3fbb7398cbbb524f53649af81081547cd87fd98b262226d275dabb1248
"""A generic client for creating and managing transformations. See the information about transformation parameters below. """ from __future__ import print_function from __future__ import absolute_import from __future__ import division import six import json from DIRAC import gLogger, gConfig, S_OK, S_ERROR from DIRAC.Core.Utilities.PromptUser import promptUser from DIRAC.Core.Base.API import API from DIRAC.TransformationSystem.Client.TransformationClient import TransformationClient from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations from DIRAC.Core.Security.ProxyInfo import getProxyInfo from DIRAC.RequestManagementSystem.Client.Operation import Operation COMPONENT_NAME = 'Transformation' __RCSID__ = '$Id$' class Transformation(API): ############################################################################# def __init__(self, transID=0, transClient=None): """ c'tor """ super(Transformation, self).__init__() self.paramTypes = {'TransformationID': six.integer_types, 'TransformationName': six.string_types, 'Status': six.string_types, 'Description': six.string_types, 'LongDescription': six.string_types, 'Type': six.string_types, 'Plugin': six.string_types, 'AgentType': six.string_types, 'FileMask': six.string_types, 'TransformationGroup': six.string_types, 'GroupSize': six.integer_types + (float,), 'InheritedFrom': six.integer_types, 'Body': six.string_types, 'MaxNumberOfTasks': six.integer_types, 'EventsPerTask': six.integer_types} self.paramValues = {'TransformationID': 0, 'TransformationName': '', 'Status': 'New', 'Description': '', 'LongDescription': '', 'Type': '', 'Plugin': 'Standard', 'AgentType': 'Manual', 'FileMask': '', 'TransformationGroup': 'General', 'GroupSize': 1, 'InheritedFrom': 0, 'Body': '', 'MaxNumberOfTasks': 0, 'EventsPerTask': 0} # the metaquery parameters are neither part of the transformation parameters nor the additional parameters, so # special treatment is necessary self.inputMetaQuery = None self.outputMetaQuery = None self.ops = Operations() self.supportedPlugins = self.ops.getValue('Transformations/AllowedPlugins', ['Broadcast', 'Standard', 'BySize', 'ByShare']) if not transClient: self.transClient = TransformationClient() else: self.transClient = transClient self.serverURL = self.transClient.getServer() self.exists = False if transID: self.paramValues['TransformationID'] = transID res = self.getTransformation() if res['OK']: self.exists = True elif res['Message'] == 'Transformation does not exist': raise AttributeError('TransformationID %d does not exist' % transID) else: self.paramValues['TransformationID'] = 0 gLogger.fatal("Failed to get transformation from database", "%s @ %s" % (transID, self.transClient.serverURL)) def getServer(self): return self.serverURL def reset(self, transID=0): self.__init__(transID) self.transClient.setServer(self.serverURL) return S_OK() def setTargetSE(self, seList): return self.__setSE('TargetSE', seList) def setSourceSE(self, seList): return self.__setSE('SourceSE', seList) def setBody(self, body): """ check that the body is a string, or using the proper syntax for multiple operations :param body: transformation body, for example .. code :: python body = [ ( "ReplicateAndRegister", { "SourceSE":"FOO-SRM", "TargetSE":"BAR-SRM" }), ( "RemoveReplica", { "TargetSE":"FOO-SRM" } ), ] :type body: string or list of tuples (or lists) of string and dictionaries :raises TypeError: If the structure is not as expected :raises ValueError: If unknown attribute for the :class:`~DIRAC.RequestManagementSystem.Client.Operation.Operation` is used :returns: S_OK, S_ERROR """ self.item_called = "Body" if isinstance(body, six.string_types): return self.__setParam(body) if not isinstance(body, (list, tuple)): raise TypeError("Expected list or string, but %r is %s" % (body, type(body))) for tup in body: if not isinstance(tup, (tuple, list)): raise TypeError("Expected tuple or list, but %r is %s" % (tup, type(tup))) if len(tup) != 2: raise TypeError("Expected 2-tuple, but %r is length %d" % (tup, len(tup))) if not isinstance(tup[0], six.string_types): raise TypeError("Expected string, but first entry in tuple %r is %s" % (tup, type(tup[0]))) if not isinstance(tup[1], dict): raise TypeError("Expected dictionary, but second entry in tuple %r is %s" % (tup, type(tup[0]))) for par, val in tup[1].items(): if not isinstance(par, six.string_types): raise TypeError("Expected string, but key in dictionary %r is %s" % (par, type(par))) if par not in Operation.ATTRIBUTE_NAMES: raise ValueError("Unknown attribute for Operation: %s" % par) if not isinstance(val, six.string_types + six.integer_types + (float, list, tuple, dict)): raise TypeError("Cannot encode %r, in json" % (val)) return self.__setParam(json.dumps(body)) def setInputMetaQuery(self, query): """Set the input meta query. :param dict query: dictionary to use for input meta query """ self.inputMetaQuery = query return S_OK() def setOutputMetaQuery(self, query): """Set the output meta query. :param dict query: dictionary to use for output meta query """ self.outputMetaQuery = query return S_OK() def __setSE(self, seParam, seList): if isinstance(seList, six.string_types): try: seList = eval(seList) except Exception: seList = seList.split(',') elif isinstance(seList, (list, dict, tuple)): seList = list(seList) else: return S_ERROR("Bad argument type") res = self.__checkSEs(seList) if not res['OK']: return res self.item_called = seParam return self.__setParam(seList) def __getattr__(self, name): if name.find('get') == 0: item = name[3:] self.item_called = item return self.__getParam if name.find('set') == 0: item = name[3:] self.item_called = item return self.__setParam raise AttributeError(name) def __getParam(self): if self.item_called == 'Available': return S_OK(list(self.paramTypes)) if self.item_called == 'Parameters': return S_OK(self.paramValues) if self.item_called in self.paramValues: return S_OK(self.paramValues[self.item_called]) raise AttributeError("Unknown parameter for transformation: %s" % self.item_called) def __setParam(self, value): change = False if self.item_called in self.paramTypes: if self.paramValues[self.item_called] != value: if isinstance(value, self.paramTypes[self.item_called]): change = True else: raise TypeError("%s %s %s expected one of %s" % (self.item_called, value, type(value), self.paramTypes[self.item_called])) else: if self.item_called not in self.paramValues: change = True else: if self.paramValues[self.item_called] != value: change = True if not change: gLogger.verbose("No change of parameter %s required" % self.item_called) else: gLogger.verbose("Parameter %s to be changed" % self.item_called) transID = self.paramValues['TransformationID'] if self.exists and transID: res = self.transClient.setTransformationParameter(transID, self.item_called, value) if not res['OK']: return res self.paramValues[self.item_called] = value return S_OK() def getTransformation(self, printOutput=False): transID = self.paramValues['TransformationID'] if not transID: gLogger.fatal("No TransformationID known") return S_ERROR() res = self.transClient.getTransformation(transID, extraParams=True) if not res['OK']: if printOutput: self._prettyPrint(res) return res transParams = res['Value'] for paramName, paramValue in transParams.items(): setter = None setterName = "set%s" % paramName if hasattr(self, setterName) and callable(getattr(self, setterName)): setter = getattr(self, setterName) if not setterName: gLogger.error("Unable to invoke setter %s, it isn't a member function" % setterName) continue setter(paramValue) if printOutput: gLogger.info("No printing available yet") return S_OK(transParams) def getTransformationLogging(self, printOutput=False): transID = self.paramValues['TransformationID'] if not transID: gLogger.fatal("No TransformationID known") return S_ERROR() res = self.transClient.getTransformationLogging(transID) if not res['OK']: if printOutput: self._prettyPrint(res) return res loggingList = res['Value'] if printOutput: self._printFormattedDictList(loggingList, ['Message', 'MessageDate', 'AuthorDN'], 'MessageDate', 'MessageDate') return S_OK(loggingList) def extendTransformation(self, nTasks, printOutput=False): return self.__executeOperation('extendTransformation', nTasks, printOutput=printOutput) def cleanTransformation(self, printOutput=False): res = self.__executeOperation('cleanTransformation', printOutput=printOutput) if res['OK']: self.paramValues['Status'] = 'Cleaned' return res def deleteTransformation(self, printOutput=False): res = self.__executeOperation('deleteTransformation', printOutput=printOutput) if res['OK']: self.reset() return res def addFilesToTransformation(self, lfns, printOutput=False): return self.__executeOperation('addFilesToTransformation', lfns, printOutput=printOutput) def setFileStatusForTransformation(self, status, lfns, printOutput=False): return self.__executeOperation('setFileStatusForTransformation', status, lfns, printOutput=printOutput) def getTransformationTaskStats(self, printOutput=False): return self.__executeOperation('getTransformationTaskStats', printOutput=printOutput) def getTransformationStats(self, printOutput=False): return self.__executeOperation('getTransformationStats', printOutput=printOutput) def deleteTasks(self, taskMin, taskMax, printOutput=False): return self.__executeOperation('deleteTasks', taskMin, taskMax, printOutput=printOutput) def addTaskForTransformation(self, lfns=[], se='Unknown', printOutput=False): return self.__executeOperation('addTaskForTransformation', lfns, se, printOutput=printOutput) def setTaskStatus(self, taskID, status, printOutput=False): return self.__executeOperation('setTaskStatus', taskID, status, printOutput=printOutput) def __executeOperation(self, operation, *parms, **kwds): transID = self.paramValues['TransformationID'] if not transID: gLogger.fatal("No TransformationID known") return S_ERROR() printOutput = kwds.pop('printOutput') fcn = None if hasattr(self.transClient, operation) and callable(getattr(self.transClient, operation)): fcn = getattr(self.transClient, operation) if not fcn: return S_ERROR("Unable to invoke %s, it isn't a member funtion of TransformationClient") res = fcn(transID, *parms, **kwds) if printOutput: self._prettyPrint(res) return res def getTransformationFiles(self, fileStatus=[], lfns=[], outputFields=['FileID', 'LFN', 'Status', 'TaskID', 'TargetSE', 'UsedSE', 'ErrorCount', 'InsertedTime', 'LastUpdate'], orderBy='FileID', printOutput=False): condDict = {'TransformationID': self.paramValues['TransformationID']} if fileStatus: condDict['Status'] = fileStatus if lfns: condDict['LFN'] = lfns res = self.transClient.getTransformationFiles(condDict=condDict) if not res['OK']: if printOutput: self._prettyPrint(res) return res if printOutput: if not outputFields: gLogger.info("Available fields are: %s" % res['ParameterNames'].join(' ')) elif not res['Value']: gLogger.info("No tasks found for selection") else: self._printFormattedDictList(res['Value'], outputFields, 'FileID', orderBy) return res def getTransformationTasks(self, taskStatus=[], taskIDs=[], outputFields=['TransformationID', 'TaskID', 'ExternalStatus', 'ExternalID', 'TargetSE', 'CreationTime', 'LastUpdateTime'], orderBy='TaskID', printOutput=False): condDict = {'TransformationID': self.paramValues['TransformationID']} if taskStatus: condDict['ExternalStatus'] = taskStatus if taskIDs: condDict['TaskID'] = taskIDs res = self.transClient.getTransformationTasks(condDict=condDict) if not res['OK']: if printOutput: self._prettyPrint(res) return res if printOutput: if not outputFields: gLogger.info("Available fields are: %s" % res['ParameterNames'].join(' ')) elif not res['Value']: gLogger.info("No tasks found for selection") else: self._printFormattedDictList(res['Value'], outputFields, 'TaskID', orderBy) return res ############################################################################# def getTransformations(self, transID=[], transStatus=[], outputFields=['TransformationID', 'Status', 'AgentType', 'TransformationName', 'CreationDate'], orderBy='TransformationID', printOutput=False): condDict = {} if transID: condDict['TransformationID'] = transID if transStatus: condDict['Status'] = transStatus res = self.transClient.getTransformations(condDict=condDict) if not res['OK']: if printOutput: self._prettyPrint(res) return res if printOutput: if not outputFields: gLogger.info("Available fields are: %s" % res['ParameterNames'].join(' ')) elif not res['Value']: gLogger.info("No tasks found for selection") else: self._printFormattedDictList(res['Value'], outputFields, 'TransformationID', orderBy) return res ############################################################################# def getAuthorDNfromProxy(self): """ gets the AuthorDN and username of the transformation from the uploaded proxy """ username = "" author = "" res = getProxyInfo() if res['OK']: author = res['Value']['identity'] username = res['Value']['username'] else: gLogger.error("Unable to get uploaded proxy Info %s " % res['Message']) return S_ERROR(res['Message']) res = {'username': username, 'authorDN': author} return S_OK(res) ############################################################################# def getTransformationsByUser(self, authorDN="", userName="", transID=[], transStatus=[], outputFields=['TransformationID', 'Status', 'AgentType', 'TransformationName', 'CreationDate', 'AuthorDN'], orderBy='TransformationID', printOutput=False): condDict = {} if authorDN == "": res = self.getAuthorDNfromProxy() if not res['OK']: gLogger.error(res['Message']) return S_ERROR(res['Message']) else: foundUserName = res['Value']['username'] foundAuthor = res['Value']['authorDN'] # If the username whom created the uploaded proxy is different than the provided username report error and exit if not (userName == "" or userName == foundUserName): gLogger.error( "Couldn't resolve the authorDN for user '%s' from the uploaded proxy (proxy created by '%s')" % (userName, foundUserName)) return S_ERROR( "Couldn't resolve the authorDN for user '%s' from the uploaded proxy (proxy created by '%s')" % (userName, foundUserName)) userName = foundUserName authorDN = foundAuthor gLogger.info( "Will list transformations created by user '%s' with status '%s'" % (userName, ', '.join(transStatus))) else: gLogger.info("Will list transformations created by '%s' with status '%s'" % (authorDN, ', '.join(transStatus))) condDict['AuthorDN'] = authorDN if transID: condDict['TransformationID'] = transID if transStatus: condDict['Status'] = transStatus res = self.transClient.getTransformations(condDict=condDict) if not res['OK']: if printOutput: self._prettyPrint(res) return res if printOutput: if not outputFields: gLogger.info("Available fields are: %s" % res['ParameterNames'].join(' ')) elif not res['Value']: gLogger.info("No tasks found for selection") else: self._printFormattedDictList(res['Value'], outputFields, 'TransformationID', orderBy) return res ############################################################################# def getSummaryTransformations(self, transID=[]): """Show the summary for a list of Transformations Fields starting with 'F' ('J') refers to files (jobs). Proc. stand for processed. """ condDict = {'TransformationID': transID} orderby = [] start = 0 maxitems = len(transID) paramShowNames = ['TransformationID', 'Type', 'Status', 'Files_Total', 'Files_PercentProcessed', 'Files_Processed', 'Files_Unused', 'Jobs_TotalCreated', 'Jobs_Waiting', 'Jobs_Running', 'Jobs_Done', 'Jobs_Failed', 'Jobs_Stalled'] # Below, the header used for each field in the printing: short to fit in one line paramShowNamesShort = ['TransID', 'Type', 'Status', 'F_Total', 'F_Proc.(%)', 'F_Proc.', 'F_Unused', 'J_Created', 'J_Wait', 'J_Run', 'J_Done', 'J_Fail', 'J_Stalled'] dictList = [] result = self.transClient.getTransformationSummaryWeb(condDict, orderby, start, maxitems) if not result['OK']: self._prettyPrint(result) return result if result['Value']['TotalRecords'] > 0: try: paramNames = result['Value']['ParameterNames'] for paramValues in result['Value']['Records']: paramShowValues = map(lambda pname: paramValues[paramNames.index(pname)], paramShowNames) showDict = dict(zip(paramShowNamesShort, paramShowValues)) dictList.append(showDict) except Exception as x: print('Exception %s ' % str(x)) if not len(dictList) > 0: gLogger.error('No found transformations satisfying input condition') return S_ERROR('No found transformations satisfying input condition') else: print(self._printFormattedDictList(dictList, paramShowNamesShort, paramShowNamesShort[0], paramShowNamesShort[0])) return S_OK(dictList) ############################################################################# def addTransformation(self, addFiles=True, printOutput=False): """Add transformation to the transformation system. Sets all parameters currently assigned to the transformation. :param bool addFiles: if True, immediately perform input data query :param bool printOutput: if True, print information about transformation """ res = self._checkCreation() if not res['OK']: return self._errorReport(res, 'Failed transformation sanity check') if printOutput: gLogger.info("Will attempt to create transformation with the following parameters") self._prettyPrint(self.paramValues) res = self.transClient.addTransformation(self.paramValues['TransformationName'], self.paramValues['Description'], self.paramValues['LongDescription'], self.paramValues['Type'], self.paramValues['Plugin'], self.paramValues['AgentType'], self.paramValues['FileMask'], transformationGroup=self.paramValues['TransformationGroup'], groupSize=self.paramValues['GroupSize'], inheritedFrom=self.paramValues['InheritedFrom'], body=self.paramValues['Body'], maxTasks=self.paramValues['MaxNumberOfTasks'], eventsPerTask=self.paramValues['EventsPerTask'], addFiles=addFiles, inputMetaQuery=self.inputMetaQuery, outputMetaQuery=self.outputMetaQuery, ) if not res['OK']: if printOutput: self._prettyPrint(res) return res transID = res['Value'] self.exists = True self.setTransformationID(transID) gLogger.notice("Created transformation %d" % transID) for paramName, paramValue in self.paramValues.items(): if paramName not in self.paramTypes: res = self.transClient.setTransformationParameter(transID, paramName, paramValue) if not res['OK']: gLogger.error("Failed to add parameter", "%s %s" % (paramName, res['Message'])) gLogger.notice("To add this parameter later please execute the following.") gLogger.notice("oTransformation = Transformation(%d)" % transID) gLogger.notice("oTransformation.set%s(...)" % paramName) return S_OK(transID) def _checkCreation(self): """ Few checks """ if self.paramValues['TransformationID']: gLogger.info("You are currently working with an active transformation definition.") gLogger.info("If you wish to create a new transformation reset the TransformationID.") gLogger.info("oTransformation.reset()") return S_ERROR() requiredParameters = ['TransformationName', 'Description', 'LongDescription', 'Type'] for parameter in requiredParameters: if not self.paramValues[parameter]: gLogger.info("%s is not defined for this transformation. This is required..." % parameter) self.paramValues[parameter] = six.moves.input("Please enter the value of " + parameter + " ") plugin = self.paramValues['Plugin'] if plugin: if plugin not in self.supportedPlugins: gLogger.info("The selected Plugin (%s) is not known to the transformation agent." % plugin) res = self.__promptForParameter('Plugin', choices=self.supportedPlugins, default='Standard') if not res['OK']: return res self.paramValues['Plugin'] = res['Value'] plugin = self.paramValues['Plugin'] return S_OK() def _checkBySizePlugin(self): return self._checkStandardPlugin() def _checkBySharePlugin(self): return self._checkStandardPlugin() def _checkStandardPlugin(self): groupSize = self.paramValues['GroupSize'] if groupSize <= 0: gLogger.info("The GroupSize was found to be less than zero. It has been set to 1.") res = self.setGroupSize(1) if not res['OK']: return res return S_OK() def _checkBroadcastPlugin(self): gLogger.info("The Broadcast plugin requires the following parameters be set: %s" % (', '.join(['SourceSE', 'TargetSE']))) requiredParams = ['SourceSE', 'TargetSE'] for requiredParam in requiredParams: if not self.paramValues.get(requiredParam): paramValue = six.moves.input("Please enter " + requiredParam + " ") setter = None setterName = "set%s" % requiredParam if hasattr(self, setterName) and callable(getattr(self, setterName)): setter = getattr(self, setterName) if not setter: return S_ERROR("Unable to invoke %s, this function hasn't been implemented." % setterName) ses = paramValue.replace(',', ' ').split() res = setter(ses) if not res['OK']: return res return S_OK() def __checkSEs(self, seList): res = gConfig.getSections('/Resources/StorageElements') if not res['OK']: return self._errorReport(res, 'Failed to get possible StorageElements') missing = set(seList) - set(res['Value']) if missing: for se in missing: gLogger.error("StorageElement %s is not known" % se) return S_ERROR("%d StorageElements not known" % len(missing)) return S_OK() def __promptForParameter(self, parameter, choices=[], default='', insert=True): res = promptUser("Please enter %s" % parameter, choices=choices, default=default) if not res['OK']: return self._errorReport(res) gLogger.notice("%s will be set to '%s'" % (parameter, res['Value'])) paramValue = res['Value'] if insert: setter = None setterName = "set%s" % parameter if hasattr(self, setterName) and callable(getattr(self, setterName)): setter = getattr(self, setterName) if not setter: return S_ERROR("Unable to invoke %s, it isn't a member function of Transformation!") res = setter(paramValue) if not res['OK']: return res return S_OK(paramValue)
yujikato/DIRAC
src/DIRAC/TransformationSystem/Client/Transformation.py
Python
gpl-3.0
26,973
[ "DIRAC" ]
e585569f63b6dc723f9b1c3fa2e7722ba29f015a9d812b3ed3221dd94172d75e
import openvoronoi as ovd import ovdvtk import time import vtk import datetime import math import random import os import sys import pickle import gzip import ovdgenerators as gens def drawLine(myscreen, pt1, pt2, lineColor): myscreen.addActor(ovdvtk.Line(p1=(pt1.x, pt1.y, 0), p2=(pt2.x, pt2.y, 0), color=lineColor)) def drawArc(myscreen, pt1, pt2, r, arcColor): myscreen.addActor(ovdvtk.Line(p1=(pt1.x, pt1.y, 0), p2=(pt2.x, pt2.y, 0), color=arcColor)) def drawOffsets(myscreen, ofs): # draw loops nloop = 0 lineColor = ovdvtk.green arcColor = ovdvtk.grass for lop in ofs: n = 0 N = len(lop) first_point = [] previous = [] for p in lop: # p[0] is the Point # p[1] is -1 for lines, and r for arcs if n == 0: # don't draw anything on the first iteration previous = p[0] # first_point = p[0] else: r = p[1] p = p[0] if r == -1: drawLine(myscreen, previous, p, lineColor) else: drawArc(myscreen, previous, p, r, arcColor) # myscreen.addActor( ovdvtk.Line(p1=(previous.x,previous.y,0),p2=(p.x,p.y,0),color=loopColor) ) previous = p n = n + 1 print "rendered loop ", nloop, " with ", len(lop), " points" nloop = nloop + 1 if __name__ == "__main__": # w=2500 # h=1500 # w=1920 # h=1080 w = 1024 h = 1024 myscreen = ovdvtk.VTKScreen(width=w, height=h) ovdvtk.drawOCLtext(myscreen, rev_text=ovd.version()) scale = 1 myscreen.render() random.seed(42) far = 1 camPos = far zmult = 3 # camPos/float(1000) myscreen.camera.SetPosition(0, -camPos / float(1000), zmult * camPos) myscreen.camera.SetClippingRange(-(zmult + 1) * camPos, (zmult + 1) * camPos) myscreen.camera.SetFocalPoint(0.0, 0, 0) vd = ovd.VoronoiDiagram(far, 120) print ovd.version() # for vtk visualization vod = ovdvtk.VD(myscreen, vd, float(scale), textscale=0.01, vertexradius=0.003) vod.drawFarCircle() vod.textScale = 0.02 vod.vertexRadius = 0.0031 vod.drawVertices = 0 vod.drawVertexIndex = 1 vod.drawGenerators = 1 vod.offsetEdges = 0 vd.setEdgeOffset(0.05) p1 = ovd.Point(-0.1, -0.2) p2 = ovd.Point(0.2, 0.1) p3 = ovd.Point(0.4, 0.2) p4 = ovd.Point(0.6, 0.6) p5 = ovd.Point(-0.6, 0.3) pts = [p1, p2, p3, p4, p5] # t_after = time.time() # print ".done in {0:.3f} s.".format( t_after-t_before ) times = [] id_list = [] m = 0 t_before = time.time() for p in pts: id_list.append(vd.addVertexSite(p)) # print m," added vertex", seg_id[0] m = m + 1 t_after = time.time() times.append(t_after - t_before) # exit() # print " ",2*Nmax," point-sites sites took {0:.3f}".format(times[0])," seconds, {0:.2f}".format( 1e6*float( times[0] )/(float(2*Nmax)*float(math.log10(2*Nmax))) ) ,"us/n*log(n)" print "all point sites inserted. " print "VD check: ", vd.check() t_before = time.time() vd.addLineSite(id_list[0], id_list[1]) vd.addLineSite(id_list[1], id_list[2]) vd.addLineSite(id_list[2], id_list[3]) vd.addLineSite(id_list[3], id_list[4]) vd.addLineSite(id_list[4], id_list[0]) vd.check() t_after = time.time() line_time = t_after - t_before if line_time < 1e-3: line_time = 1 times.append(line_time) # of = ovd.Offset( vd.getGraph() ) # pass the created graph to the Offset class # of.str() # ofs = of.offset(0.123) # print ofs # drawOffsets(myscreen, ofs) pi = ovd.PolygonInterior(True) vd.filter_graph(pi) of = ovd.Offset(vd.getGraph()) # pass the created graph to the Offset class ofs = of.offset(0.123) # print ofs ovdvtk.drawOffsets(myscreen, ofs) # of.offset(0.125) vod.setVDText2(times) vod.setAll() print "PYTHON All DONE." myscreen.render() myscreen.iren.Start()
aewallin/openvoronoi
python_examples/polygon_interior_1.py
Python
lgpl-2.1
4,111
[ "VTK" ]
3a7e5d2f3c83e05eca540256374f5c8bf8005ab8a5f1b9695b430d9ade8184ba
#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # # 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. """This example shows how to use validateOnly SOAP header. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. Tags: CampaignService.mutate Api: AdWordsOnly """ __author__ = ('api.kwinter@gmail.com (Kevin Winter)' 'Joseph DiLallo') import suds from googleads import adwords AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' def main(client, ad_group_id): # Initialize appropriate service with validate only flag enabled. client.validate_only = True ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') # Construct operations to add a text ad. operations = [{ 'operator': 'ADD', 'operand': { 'xsi_type': 'AdGroupAd', 'adGroupId': ad_group_id, 'ad': { 'xsi_type': 'TextAd', 'finalUrls': { 'urls': ['http://www.example.com'] }, 'displayUrl': 'example.com', 'description1': 'Visit the Red Planet in style.', 'description2': 'Low-gravity fun for everyone!', 'headline': 'Luxury Cruise to Mars' } } }] ad_group_ad_service.mutate(operations) # No error means the request is valid. # Now let's check an invalid ad using a very long line to trigger an error. operations = [{ 'operator': 'ADD', 'operand': { 'xsi_type': 'AdGroupAd', 'adGroupId': ad_group_id, 'ad': { 'xsi_type': 'TextAd', 'url': 'http://www.example.com', 'displayUrl': 'example.com', 'description1': 'Visit the Red Planet in style.', 'description2': 'Low-gravity fun for all astronauts in orbit', 'headline': 'Luxury Cruise to Mars' } } }] try: ad_group_ad_service.mutate(operations) except suds.WebFault, e: print 'Validation correctly failed with \'%s\'.' % str(e) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client, AD_GROUP_ID)
cctaylor/googleads-python-lib
examples/adwords/v201409/campaign_management/validate_text_ad.py
Python
apache-2.0
2,880
[ "VisIt" ]
3af6968db43db869584309371087d8128cba6c1e1b7bb6a301057b8c3f608d45
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ Module for Latent Semantic Analysis (aka Latent Semantic Indexing) in Python. Implements fast truncated SVD (Singular Value Decomposition). The SVD decomposition can be updated with new observations at any time, for an online, incremental, memory-efficient training. This module actually contains several algorithms for decomposition of large corpora, a combination of which effectively and transparently allows building LSI models for: * corpora much larger than RAM: only constant memory is needed, independent of the corpus size * corpora that are streamed: documents are only accessed sequentially, no random access * corpora that cannot be even temporarily stored: each document can only be seen once and must be processed immediately (one-pass algorithm) * distributed computing for very large corpora, making use of a cluster of machines Wall-clock `performance on the English Wikipedia <http://radimrehurek.com/gensim/wiki.html>`_ (2G corpus positions, 3.2M documents, 100K features, 0.5G non-zero entries in the final TF-IDF matrix), requesting the top 400 LSI factors: ====================================================== ============ ================== algorithm serial distributed ====================================================== ============ ================== one-pass merge algorithm 5h14m 1h41m multi-pass stochastic algo (with 2 power iterations) 5h39m N/A [1]_ ====================================================== ============ ================== *serial* = Core 2 Duo MacBook Pro 2.53Ghz, 4GB RAM, libVec *distributed* = cluster of four logical nodes on three physical machines, each with dual core Xeon 2.0GHz, 4GB RAM, ATLAS .. [1] The stochastic algo could be distributed too, but most time is already spent reading/decompressing the input from disk in its 4 passes. The extra network traffic due to data distribution across cluster nodes would likely make it *slower*. """ import logging import sys import numpy import scipy.linalg import scipy.sparse from scipy.sparse import sparsetools from gensim import interfaces, matutils, utils from six import iterkeys from six.moves import xrange logger = logging.getLogger('gensim.models.lsimodel') # accuracy defaults for the multi-pass stochastic algo P2_EXTRA_DIMS = 100 # set to `None` for dynamic P2_EXTRA_DIMS=k P2_EXTRA_ITERS = 2 def clip_spectrum(s, k, discard=0.001): """ Given eigenvalues `s`, return how many factors should be kept to avoid storing spurious (tiny, numerically instable) values. This will ignore the tail of the spectrum with relative combined mass < min(`discard`, 1/k). The returned value is clipped against `k` (= never return more than `k`). """ # compute relative contribution of eigenvalues towards the energy spectrum rel_spectrum = numpy.abs(1.0 - numpy.cumsum(s / numpy.sum(s))) # ignore the last `discard` mass (or 1/k, whichever is smaller) of the spectrum small = 1 + len(numpy.where(rel_spectrum > min(discard, 1.0 / k))[0]) k = min(k, small) # clip against k logger.info("keeping %i factors (discarding %.3f%% of energy spectrum)", k, 100 * rel_spectrum[k - 1]) return k def asfarray(a, name=''): if not a.flags.f_contiguous: logger.debug("converting %s array %s to FORTRAN order", a.shape, name) a = numpy.asfortranarray(a) return a def ascarray(a, name=''): if not a.flags.contiguous: logger.debug("converting %s array %s to C order", a.shape, name) a = numpy.ascontiguousarray(a) return a class Projection(utils.SaveLoad): def __init__(self, m, k, docs=None, use_svdlibc=False, power_iters=P2_EXTRA_ITERS, extra_dims=P2_EXTRA_DIMS): """ Construct the (U, S) projection from a corpus `docs`. The projection can be later updated by merging it with another Projection via `self.merge()`. This is the class taking care of the 'core math'; interfacing with corpora, splitting large corpora into chunks and merging them etc. is done through the higher-level `LsiModel` class. """ self.m, self.k = m, k self.power_iters = power_iters self.extra_dims = extra_dims if docs is not None: # base case decomposition: given a job `docs`, compute its decomposition, # *in-core*. if not use_svdlibc: u, s = stochastic_svd( docs, k, chunksize=sys.maxsize, num_terms=m, power_iters=self.power_iters, extra_dims=self.extra_dims) else: try: import sparsesvd except ImportError: raise ImportError("`sparsesvd` module requested but not found; run `easy_install sparsesvd`") logger.info("computing sparse SVD of %s matrix", str(docs.shape)) if not scipy.sparse.issparse(docs): docs = matutils.corpus2csc(docs) ut, s, vt = sparsesvd.sparsesvd(docs, k + 30) # ask for extra factors, because for some reason SVDLIBC sometimes returns fewer factors than requested u = ut.T del ut, vt k = clip_spectrum(s**2, self.k) self.u = u[:, :k].copy() self.s = s[:k].copy() else: self.u, self.s = None, None def empty_like(self): return Projection(self.m, self.k, power_iters=self.power_iters, extra_dims=self.extra_dims) def merge(self, other, decay=1.0): """ Merge this Projection with another. The content of `other` is destroyed in the process, so pass this function a copy of `other` if you need it further. """ if other.u is None: # the other projection is empty => do nothing return if self.u is None: # we are empty => result of merge is the other projection, whatever it is self.u = other.u.copy() self.s = other.s.copy() return if self.m != other.m: raise ValueError("vector space mismatch: update is using %s features, expected %s" % (other.m, self.m)) logger.info("merging projections: %s + %s", str(self.u.shape), str(other.u.shape)) m, n1, n2 = self.u.shape[0], self.u.shape[1], other.u.shape[1] # TODO Maybe keep the bases as elementary reflectors, without # forming explicit matrices with ORGQR. # The only operation we ever need is basis^T*basis ond basis*component. # But how to do that in scipy? And is it fast(er)? # find component of u2 orthogonal to u1 logger.debug("constructing orthogonal component") self.u = asfarray(self.u, 'self.u') c = numpy.dot(self.u.T, other.u) self.u = ascarray(self.u, 'self.u') other.u -= numpy.dot(self.u, c) other.u = [other.u] # do some reference magic and call qr_destroy, to save RAM q, r = matutils.qr_destroy(other.u) # q, r = QR(component) assert not other.u # find the rotation that diagonalizes r k = numpy.bmat([[numpy.diag(decay * self.s), numpy.multiply(c, other.s)], [matutils.pad(numpy.array([]).reshape(0, 0), min(m, n2), n1), numpy.multiply(r, other.s)]]) logger.debug("computing SVD of %s dense matrix", str(k.shape)) try: # in numpy < 1.1.0, running SVD sometimes results in "LinAlgError: SVD did not converge'. # for these early versions of numpy, catch the error and try to compute # SVD again, but over k*k^T. # see http://www.mail-archive.com/numpy-discussion@scipy.org/msg07224.html and # bug ticket http://projects.scipy.org/numpy/ticket/706 # sdoering: replaced numpy's linalg.svd with scipy's linalg.svd: u_k, s_k, _ = scipy.linalg.svd(k, full_matrices=False) # TODO *ugly overkill*!! only need first self.k SVD factors... but there is no LAPACK wrapper for partial svd/eigendecomp in numpy :( //sdoering: maybe there is one in scipy? except scipy.linalg.LinAlgError: logger.error("SVD(A) failed; trying SVD(A * A^T)") u_k, s_k, _ = scipy.linalg.svd(numpy.dot(k, k.T), full_matrices=False) # if this fails too, give up with an exception s_k = numpy.sqrt(s_k) # go back from eigen values to singular values k = clip_spectrum(s_k**2, self.k) u1_k, u2_k, s_k = numpy.array(u_k[:n1, :k]), numpy.array(u_k[n1:, :k]), s_k[:k] # update & rotate current basis U = [U, U']*[U1_k, U2_k] logger.debug("updating orthonormal basis U") self.s = s_k self.u = ascarray(self.u, 'self.u') self.u = numpy.dot(self.u, u1_k) q = ascarray(q, 'q') q = numpy.dot(q, u2_k) self.u += q # make each column of U start with a non-negative number (to force canonical decomposition) if self.u.shape[0] > 0: for i in xrange(self.u.shape[1]): if self.u[0, i] < 0.0: self.u[:, i] *= -1.0 # diff = numpy.dot(self.u.T, self.u) - numpy.eye(self.u.shape[1]) # logger.info('orth error after=%f' % numpy.sum(diff * diff)) #endclass Projection class LsiModel(interfaces.TransformationABC): """ Objects of this class allow building and maintaining a model for Latent Semantic Indexing (also known as Latent Semantic Analysis). The main methods are: 1. constructor, which initializes the projection into latent topics space, 2. the ``[]`` method, which returns representation of any input document in the latent space, 3. `add_documents()` for incrementally updating the model with new documents. The left singular vectors are stored in `lsi.projection.u`, singular values in `lsi.projection.s`. Right singular vectors can be reconstructed from the output of `lsi[training_corpus]`, if needed. See also FAQ [2]_. Model persistency is achieved via its load/save methods. .. [2] https://github.com/piskvorky/gensim/wiki/Recipes-&-FAQ#q4-how-do-you-output-the-u-s-vt-matrices-of-lsi """ def __init__(self, corpus=None, num_topics=200, id2word=None, chunksize=20000, decay=1.0, distributed=False, onepass=True, power_iters=P2_EXTRA_ITERS, extra_samples=P2_EXTRA_DIMS): """ `num_topics` is the number of requested factors (latent dimensions). After the model has been trained, you can estimate topics for an arbitrary, unseen document, using the ``topics = self[document]`` dictionary notation. You can also add new training documents, with ``self.add_documents``, so that training can be stopped and resumed at any time, and the LSI transformation is available at any point. If you specify a `corpus`, it will be used to train the model. See the method `add_documents` for a description of the `chunksize` and `decay` parameters. Turn `onepass` off to force a multi-pass stochastic algorithm. `power_iters` and `extra_samples` affect the accuracy of the stochastic multi-pass algorithm, which is used either internally (`onepass=True`) or as the front-end algorithm (`onepass=False`). Increasing the number of power iterations improves accuracy, but lowers performance. See [3]_ for some hard numbers. Turn on `distributed` to enable distributed computing. Example: >>> lsi = LsiModel(corpus, num_topics=10) >>> print(lsi[doc_tfidf]) # project some document into LSI space >>> lsi.add_documents(corpus2) # update LSI on additional documents >>> print(lsi[doc_tfidf]) .. [3] http://nlp.fi.muni.cz/~xrehurek/nips/rehurek_nips.pdf """ self.id2word = id2word self.num_topics = int(num_topics) self.chunksize = int(chunksize) self.decay = float(decay) if distributed: if not onepass: logger.warning("forcing the one-pass algorithm for distributed LSA") onepass = True self.onepass = onepass self.extra_samples, self.power_iters = extra_samples, power_iters if corpus is None and self.id2word is None: raise ValueError('at least one of corpus/id2word must be specified, to establish input space dimensionality') if self.id2word is None: logger.warning("no word id mapping provided; initializing from corpus, assuming identity") self.id2word = utils.dict_from_corpus(corpus) self.num_terms = len(self.id2word) else: self.num_terms = 1 + max([-1] + self.id2word.keys()) self.docs_processed = 0 self.projection = Projection(self.num_terms, self.num_topics, power_iters=self.power_iters, extra_dims=self.extra_samples) self.numworkers = 1 if not distributed: logger.info("using serial LSI version on this node") self.dispatcher = None else: if not onepass: raise NotImplementedError("distributed stochastic LSA not implemented yet; " "run either distributed one-pass, or serial randomized.") try: import Pyro4 dispatcher = Pyro4.Proxy('PYRONAME:gensim.lsi_dispatcher') logger.debug("looking for dispatcher at %s", str(dispatcher._pyroUri)) dispatcher.initialize(id2word=self.id2word, num_topics=num_topics, chunksize=chunksize, decay=decay, power_iters=self.power_iters, extra_samples=self.extra_samples, distributed=False, onepass=onepass) self.dispatcher = dispatcher self.numworkers = len(dispatcher.getworkers()) logger.info("using distributed version with %i workers", self.numworkers) except Exception as err: # distributed version was specifically requested, so this is an error state logger.error("failed to initialize distributed LSI (%s)", err) raise RuntimeError("failed to initialize distributed LSI (%s)" % err) if corpus is not None: self.add_documents(corpus) def add_documents(self, corpus, chunksize=None, decay=None): """ Update singular value decomposition to take into account a new corpus of documents. Training proceeds in chunks of `chunksize` documents at a time. The size of `chunksize` is a tradeoff between increased speed (bigger `chunksize`) vs. lower memory footprint (smaller `chunksize`). If the distributed mode is on, each chunk is sent to a different worker/computer. Setting `decay` < 1.0 causes re-orientation towards new data trends in the input document stream, by giving less emphasis to old observations. This allows LSA to gradually "forget" old observations (documents) and give more preference to new ones. """ logger.info("updating model with new documents") # get computation parameters; if not specified, use the ones from constructor if chunksize is None: chunksize = self.chunksize if decay is None: decay = self.decay if not scipy.sparse.issparse(corpus): if not self.onepass: # we are allowed multiple passes over the input => use a faster, randomized two-pass algo update = Projection(self.num_terms, self.num_topics, None) update.u, update.s = stochastic_svd( corpus, self.num_topics, num_terms=self.num_terms, chunksize=chunksize, extra_dims=self.extra_samples, power_iters=self.power_iters) self.projection.merge(update, decay=decay) else: # the one-pass algo doc_no = 0 if self.dispatcher: logger.info('initializing %s workers', self.numworkers) self.dispatcher.reset() for chunk_no, chunk in enumerate(utils.grouper(corpus, chunksize)): logger.info("preparing a new chunk of documents") nnz = sum(len(doc) for doc in chunk) # construct the job as a sparse matrix, to minimize memory overhead # definitely avoid materializing it as a dense matrix! logger.debug("converting corpus to csc format") job = matutils.corpus2csc(chunk, num_docs=len(chunk), num_terms=self.num_terms, num_nnz=nnz) del chunk doc_no += job.shape[1] if self.dispatcher: # distributed version: add this job to the job queue, so workers can work on it logger.debug("creating job #%i", chunk_no) self.dispatcher.putjob(job) # put job into queue; this will eventually block, because the queue has a small finite size del job logger.info("dispatched documents up to #%s", doc_no) else: # serial version, there is only one "worker" (myself) => process the job directly update = Projection(self.num_terms, self.num_topics, job, extra_dims=self.extra_samples, power_iters=self.power_iters) del job self.projection.merge(update, decay=decay) del update logger.info("processed documents up to #%s", doc_no) self.print_topics(5) # wait for all workers to finish (distributed version only) if self.dispatcher: logger.info("reached the end of input; now waiting for all remaining jobs to finish") self.projection = self.dispatcher.getstate() # logger.info("top topics after adding %i documents" % doc_no) # self.print_debug(10) else: assert not self.dispatcher, "must be in serial mode to receive jobs" assert self.onepass, "distributed two-pass algo not supported yet" update = Projection(self.num_terms, self.num_topics, corpus.tocsc(), extra_dims=self.extra_samples, power_iters=self.power_iters) self.projection.merge(update, decay=decay) logger.info("processed sparse job of %i documents", corpus.shape[1]) def __str__(self): return "LsiModel(num_terms=%s, num_topics=%s, decay=%s, chunksize=%s)" % ( self.num_terms, self.num_topics, self.decay, self.chunksize) def __getitem__(self, bow, scaled=False, chunksize=512): """ Return latent representation, as a list of (topic_id, topic_value) 2-tuples. This is done by folding input document into the latent topic space. If `scaled` is set, scale topics by the inverse of singular values (default: no scaling). """ assert self.projection.u is not None, "decomposition not initialized yet" # if the input vector is in fact a corpus, return a transformed corpus as a result is_corpus, bow = utils.is_corpus(bow) if is_corpus and chunksize: # by default, transform `chunksize` documents at once, when called as `lsi[corpus]`. # this chunking is completely transparent to the user, but it speeds # up internal computations (one mat * mat multiplication, instead of # `chunksize` smaller mat * vec multiplications). return self._apply(bow, chunksize=chunksize) if not is_corpus: bow = [bow] # convert input to scipy.sparse CSC, then do "sparse * dense = dense" multiplication vec = matutils.corpus2csc(bow, num_terms=self.num_terms, dtype=self.projection.u.dtype) topic_dist = (vec.T * self.projection.u[:, :self.num_topics]).T # (x^T * u).T = u^-1 * x # # convert input to dense, then do dense * dense multiplication # # ± same performance as above (BLAS dense * dense is better optimized than scipy.sparse), but consumes more memory # vec = matutils.corpus2dense(bow, num_terms=self.num_terms, num_docs=len(bow)) # topic_dist = numpy.dot(self.projection.u[:, :self.num_topics].T, vec) # # use numpy's advanced indexing to simulate sparse * dense # # ± same speed again # u = self.projection.u[:, :self.num_topics] # topic_dist = numpy.empty((u.shape[1], len(bow)), dtype=u.dtype) # for vecno, vec in enumerate(bow): # indices, data = zip(*vec) if vec else ([], []) # topic_dist[:, vecno] = numpy.dot(u.take(indices, axis=0).T, numpy.array(data, dtype=u.dtype)) if not is_corpus: # convert back from matrix into a 1d vec topic_dist = topic_dist.reshape(-1) if scaled: topic_dist = (1.0 / self.projection.s[:self.num_topics]) * topic_dist # s^-1 * u^-1 * x # convert a numpy array to gensim sparse vector = tuples of (feature_id, feature_weight), # with no zero weights. if not is_corpus: # lsi[single_document] result = matutils.full2sparse(topic_dist) else: # lsi[chunk of documents] result = matutils.Dense2Corpus(topic_dist) return result def show_topic(self, topicno, topn=10): """ Return a specified topic (=left singular vector), 0 <= `topicno` < `self.num_topics`, as a string. Return only the `topn` words which contribute the most to the direction of the topic (both negative and positive). >>> lsimodel.show_topic(10, topn=5) [(-0.340, "category"), (0.298, "$M$"), (0.183, "algebra"), (-0.174, "functor"), (-0.168, "operator")] """ # size of the projection matrix can actually be smaller than `self.num_topics`, # if there were not enough factors (real rank of input matrix smaller than # `self.num_topics`). in that case, return an empty string if topicno >= len(self.projection.u.T): return '' c = numpy.asarray(self.projection.u.T[topicno, :]).flatten() norm = numpy.sqrt(numpy.sum(numpy.dot(c, c))) most = matutils.argsort(numpy.abs(c), topn, reverse=True) return [(1.0 * c[val] / norm, self.id2word[val]) for val in most] def print_topic(self, topicno, topn=10): """ Return a single topic as a formatted string. See `show_topic()` for parameters. >>> lsimodel.print_topic(10, topn=5) '-0.340 * "category" + 0.298 * "$M$" + 0.183 * "algebra" + -0.174 * "functor" + -0.168 * "operator"' """ return ' + '.join(['%.3f*"%s"' % v for v in self.show_topic(topicno, topn)]) def show_topics(self, num_topics=-1, num_words=10, log=False, formatted=True): """ Return `num_topics` most significant topics (return all by default). For each topic, show `num_words` most significant words (10 words by default). The topics are returned as a list -- a list of strings if `formatted` is True, or a list of (weight, word) 2-tuples if False. If `log` is True, also output this result to log. """ shown = [] if num_topics < 0: num_topics = self.num_topics for i in xrange(min(num_topics, self.num_topics)): if i < len(self.projection.s): if formatted: topic = self.print_topic(i, topn=num_words) else: topic = self.show_topic(i, topn=num_words) shown.append(topic) if log: logger.info("topic #%i(%.3f): %s", i, self.projection.s[i], topic) return shown def print_topics(self, num_topics=5, num_words=10): """Alias for `show_topics()` which prints the top 5 topics to log.""" return self.show_topics(num_topics=num_topics, num_words=num_words, log=True) def print_debug(self, num_topics=5, num_words=10): """ Print (to log) the most salient words of the first `num_topics` topics. Unlike `print_topics()`, this looks for words that are significant for a particular topic *and* not for others. This *should* result in a more human-interpretable description of topics. """ # only wrap the module-level fnc print_debug( self.id2word, self.projection.u, self.projection.s, range(min(num_topics, len(self.projection.u.T))), num_words=num_words ) def save(self, fname, *args, **kwargs): """ Save the model to file. Large internal arrays may be stored into separate files, with `fname` as prefix. Note: do not save as a compressed file if you intend to load the file back with `mmap`. """ if self.projection is not None: self.projection.save(utils.smart_extension(fname, '.projection'), *args, **kwargs) super(LsiModel, self).save(fname, *args, ignore=['projection', 'dispatcher'], **kwargs) @classmethod def load(cls, fname, *args, **kwargs): """ Load a previously saved object from file (also see `save`). Large arrays can be memmap'ed back as read-only (shared memory) by setting `mmap='r'`: >>> LsiModel.load(fname, mmap='r') """ kwargs['mmap'] = kwargs.get('mmap', None) result = super(LsiModel, cls).load(fname, *args, **kwargs) projection_fname = utils.smart_extension(fname, '.projection') try: result.projection = super(LsiModel, cls).load(projection_fname, *args, **kwargs) except Exception as e: logging.warning("failed to load projection from %s: %s" % (projection_fname, e)) return result #endclass LsiModel def print_debug(id2token, u, s, topics, num_words=10, num_neg=None): if num_neg is None: # by default, print half as many salient negative words as positive num_neg = num_words / 2 logger.info('computing word-topic salience for %i topics', len(topics)) topics, result = set(topics), {} # TODO speed up by block computation for uvecno, uvec in enumerate(u): uvec = numpy.abs(numpy.asarray(uvec).flatten()) udiff = uvec / numpy.sqrt(numpy.sum(numpy.dot(uvec, uvec))) for topic in topics: result.setdefault(topic, []).append((udiff[topic], uvecno)) logger.debug("printing %i+%i salient words", num_words, num_neg) for topic in sorted(iterkeys(result)): weights = sorted(result[topic], key=lambda x: -abs(x[0])) _, most = weights[0] if u[most, topic] < 0.0: # the most significant word has a negative sign => flip sign of u[most] normalize = -1.0 else: normalize = 1.0 # order features according to salience; ignore near-zero entries in u pos, neg = [], [] for weight, uvecno in weights: if normalize * u[uvecno, topic] > 0.0001: pos.append('%s(%.3f)' % (id2token[uvecno], u[uvecno, topic])) if len(pos) >= num_words: break for weight, uvecno in weights: if normalize * u[uvecno, topic] < -0.0001: neg.append('%s(%.3f)' % (id2token[uvecno], u[uvecno, topic])) if len(neg) >= num_neg: break logger.info('topic #%s(%.3f): %s, ..., %s', topic, s[topic], ', '.join(pos), ', '.join(neg)) def stochastic_svd(corpus, rank, num_terms, chunksize=20000, extra_dims=None, power_iters=0, dtype=numpy.float64, eps=1e-6): """ Run truncated Singular Value Decomposition (SVD) on a sparse input. Return (U, S): the left singular vectors and the singular values of the input data stream `corpus` [4]_. The corpus may be larger than RAM (iterator of vectors). This may return less than the requested number of top `rank` factors, in case the input itself is of lower rank. The `extra_dims` (oversampling) and especially `power_iters` (power iterations) parameters affect accuracy of the decomposition. This algorithm uses `2+power_iters` passes over the input data. In case you can only afford a single pass, set `onepass=True` in :class:`LsiModel` and avoid using this function directly. The decomposition algorithm is based on **Halko, Martinsson, Tropp. Finding structure with randomness, 2009.** .. [4] If `corpus` is a scipy.sparse matrix instead, it is assumed the whole corpus fits into core memory and a different (more efficient) code path is chosen. """ rank = int(rank) if extra_dims is None: samples = max(10, 2 * rank) # use more samples than requested factors, to improve accuracy else: samples = rank + int(extra_dims) logger.info("using %i extra samples and %i power iterations", samples - rank, power_iters) num_terms = int(num_terms) # first phase: construct the orthonormal action matrix Q = orth(Y) = orth((A * A.T)^q * A * O) # build Y in blocks of `chunksize` documents (much faster than going one-by-one # and more memory friendly than processing all documents at once) y = numpy.zeros(dtype=dtype, shape=(num_terms, samples)) logger.info("1st phase: constructing %s action matrix", str(y.shape)) if scipy.sparse.issparse(corpus): m, n = corpus.shape assert num_terms == m, "mismatch in number of features: %i in sparse matrix vs. %i parameter" % (m, num_terms) o = numpy.random.normal(0.0, 1.0, (n, samples)).astype(y.dtype) # draw a random gaussian matrix sparsetools.csc_matvecs(m, n, samples, corpus.indptr, corpus.indices, corpus.data, o.ravel(), y.ravel()) # y = corpus * o del o # unlike numpy, scipy.sparse `astype()` copies everything, even if there is no change to dtype! # so check for equal dtype explicitly, to avoid the extra memory footprint if possible if y.dtype != dtype: y = y.astype(dtype) logger.info("orthonormalizing %s action matrix", str(y.shape)) y = [y] q, _ = matutils.qr_destroy(y) # orthonormalize the range logger.debug("running %i power iterations", power_iters) for power_iter in xrange(power_iters): q = corpus.T * q q = [corpus * q] q, _ = matutils.qr_destroy(q) # orthonormalize the range after each power iteration step else: num_docs = 0 for chunk_no, chunk in enumerate(utils.grouper(corpus, chunksize)): logger.info('PROGRESS: at document #%i', (chunk_no * chunksize)) # construct the chunk as a sparse matrix, to minimize memory overhead # definitely avoid materializing it as a dense (num_terms x chunksize) matrix! s = sum(len(doc) for doc in chunk) chunk = matutils.corpus2csc(chunk, num_terms=num_terms, dtype=dtype) # documents = columns of sparse CSC m, n = chunk.shape assert m == num_terms assert n <= chunksize # the very last chunk of A is allowed to be smaller in size num_docs += n logger.debug("multiplying chunk * gauss") o = numpy.random.normal(0.0, 1.0, (n, samples)).astype(dtype) # draw a random gaussian matrix sparsetools.csc_matvecs(m, n, samples, chunk.indptr, chunk.indices, # y = y + chunk * o chunk.data, o.ravel(), y.ravel()) del chunk, o y = [y] q, _ = matutils.qr_destroy(y) # orthonormalize the range for power_iter in xrange(power_iters): logger.info("running power iteration #%i", power_iter + 1) yold = q.copy() q[:] = 0.0 for chunk_no, chunk in enumerate(utils.grouper(corpus, chunksize)): logger.info('PROGRESS: at document #%i/%i', chunk_no * chunksize, num_docs) chunk = matutils.corpus2csc(chunk, num_terms=num_terms, dtype=dtype) # documents = columns of sparse CSC tmp = chunk.T * yold tmp = chunk * tmp del chunk q += tmp del yold q = [q] q, _ = matutils.qr_destroy(q) # orthonormalize the range qt = q[:, :samples].T.copy() del q if scipy.sparse.issparse(corpus): b = qt * corpus logger.info("2nd phase: running dense svd on %s matrix" % str(b.shape)) u, s, vt = scipy.linalg.svd(b, full_matrices=False) del b, vt else: # second phase: construct the covariance matrix X = B * B.T, where B = Q.T * A # again, construct X incrementally, in chunks of `chunksize` documents from the streaming # input corpus A, to avoid using O(number of documents) memory x = numpy.zeros(shape=(qt.shape[0], qt.shape[0]), dtype=numpy.float64) logger.info("2nd phase: constructing %s covariance matrix", str(x.shape)) for chunk_no, chunk in enumerate(utils.grouper(corpus, chunksize)): logger.info('PROGRESS: at document #%i/%i', chunk_no * chunksize, num_docs) chunk = matutils.corpus2csc(chunk, num_terms=num_terms, dtype=qt.dtype) b = qt * chunk # dense * sparse matrix multiply del chunk x += numpy.dot(b, b.T) # TODO should call the BLAS routine SYRK, but there is no SYRK wrapper in scipy :( del b # now we're ready to compute decomposition of the small matrix X logger.info("running dense decomposition on %s covariance matrix", str(x.shape)) u, s, vt = scipy.linalg.svd(x) # could use linalg.eigh, but who cares... and svd returns the factors already sorted :) s = numpy.sqrt(s) # sqrt to go back from singular values of X to singular values of B = singular values of the corpus q = qt.T.copy() del qt logger.info("computing the final decomposition") keep = clip_spectrum(s**2, rank, discard=eps) u = u[:, :keep].copy() s = s[:keep] u = numpy.dot(q, u) return u.astype(dtype), s.astype(dtype)
cngo-github/gensim
gensim/models/lsimodel.py
Python
gpl-3.0
34,984
[ "Gaussian" ]
760f27aba77525012871bceb723007b08fd1f2d2f64104367a1ea0c57b50ac30
# $Id$ # # Copyright (C) 2001-2008 Greg Landrum and Rational Discovery LLC # All Rights Reserved # """ Automatic search for quantization bounds This uses the expected informational gain to determine where quantization bounds should lie. **Notes**: - bounds are less than, so if the bounds are [1.,2.], [0.9,1.,1.1,2.,2.2] -> [0,1,1,2,2] """ from __future__ import print_function import numpy from rdkit.ML.InfoTheory import entropy from rdkit.six.moves import zip, map, range try: from rdkit.ML.Data import cQuantize except ImportError: hascQuantize = 0 else: hascQuantize = 1 _float_tol = 1e-8 def feq(v1, v2, tol=_float_tol): """ floating point equality with a tolerance factor **Arguments** - v1: a float - v2: a float - tol: the tolerance for comparison **Returns** 0 or 1 """ return abs(v1 - v2) < tol def FindVarQuantBound(vals, results, nPossibleRes): """ Uses FindVarMultQuantBounds, only here for historic reasons """ bounds, gain = FindVarMultQuantBounds(vals, 1, results, nPossibleRes) return (bounds[0], gain) def _GenVarTable(vals, cuts, starts, results, nPossibleRes): """ Primarily intended for internal use constructs a variable table for the data passed in The table for a given variable records the number of times each possible value of that variable appears for each possible result of the function. **Arguments** - vals: a 1D Numeric array with the values of the variables - cuts: a list with the indices of the quantization bounds (indices are into _starts_ ) - starts: a list of potential starting points for quantization bounds - results: a 1D Numeric array of integer result codes - nPossibleRes: an integer with the number of possible result codes **Returns** the varTable, a 2D Numeric array which is nVarValues x nPossibleRes **Notes** - _vals_ should be sorted! """ nVals = len(cuts) + 1 varTable = numpy.zeros((nVals, nPossibleRes), 'i') idx = 0 for i in range(nVals - 1): cut = cuts[i] while idx < starts[cut]: varTable[i, results[idx]] += 1 idx += 1 while idx < len(vals): varTable[-1, results[idx]] += 1 idx += 1 return varTable def _PyRecurseOnBounds(vals, cuts, which, starts, results, nPossibleRes, varTable=None): """ Primarily intended for internal use Recursively finds the best quantization boundaries **Arguments** - vals: a 1D Numeric array with the values of the variables, this should be sorted - cuts: a list with the indices of the quantization bounds (indices are into _starts_ ) - which: an integer indicating which bound is being adjusted here (and index into _cuts_ ) - starts: a list of potential starting points for quantization bounds - results: a 1D Numeric array of integer result codes - nPossibleRes: an integer with the number of possible result codes **Returns** - a 2-tuple containing: 1) the best information gain found so far 2) a list of the quantization bound indices ( _cuts_ for the best case) **Notes** - this is not even remotely efficient, which is why a C replacement was written """ nBounds = len(cuts) maxGain = -1e6 bestCuts = None highestCutHere = len(starts) - nBounds + which if varTable is None: varTable = _GenVarTable(vals, cuts, starts, results, nPossibleRes) while cuts[which] <= highestCutHere: varTable = _GenVarTable(vals, cuts, starts, results, nPossibleRes) gainHere = entropy.InfoGain(varTable) if gainHere > maxGain: maxGain = gainHere bestCuts = cuts[:] # recurse on the next vars if needed if which < nBounds - 1: gainHere, cutsHere = _RecurseOnBounds(vals, cuts[:], which + 1, starts, results, nPossibleRes, varTable=varTable) if gainHere > maxGain: maxGain = gainHere bestCuts = cutsHere # update this cut cuts[which] += 1 for i in range(which + 1, nBounds): if cuts[i] == cuts[i - 1]: cuts[i] += 1 return maxGain, bestCuts def _NewPyRecurseOnBounds(vals, cuts, which, starts, results, nPossibleRes, varTable=None): """ Primarily intended for internal use Recursively finds the best quantization boundaries **Arguments** - vals: a 1D Numeric array with the values of the variables, this should be sorted - cuts: a list with the indices of the quantization bounds (indices are into _starts_ ) - which: an integer indicating which bound is being adjusted here (and index into _cuts_ ) - starts: a list of potential starting points for quantization bounds - results: a 1D Numeric array of integer result codes - nPossibleRes: an integer with the number of possible result codes **Returns** - a 2-tuple containing: 1) the best information gain found so far 2) a list of the quantization bound indices ( _cuts_ for the best case) **Notes** - this is not even remotely efficient, which is why a C replacement was written """ nBounds = len(cuts) maxGain = -1e6 bestCuts = None highestCutHere = len(starts) - nBounds + which if varTable is None: varTable = _GenVarTable(vals, cuts, starts, results, nPossibleRes) while cuts[which] <= highestCutHere: gainHere = entropy.InfoGain(varTable) if gainHere > maxGain: maxGain = gainHere bestCuts = cuts[:] # recurse on the next vars if needed if which < nBounds - 1: gainHere, cutsHere = _RecurseOnBounds(vals, cuts[:], which + 1, starts, results, nPossibleRes, varTable=None) if gainHere > maxGain: maxGain = gainHere bestCuts = cutsHere # update this cut oldCut = cuts[which] cuts[which] += 1 bot = starts[oldCut] if oldCut + 1 < len(starts): top = starts[oldCut + 1] else: top = starts[-1] for i in range(bot, top): v = results[i] varTable[which, v] += 1 varTable[which + 1, v] -= 1 for i in range(which + 1, nBounds): if cuts[i] == cuts[i - 1]: cuts[i] += 1 return maxGain, bestCuts def _NewPyFindStartPoints(sortVals, sortResults, nData): # -------------------------------- # # find all possible dividing points # # There are a couple requirements for a dividing point: # 1) the dependent variable (descriptor) must change across it, # 2) the result score must change across it # # So, in the list [(0,0),(1,0),(1,1),(2,1)]: # we should divide before (1,0) and (2,1) # # -------------------------------- startNext = [] tol = 1e-8 blockAct = sortResults[0] lastBlockAct = None lastDiv = None i = 1 while i < nData: # move to the end of this block: while i < nData and sortVals[i] - sortVals[i - 1] <= tol: if sortResults[i] != blockAct: # this block is heterogeneous blockAct = -1 i += 1 if lastBlockAct is None: # first time through: lastBlockAct = blockAct lastDiv = i else: if blockAct == -1 or lastBlockAct == -1 or blockAct != lastBlockAct: startNext.append(lastDiv) lastDiv = i lastBlockAct = blockAct else: lastDiv = i if i < nData: blockAct = sortResults[i] i += 1 # catch the case that the last point also sets a bin: if blockAct != lastBlockAct: startNext.append(lastDiv) return startNext def FindVarMultQuantBounds(vals, nBounds, results, nPossibleRes): """ finds multiple quantization bounds for a single variable **Arguments** - vals: sequence of variable values (assumed to be floats) - nBounds: the number of quantization bounds to find - results: a list of result codes (should be integers) - nPossibleRes: an integer with the number of possible values of the result variable **Returns** - a 2-tuple containing: 1) a list of the quantization bounds (floats) 2) the information gain associated with this quantization """ assert len(vals) == len(results), 'vals/results length mismatch' nData = len(vals) if nData == 0: return [], -1e8 # sort the variable values: svs = list(zip(vals, results)) svs.sort() sortVals, sortResults = zip(*svs) startNext = _FindStartPoints(sortVals, sortResults, nData) if not len(startNext): return [0], 0.0 if len(startNext) < nBounds: nBounds = len(startNext) - 1 if nBounds == 0: nBounds = 1 initCuts = list(range(nBounds)) maxGain, bestCuts = _RecurseOnBounds(sortVals, initCuts, 0, startNext, sortResults, nPossibleRes) quantBounds = [] nVs = len(sortVals) for cut in bestCuts: idx = startNext[cut] if idx == nVs: quantBounds.append(sortVals[-1]) elif idx == 0: quantBounds.append(sortVals[idx]) else: quantBounds.append((sortVals[idx] + sortVals[idx - 1]) / 2.) return quantBounds, maxGain # hascQuantize=0 if hascQuantize: _RecurseOnBounds = cQuantize._RecurseOnBounds _FindStartPoints = cQuantize._FindStartPoints else: _RecurseOnBounds = _NewPyRecurseOnBounds _FindStartPoints = _NewPyFindStartPoints if __name__ == '__main__': if 1: d = [(1., 0), (1.1, 0), (1.2, 0), (1.4, 1), (1.4, 0), (1.6, 1), (2., 1), (2.1, 0), (2.1, 0), (2.1, 0), (2.2, 1), (2.3, 0)] varValues = list(map(lambda x: x[0], d)) resCodes = list(map(lambda x: x[1], d)) nPossibleRes = 2 res = FindVarMultQuantBounds(varValues, 2, resCodes, nPossibleRes) print('RES:', res) target = ([1.3, 2.05], .34707) else: d = [(1., 0), (1.1, 0), (1.2, 0), (1.4, 1), (1.4, 0), (1.6, 1), (2., 1), (2.1, 0), (2.1, 0), (2.1, 0), (2.2, 1), (2.3, 0)] varValues = list(map(lambda x: x[0], d)) resCodes = list(map(lambda x: x[1], d)) nPossibleRes = 2 res = FindVarMultQuantBounds(varValues, 1, resCodes, nPossibleRes) print(res) # sys.exit(1) d = [(1.4, 1), (1.4, 0)] varValues = list(map(lambda x: x[0], d)) resCodes = list(map(lambda x: x[1], d)) nPossibleRes = 2 res = FindVarMultQuantBounds(varValues, 1, resCodes, nPossibleRes) print(res) d = [(1.4, 0), (1.4, 0), (1.6, 1)] varValues = list(map(lambda x: x[0], d)) resCodes = list(map(lambda x: x[1], d)) nPossibleRes = 2 res = FindVarMultQuantBounds(varValues, 2, resCodes, nPossibleRes) print(res)
rvianello/rdkit
rdkit/ML/Data/Quantize.py
Python
bsd-3-clause
10,529
[ "RDKit" ]
da59c9cd6004a2ffac4859cad7db1f534bb8f4dbd287c81c21fd094dda0d19cd
#!/usr/bin/env python import os from Bio import SeqIO import sys from Initial_functions import Uniq from Bio.Blast import NCBIXML def BWA_analysis(sra_name,additional_file,database,mapping_mode,file_mode,z): global fliC_option global fljB_option global family_c_list global family_b_list global list_c_length global list_b_length family_c_list=[] #will catch families on the family test mapping family_b_list=[] if file_mode=="1":#interleaved if sra_name[-3:]=="sra": del_fastq=1 for_fq=sra_name.replace(".sra","_1.fastq") rev_fq=sra_name.replace(".sra","_2.fastq") for_sai=sra_name.replace(".sra","_1.sai") rev_sai=sra_name.replace(".sra","_2.sai") sam=sra_name.replace(".sra",".sam") bam=sra_name.replace(".sra",".bam") else: del_fastq=0 core_id=sra_name.split(".fastq")[0] for_fq=core_id+"-read1.fastq" rev_fq=core_id+"-read2.fastq" for_sai=core_id+"_1.sai" rev_sai=core_id+"_2.sai" sam=core_id+".sam" bam=core_id+".bam" elif file_mode=="2":#seperated forword_seq=sra_name reverse_seq=additional_file for_core_id=forword_seq.split(".fastq")[0] re_core_id=reverse_seq.split(".fastq")[0] for_fq=for_core_id+".fastq" rev_fq=re_core_id+".fastq" for_sai=for_core_id+".sai" rev_sai=re_core_id+".sai" sam=for_core_id+".sam" bam=sam.replace(".sam",".bam") elif file_mode=="3":#single-end if sra_name[-3:]=="sra": del_fastq=1 for_fq=sra_name.replace(".sra","_1.fastq") rev_fq=sra_name.replace(".sra","_2.fastq") for_sai=sra_name.replace(".sra","_1.sai") rev_sai=sra_name.replace(".sra","_2.sai") sam=sra_name.replace(".sra",".sam") bam=sra_name.replace(".sra",".bam") else: del_fastq=0 core_id=sra_name.split(".fastq")[0] for_fq=core_id+".fastq" rev_fq=core_id+".fastq" for_sai=core_id+"_1.sai" rev_sai=core_id+"_2.sai" sam=core_id+".sam" bam=core_id+".bam" database=database.split("/")[-1]##########1/27/2015 os.system("bwa index database/"+database) if file_mode!="3": if mapping_mode=="mem": os.system("bwa mem database/"+database+" "+for_fq+" "+rev_fq+" > "+sam) #2014/12/23 elif mapping_mode=="sam": os.system("bwa aln database/"+database+" "+for_fq+" > "+for_sai) os.system("bwa aln database/"+database+" "+rev_fq+" > "+rev_sai) os.system("bwa sampe database/"+database+" "+for_sai+" "+ rev_sai+" "+for_fq+" "+rev_fq+" > "+sam) elif mapping_mode=="nanopore": os.system("bwa mem -x ont2d database/"+database+" "+for_fq+" "+rev_fq+" > "+sam) else: if mapping_mode=="mem": os.system("bwa mem database/"+database+" "+for_fq+" > "+sam) #2014/12/23 elif mapping_mode=="sam": os.system("bwa aln database/"+database+" "+for_fq+" > "+for_sai) os.system("bwa samse database/"+database+" "+for_sai+" "+for_fq+" > "+sam) elif mapping_mode=="nanopore": os.system("bwa mem -x ont2d database/"+database+" "+for_fq+" > "+sam) os.system("samtools view -F 4 -Sbh "+sam+" > "+bam) os.system("samtools view -h -o "+sam+" "+bam) file=open(sam,"r") handle=file.readlines() name_list=[] for line in handle: if len(line)>300: name_list.append(line.split("\t")[2]) a,b=Uniq(name_list) c=dict(zip(a,b)) Sero_list_C=[] Sero_list_B=[] description=[] #for storage of whole desription to extract the multifasta file for second BWA mapping fliC={} fljB={} for x in c: if x[:4]=="fliC": fliC[x]=c[x] for x in c: if x[:4]=="fljB": fljB[x]=c[x] final_fliC=sorted(fliC.iteritems(), key=lambda d:d[1], reverse = True) #order from frequency high to low, but tuple while not list final_fljB=sorted(fljB.iteritems(), key=lambda d:d[1], reverse = True) #order from frequency high to low, but tuple while not list print "Final_filC_list:" print final_fliC num_1=0#new inserted num_2=0#new inserted if len(final_fliC)>0: #new inserted for x in final_fliC:#new inserted num_1=num_1+x[1]#new inserted print "Final_fliC_number_together: ",num_1#new inserted print "Final_fljB_list:" print final_fljB if len(final_fljB)>0: #new inserted for x in final_fljB: #new inserted num_2=num_2+x[1] #new inserted print "Final_fljB_number_together: ",num_2#new inserted print "$$Genome:",sra_name try: fliC_option=final_fliC[0][0].split("_")[1] except: fliC_option="-" try: fljB_option=final_fljB[0][0].split("_")[1] except: fljB_option="-" if z==0: if len(final_fliC)==0 or num_1<=10: print "$$$No fliC, due to no hit" else: if final_fliC[0][1]<=1 and z==1: print "$$$No fliC, due to the hit reads number is small." else: try: family=final_fliC[0][0].split("_")[-1] Sero_list_C.append(family) description.append(final_fliC[0][0]) print "$$Most possilble fliC family: ",Sero_list_C[0]," Number: ",final_fliC[0][1] i=0 for x in final_fliC: if x[0].split("_")[-1] not in Sero_list_C: if i<=x[1]: i=x[1] sec_choice=x[0].split("_")[-1] des=x[0] number=x[1] if locals().has_key('sec_choice'): Sero_list_C.append(sec_choice) description.append(des) print "$$Sec possilble fliC family: ",sec_choice," Number: ",number j=0 for x in final_fliC: if x[0].split("_")[-1] not in Sero_list_C: if j<=x[1]: j=x[1] third_choice=x[0].split("_")[-1] des=x[0] number=x[1] if locals().has_key('third_choice'): Sero_list_C.append(third_choice) description.append(des) print "$$Third possilble fliC family: ",third_choice," Number: ",number except: print "$$$No fliC, or failure of mapping" try: ratio=float(num_2)/float(num_1) except: ratio=0 if len(final_fljB)==0 or num_2<=5 or ratio<0.15: print "$$$No fljB, due to no hit" else: if final_fljB[0][1]<=1 and z==1: print "$$$No fljB, due to the hit reads number is small." else: try: family=final_fljB[0][0].split("_")[-1] Sero_list_B.append(family) description.append(final_fljB[0][0]) print "$$Most possilble fljB family: ",Sero_list_B[0]," Number: ",final_fljB[0][1] i=0 for x in final_fljB: if x[0].split("_")[-1] not in Sero_list_B: if i<=x[1]: i=x[1] B_sec_choice=x[0].split("_")[-1] des=x[0] number=x[1] if locals().has_key('B_sec_choice'): Sero_list_B.append(B_sec_choice) description.append(des) print "$$Sec possilble fljB: ",B_sec_choice," Number: ",number j=0 for x in final_fljB: if x[0].split("_")[-1] not in Sero_list_B: if j<=x[1]: j=x[1] B_third_choice=x[0].split("_")[-1] des=x[0] number=x[1] if locals().has_key('B_third_choice'): Sero_list_B.append(B_third_choice) description.append(des) print "$$Third possilble fljB: ",B_third_choice," Number: ",number except: print "$$$No fljB, or failure of mapping" if len(description)==0: #used for the case which fljB and fliC both has no hit, it will directly cease the function return handle=SeqIO.parse("database/"+database,"fasta")########1/27/2015 handle=list(handle) file1=open("temp"+sra_name+".fasta","w") for x in handle: for y in description: if x.description==y: title=">"+x.description seq=str(x.seq) file1.write(title+"\n") file1.write(seq+"\n") file1.close() data_base2="temp"+sra_name+".fasta" os.system("mv "+data_base2+" database")######1/27/2015 z=1 BWA_analysis(sra_name,additional_file,data_base2,mapping_mode,file_mode,z) #z=1 this time, z is the pointer for the seqeunce of run return if z==1: list_c_length=len(final_fliC) list_b_length=len(final_fljB) family_test(final_fliC,"fliC",type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam) family_test(final_fljB,"fljB",type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam) #os.system("rm "+for_fq)###01/28/2015#$$$$$$$ #os.system("rm "+rev_fq)###01/28/2015 #os.system("rm "+for_sai) #os.system("rm "+rev_sai) #os.system("rm "+bam) #os.system("rm "+sam)###01/28/2015 #os.system("rm temp.txt")###01/28/2015 #os.system("rm "+sam+".fasta"+"_db.*")###01/28/2015 #os.system("rm temp"+sra_name+".fasta")###01/28/2015 def family_test(fliC_fljB_list,listtype,type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam): Sero_list_C=[] Sero_list_B=[] if listtype=="fliC": if len(fliC_fljB_list)==0: print "$$No fliC, due to no hit" #because the only possible situation for len(final_fliC)==0 is above (z=0) len(final_fliC)==0, so there is no need to use "$$$" here else: if fliC_fljB_list[0][1]<=1: print "$$No fliC, due to the hit reads number is small." #similiar with above, no "$$$" else: if fliC_fljB_list[0][0].split("_")[-1]=="g,m": type="fliC" database="FliC_f_g_s_whole.fasta" database2="FliC_Family_g_special_genes.fasta" assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_c_length,mapping_mode) elif fliC_fljB_list[0][0].split("_")[-1]=="l,v": type="fliC" database="fliC_l_z13_whole.fasta" database2="FliC_Family_l,v_special_genes.fasta" assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_c_length,mapping_mode) elif fliC_fljB_list[0][0].split("_")[-1]=="r,i": type="fliC" database="fliC_r_whole.fasta" database2="FliC_Family_r,i_special_genes_short.fasta" assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_c_length,mapping_mode) elif fliC_fljB_list[0][0].split("_")[-1]=="k,z": type="fliC" database="fliC_k,z_whole.fasta" database2="FliC_Family_k,z_special_genes.fasta" assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_c_length,mapping_mode) elif fliC_fljB_list[0][0].split("_")[-1]=="b,d,j": type="fliC" database="fliC_b_whole.fasta" database2="FliC_Family_b,d,j_special_genes.fasta" assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_c_length,mapping_mode) elif fliC_fljB_list[0][0].split("_")[-1]=="z4,z23": type="fliC" database="fliC_z4z23_whole.fasta" database2="fliC_z4,z23_family.fasta" #"FliC_Family_z4z23_special_genes.fasta" assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_c_length,mapping_mode) elif fliC_fljB_list[0][0].split("_")[-1]=="z36,z38": type="fliC" database="fliC_z36,z38_whole.fasta" database2="FliC_Family_z36z38_special_genes.fasta" assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_c_length,mapping_mode) else: try: Sero_list_C.append(fliC_fljB_list[0][0].split("_")[1]) print "$$$Most possilble fliC: ",Sero_list_C[0]," Number: ",fliC_fljB_list[0][1] i=0 for x in fliC_fljB_list: if x[0].split("_")[1] not in Sero_list_C: if i<=x[1]: i=x[1] sec_choice=x[0].split("_")[1] number=x[1] if locals().has_key('sec_choice'): Sero_list_C.append(sec_choice) print "$$$Sec possilble fliC: ",sec_choice," Number: ",number j=0 for x in fliC_fljB_list: if x[0].split("_")[1] not in Sero_list_C: if j<=x[1]: j=x[1] third_choice=x[0].split("_")[1] number=x[1] if locals().has_key('third_choice'): Sero_list_C.append(third_choice) print "$$$Third possilble fliC: ",third_choice," Number: ",number except: print "$$$No fliC, or failure of mapping (second run)" if listtype=="fljB": if len(fliC_fljB_list)==0: print "$$No fljB, due to no hit" #similiar with above, no "$$$" else: if fliC_fljB_list[0][1]<=1: print "$$No fljB, due to the hit reads number is small." #similiar with above, no "$$$" else: if fliC_fljB_list[0][0].split("_")[-1]=="1": type="fljB" database="FljB_1_2_7_whole.fasta" database2="FljB_Family_1_special_genes_all.fasta" assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_b_length,mapping_mode) elif fliC_fljB_list[0][0].split("_")[-1]=="e": type="fljB" database="fljB_e,n,z15_whole.fasta" database2="FljB_Family_e_special_genes.fasta" assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_b_length,mapping_mode) elif fliC_fljB_list[0][0].split("_")[-1]=="l,v": type="fljB" database="FljB_l,z13,z28_whole.fasta" database2="FljB_Family_l,v_special_genes.fasta" assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_b_length,mapping_mode) elif fliC_fljB_list[0][0].split("_")[-1]=="k,z": type="fljB" database="FljB_z6_whole.fasta" database2="FljB_Family_k,z_special_genes.fasta" assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_b_length,mapping_mode) else: try: Sero_list_B.append(fliC_fljB_list[0][0].split("_")[1]) print "$$$Most possilble fljB: ",Sero_list_B[0]," Number: ",fliC_fljB_list[0][1] i=0 for x in fliC_fljB_list: if x[0].split("_")[1] not in Sero_list_B: if i<=x[1]: i=x[1] B_sec_choice=x[0].split("_")[1] number=x[1] if locals().has_key('B_sec_choice'): Sero_list_B.append(B_sec_choice) print "$$$Sec possilble fljB: ",B_sec_choice," Number: ",number j=0 for x in fliC_fljB_list: if x[0].split("_")[1] not in Sero_list_B: if j<=x[1]: j=x[1] B_third_choice=x[0].split("_")[1] number=x[1] if locals().has_key('B_third_choice'): Sero_list_B.append(B_third_choice) print "$$$Third possilble fljB: ",B_third_choice," Number: ",number except: print "$$$No fljB, or failure of mapping (second run)" def assembly(type,sra_name,for_fq,rev_fq,for_sai,rev_sai,sam,bam,database,database2,list_length,mapping_mode): os.system("bwa index database/"+database) if file_mode!="3": if mapping_mode=="mem": os.system("bwa mem database/"+database+" "+for_fq+" "+rev_fq+" > "+sam) #2014/12/23 elif mapping_mode=="sam": os.system("bwa aln database/"+database+" "+for_fq+" > "+for_sai) os.system("bwa aln database/"+database+" "+rev_fq+" > "+rev_sai) os.system("bwa sampe database/"+database+" "+for_sai+" "+ rev_sai+" "+for_fq+" "+rev_fq+" > "+sam) elif mapping_mode=="nanopore": os.system("bwa mem -x ont2d database/"+database+" "+for_fq+" "+rev_fq+" > "+sam) else: if mapping_mode=="mem": os.system("bwa mem database/"+database+" "+for_fq+" > "+sam) #2014/12/23 elif mapping_mode=="sam": os.system("bwa aln database/"+database+" "+for_fq+" > "+for_sai) os.system("bwa samse database/"+database+" "+for_sai+" "+for_fq+" > "+sam) elif mapping_mode=="nanopore": os.system("bwa mem -x ont2d database/"+database+" "+for_fq+" > "+sam) os.system("samtools view -F 4 -Sbh "+sam+" > "+bam) os.system("samtools view -h -o "+sam+" "+bam) os.system("cat "+sam+"|awk '{if ($5>=0) {print $10}}'>"+database+sam+"_seq.txt") os.system("cat "+sam+"|awk '{if ($5>=0) {print $1}}'>"+database+sam+"_title.txt") file1=open(database+sam+"_title.txt","r") file2=open(database+sam+"_seq.txt","r") file1=file1.readlines() file2=file2.readlines() file=open(database+"_"+sam+".fasta","w") for i in range(len(file1)): title=">"+file1[i] seq=file2[i] if len(seq)>=50 and len(title)>6:#generally, can be adjusted with different situations file.write(title) file.write(seq) file.close() os.system("mv "+database+"_"+sam+".fasta"+" database")######1/27/2015 os.system('makeblastdb -in database/'+database+"_"+sam+".fasta"+' -out '+sam+".fasta"+'_db '+'-dbtype nucl >temp.txt') #temp.txt is to forbid the blast result interrupt the output of our program###1/27/2015 os.system("blastn -query database/"+database2+" -db "+sam+".fasta"+"_db -out "+database2+"_vs_"+sam+".xml -outfmt 5 >temp.txt")###1/27/2015 handle=open(database2+"_vs_"+sam+".xml") handle=NCBIXML.parse(handle) handle=list(handle) List=[] List_score=[] for i in range(len(handle)): if len(handle[i].alignments)>0: List.append(handle[i].query) score=0 for j in range(len(handle[i].alignments)): for z in range(len(handle[i].alignments[j].hsps)): score+=handle[i].alignments[j].hsps[z].bits List_score.append(score) temp=dict(zip(List,List_score)) Final_list=sorted(temp.iteritems(), key=lambda d:d[1], reverse = True) family=database2.split("_")[2] try: Final_list[0][0].split("_")[1] # or it will always print "$$$Genome...."(next line) print "$$$Genome:",sra_name print "$$$Most possilble "+type+": ",Final_list[0][0].split("_")[1]," Score(due_to_special_test, number changed to score): ",Final_list[0][1] print Final_list except: if type=="fliC": print "$$$There may be no hit for "+type+"_"+family+" family due to the reads not covering core seqeunce, but just based on reads hit number, the most possible one is: ",fliC_option if type=="fljB": print "$$$There may be no hit for "+type+"_"+family+" family due to the reads not covering core seqeunce, but just based on reads hit number, the most possible one is: ",fljB_option os.system("rm "+database2+"_vs_"+sam+".xml")###01/28/2015 os.system("rm "+database+sam+"_seq.txt")###01/28/2015 os.system("rm "+database+sam+"_title.txt")###01/28/2015 os.system("rm temp.txt")###01/28/2015 os.system("rm "+sam+".fasta"+"_db.*")###01/28/2015 z=0 target=sys.argv[1] #should be sra format data_base=sys.argv[2] mapping_mode=sys.argv[3] if sys.argv[4] not in ("1","2","3"): additional_file=sys.argv[4] file_mode=sys.argv[5] else: additional_file="" file_mode=sys.argv[4] BWA_analysis(target,additional_file,data_base,mapping_mode,file_mode,z)
denglab/SeqSero
libs/BWA_analysis_H_update_new_family_dependent.py
Python
gpl-2.0
19,874
[ "BLAST", "BWA" ]
738a5d6d4163eb8c8478c7fbf12ec98d516e112c443287372af1c4e4d83328f4
# -*- coding: utf-8 -*- """ End-to-end tests for set manage target of biz feature """ from bok_choy.web_app_test import WebAppTest from nose.plugins.attrib import attr from . import ( SUPER_USER_INFO, PLATFORMER_USER_INFO, PLAT_COMPANY_NAME, PLAT_COMPANY_CODE, GaccoBizTestMixin, ) from ...pages.biz.ga_achievement import BizAchievementPage from ...pages.biz.ga_contract import BizContractPage from ...pages.biz.ga_contract_operation import BizStudentsPage from ...pages.biz.ga_dashboard import DashboardPage from ...pages.biz.ga_navigation import NO_SELECTED from ...pages.lms.ga_django_admin import DjangoAdminPage @attr('shard_ga_biz_2') class BizSetManageTargetTest(WebAppTest, GaccoBizTestMixin): def test_director_no_contract(self): """ Test director has no contract - Case 1 """ new_director = self.register_user() # test data, org contract permission new_org_info = self.register_organization(PLATFORMER_USER_INFO) self.grant(PLATFORMER_USER_INFO, new_org_info['Organization Name'], 'director', new_director) # Test Case 1 self.restart_memcached() self.switch_to_user(new_director) biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.wait_for_contract_not_specified() self.assertEqual([u'Contract is not specified.'], biz_nav.messages) def test_change_manage_target_no_select(self): """ Test change target, select empty - Case 2, 3 """ # create course new_course_key_plat_1, _ = self.install_course(PLAT_COMPANY_CODE) new_course_key_plat_2, new_course_name_plat_2 = self.install_course(PLAT_COMPANY_CODE) new_director = self.register_user() new_manager = self.register_user() # test data, org contract permission new_org_info_1 = self.register_organization(PLATFORMER_USER_INFO) new_contract = self.register_contract(PLATFORMER_USER_INFO, new_org_info_1['Organization Name'], detail_info=[new_course_key_plat_1, new_course_key_plat_2]) self.register_contract(PLATFORMER_USER_INFO, new_org_info_1['Organization Name']) self.grant(PLATFORMER_USER_INFO, new_org_info_1['Organization Name'], 'director', new_director) self.grant(PLATFORMER_USER_INFO, new_org_info_1['Organization Name'], 'manager', new_manager) new_org_info_2 = self.register_organization(PLATFORMER_USER_INFO) self.grant(PLATFORMER_USER_INFO, new_org_info_2['Organization Name'], 'director', new_director) self.grant(PLATFORMER_USER_INFO, new_org_info_2['Organization Name'], 'manager', new_manager) # Test Case 2 self.switch_to_user(new_director) biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.change_manage_target(new_org_info_1['Organization Name'], new_contract['Contract Name'], new_course_name_plat_2) BizAchievementPage(self.browser).wait_for_page() self.assertEqual(biz_nav.contract_name, new_contract['Contract Name']) self.assertEqual(biz_nav.course_name, new_course_name_plat_2) # Test Case 3 biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.change_manage_target(NO_SELECTED, close=False) self.assertEqual(biz_nav.modal_message, u'Organization name is not specified.') biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.change_manage_target(new_org_info_1['Organization Name'], NO_SELECTED, close=False) self.assertEqual(biz_nav.modal_message, u'Contract name is not specified.') biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.change_manage_target(new_org_info_1['Organization Name'], new_contract['Contract Name'], NO_SELECTED, close=False) BizStudentsPage(self.browser).wait_for_page() # Test Case 2:manager self.switch_to_user(new_manager) biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.change_manage_target(new_org_info_1['Organization Name'], new_contract['Contract Name'], new_course_name_plat_2) BizAchievementPage(self.browser).wait_for_page() self.assertEqual(biz_nav.contract_name, new_contract['Contract Name']) self.assertEqual(biz_nav.course_name, new_course_name_plat_2) # Test Case 3:manager biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.change_manage_target(NO_SELECTED, close=False) self.assertEqual(biz_nav.modal_message, u'Organization name is not specified.') biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.change_manage_target(new_org_info_1['Organization Name'], NO_SELECTED, close=False) self.assertEqual(biz_nav.modal_message, u'Contract name is not specified.') biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.change_manage_target(new_org_info_1['Organization Name'], new_contract['Contract Name'], NO_SELECTED, close=False) biz_nav.wait_for_page().wait_for_course_not_specified() self.assertEqual(biz_nav.messages, [u'Course is not specified.']) def test_no_contract_no_course(self): """ Test no contract, no course - Case 85, 86 """ # test data, org contract permission for aggregator new_aggregator, _, _ = self.create_aggregator() # test data, org permission for director new_director = self.register_user() new_manager = self.register_user() new_org_info = self.register_organization(new_aggregator) self.grant(new_aggregator, new_org_info['Organization Name'], 'director', new_director) self.grant(new_aggregator, new_org_info['Organization Name'], 'manager', new_manager) # Test Case 85 self.restart_memcached() self.switch_to_user(new_director) biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.wait_for_contract_not_specified() self.assertEqual(biz_nav.messages, [u'Contract is not specified.']) # Test Case 85:manager self.restart_memcached() self.switch_to_user(new_manager) biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.wait_for_contract_not_specified() self.assertEqual(biz_nav.messages, [u'Contract is not specified.']) # test data contract for director self.register_contract(new_aggregator, new_org_info['Organization Name'], 'OS') # Test Case 86 self.restart_memcached() self.switch_to_user(new_director) biz_nav = DashboardPage(self.browser).visit().click_biz() BizStudentsPage(self.browser).wait_for_page() # Test Case 86:manager self.restart_memcached() self.switch_to_user(new_manager) biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.wait_for_course_not_specified() self.assertEqual(biz_nav.messages, [u'Course is not specified.']) def test_just_1(self): """ Test just 1 org, 1 contract, 1 course - Case 87 """ # test data, org contract permission for aggregator new_aggregator, new_org_info_1, _ = self.create_aggregator() # create course new_course_key_1, new_course_name_1 = self.install_course(new_org_info_1['Organization Code']) # test data, org contract permission for director new_director = self.register_user() new_org_info_2 = self.register_organization(new_aggregator) new_contract = self.register_contract(new_aggregator, new_org_info_2['Organization Name'], 'OS', detail_info=[new_course_key_1]) self.grant(new_aggregator, new_org_info_2['Organization Name'], 'director', new_director) # Test Case 87 self.restart_memcached() self.switch_to_user(new_director) biz_nav = DashboardPage(self.browser).visit().click_biz() BizAchievementPage(self.browser).wait_for_page() self.assertEqual(biz_nav.contract_name, new_contract['Contract Name']) self.assertEqual(biz_nav.course_name, new_course_name_1) def test_2_courses(self): """ Test 1 org, 1 contract, 2 courses - Case 88 """ # test data, org contract permission for aggregator new_aggregator, new_org_info_1, _ = self.create_aggregator() # create course new_course_key_1, _ = self.install_course(new_org_info_1['Organization Code']) new_course_key_2, new_course_name_2 = self.install_course(new_org_info_1['Organization Code']) # test data, org contract permission for director new_director = self.register_user() new_org_info_2 = self.register_organization(new_aggregator) new_contract = self.register_contract(new_aggregator, new_org_info_2['Organization Name'], 'OS', detail_info=[new_course_key_1, new_course_key_2]) self.grant(new_aggregator, new_org_info_2['Organization Name'], 'director', new_director) # Test Case 88 self.restart_memcached() self.switch_to_user(new_director) biz_nav = DashboardPage(self.browser).visit().click_biz() BizStudentsPage(self.browser).wait_for_page() biz_nav.change_manage_target(new_org_info_2['Organization Name'], new_contract['Contract Name'], new_course_name_2) BizAchievementPage(self.browser).wait_for_page() self.assertEqual(biz_nav.contract_name, new_contract['Contract Name']) self.assertEqual(biz_nav.course_name, new_course_name_2) # Retry from Dashboard biz_nav = DashboardPage(self.browser).visit().click_biz() self.assertEqual(biz_nav.contract_name, new_contract['Contract Name']) self.assertEqual(biz_nav.course_name, new_course_name_2) def test_2_contracts(self): """ Test 1 org, 2 contracts, 1 course - Case 89 """ # test data, org contract permission for aggregator new_aggregator, new_org_info_1, _ = self.create_aggregator() # create course new_course_key_1, new_course_name_1 = self.install_course(new_org_info_1['Organization Code']) # test data, org contract permission for director new_director = self.register_user() new_org_info_2 = self.register_organization(new_aggregator) self.register_contract(new_aggregator, new_org_info_2['Organization Name'], 'OS') new_contract = self.register_contract(new_aggregator, new_org_info_2['Organization Name'], 'OS', detail_info=[new_course_key_1]) self.grant(new_aggregator, new_org_info_2['Organization Name'], 'director', new_director) # Test Case 89 self.restart_memcached() self.switch_to_user(new_director) biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.wait_for_contract_not_specified() self.assertEqual(biz_nav.messages, [u'Contract is not specified.']) biz_nav.change_manage_target(new_org_info_2['Organization Name'], new_contract['Contract Name'], new_course_name_1) BizAchievementPage(self.browser).wait_for_page() self.assertEqual(biz_nav.contract_name, new_contract['Contract Name']) self.assertEqual(biz_nav.course_name, new_course_name_1) # Retry from Dashboard biz_nav = DashboardPage(self.browser).visit().click_biz() self.assertEqual(biz_nav.contract_name, new_contract['Contract Name']) self.assertEqual(biz_nav.course_name, new_course_name_1) def test_aggregator_no_contract_1_contract(self): """ Test aggregator has no contract - Case 90, 91 """ # test data, org permission for aggregator new_aggregator, new_org_info, _ = self.create_aggregator(0) # Test Case 90 self.restart_memcached() self.switch_to_user(new_aggregator) biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.wait_for_contract_not_specified() self.assertEqual([u'Contract is not specified.'], biz_nav.messages) # test data, contract for aggregator new_contract = self.register_contract(PLATFORMER_USER_INFO, new_org_info['Organization Name'], 'O') # Test Case 91 self.restart_memcached() self.switch_to_user(new_aggregator) biz_nav = DashboardPage(self.browser).visit().click_biz() BizContractPage(self.browser).wait_for_page() self.assertEqual([], biz_nav.messages) def test_aggregator_2_contracts(self): """ Test 1 org, 2 contracts - Case 92 """ # test data, org contract permission for aggregator new_aggregator, new_org_info, new_contracts = self.create_aggregator(2) # Test Case 92 self.restart_memcached() self.switch_to_user(new_aggregator) biz_nav = DashboardPage(self.browser).visit().click_biz() biz_nav.wait_for_contract_not_specified() self.assertEqual(biz_nav.messages, [u'Contract is not specified.']) biz_nav.change_manage_target(new_org_info['Organization Name'], new_contracts[1]['Contract Name']) BizContractPage(self.browser).wait_for_page() self.assertEqual([], biz_nav.messages) # Retry from Dashboard biz_nav = DashboardPage(self.browser).visit().click_biz() BizContractPage(self.browser).wait_for_page() self.assertEqual([], biz_nav.messages) def test_platformer(self): """ Test platformer view page of contract - Case 93 """ self.restart_memcached() self.switch_to_user(PLATFORMER_USER_INFO) biz_nav = DashboardPage(self.browser).visit().click_biz() BizContractPage(self.browser).wait_for_page() self.assertEqual([], biz_nav.messages) def test_new_platformer(self): """ Test new platformer view page of contract - Case 94 """ new_platformer = self.register_user() # register platformer on django admin self.switch_to_user(SUPER_USER_INFO) django_admin_add_page = DjangoAdminPage(self.browser).visit().click_add('ga_manager', 'manager') django_admin_list_page = django_admin_add_page.input({ 'org': PLAT_COMPANY_NAME, 'manager_permissions': 'platformer', }).lookup_user('lookup_id_user', new_platformer['username']).save() django_admin_list_page.get_row({ 'Org name': PLAT_COMPANY_NAME, 'User name': new_platformer['username'], 'Permissions': 'platformer', }) # Test Case 94 self.restart_memcached() self.switch_to_user(new_platformer) biz_nav = DashboardPage(self.browser).visit().click_biz() BizContractPage(self.browser).wait_for_page() self.assertEqual([], biz_nav.messages)
nttks/edx-platform
common/test/acceptance/tests/biz/test_ga_set_manage_target.py
Python
agpl-3.0
14,958
[ "VisIt" ]
5f01870030ef15e509ace852d2f9f150057ee7c98f54e5a1c4960e6b058bcfa6
from aiida.parsers.exceptions import OutputParsingError from aiida.orm.data.array.trajectory import TrajectoryData from aiida.parsers.plugins.vasp.instruction import BaseInstruction import numpy as np import mmap def read_VASP_XDATCAR(file_name, time_step, limit_number_steps=10000000, initial_cut=1, end_cut=None): # Dimensionality of VASP calculation number_of_dimensions = 3 configuration_number = [] positions = [] counter = 0 with open(file_name, "r+") as f: file_map = mmap.mmap(f.fileno(), 0) # Read cell for i in range(2): file_map.readline() a = file_map.readline().split() b = file_map.readline().split() c = file_map.readline().split() cells = np.array([a, b, c], dtype='double').T atomic_symbols_line = file_map.readline().split() # for i in range(1): file_map.readline() number_of_types = np.array(file_map.readline().split(), dtype=int) # print number_of_types symbols = [] for i, j in enumerate(atomic_symbols_line): symbols.append([j] * number_of_types[i]) print symbols symbols = [item for sublist in symbols for item in sublist] number_of_atoms = number_of_types.sum() while True: counter += 1 # Read time steps position_number = file_map.find('Direct configuration') if position_number < 0: break file_map.seek(position_number) configuration_number.append(int(file_map.readline().split('=')[1])-1) # Initial cut control if initial_cut > counter: continue # Reading coordinates read_coordinates = [] for i in range(number_of_atoms): read_coordinates.append(file_map.readline().split()[0:number_of_dimensions]) try: positions.append(np.array(read_coordinates, dtype=float)) # in angstroms except ValueError: print("Error reading step {0}".format(counter)) break # print(read_coordinates) # security routine to limit maximum of steps to read and put in memory if limit_number_steps + initial_cut < counter: print("Warning! maximum number of steps reached! No more steps will be read") break if end_cut is not None and end_cut <= counter: break file_map.close() positions = np.array(positions) n_steps = len(positions) np.array([cells.tolist() * n_steps]) step_ids = range(n_steps) time = np.array(configuration_number) * time_step return step_ids, positions, time, cells, symbols class Trajectory_parametersInstruction(BaseInstruction): _input_file_list_ = ['XDATCAR'] def _parser_function(self): """ Parses the XDATCAR using custom function. """ parser_warnings = {} # return non-critical errors timestep = self._calc.inp.incar.dict.NSW * 1e-3 # In picoseconds # extract data try: step_ids, positions, time, cells, symbols = read_VASP_XDATCAR(self._out_folder.get_abs_path('XDATCAR'), timestep) except: print ('Error parsing XDATCAR') # construct proper trajectory data format trajectory_data = TrajectoryData() try: nodes_list = [] trajectory_data.set_trajectory(step_ids, cells, symbols, positions, times=time) nodes_list.append(( 'trajectory_data', trajectory_data )) except Exception, e: msg = ( "Failed to create AiiDA data structures " "(ParameterData/ArrrayData) from parsed data, " "with error message:\n>> {}".format(e) ) raise OutputParsingError(msg) if not parser_warnings: parser_warnings = None return nodes_list, parser_warnings
abelcarreras/aiida_extensions
plugins/parsers/vasp/instruction/data/trajectory_data_parser.py
Python
mit
4,127
[ "VASP" ]
7058504f2be3f0219eeb3b32775c29a6faaeba0d37cbc3f2a72950f37bb061b2
# being a bit too dynamic # pylint: disable=E1101 from __future__ import division import warnings import re from collections import namedtuple from distutils.version import LooseVersion import numpy as np from pandas.util._decorators import cache_readonly, Appender from pandas.compat import range, lrange, map, zip, string_types import pandas.compat as compat import pandas.core.common as com from pandas.core.base import PandasObject from pandas.core.config import get_option from pandas.core.generic import _shared_docs, _shared_doc_kwargs from pandas.core.dtypes.missing import isna, notna, remove_na_arraylike from pandas.core.dtypes.common import ( is_list_like, is_integer, is_number, is_hashable, is_iterator) from pandas.core.dtypes.generic import ( ABCSeries, ABCDataFrame, ABCPeriodIndex, ABCMultiIndex, ABCIndexClass) from pandas.io.formats.printing import pprint_thing from pandas.plotting._compat import _mpl_ge_3_0_0 from pandas.plotting._style import (plot_params, _get_standard_colors) from pandas.plotting._tools import (_subplots, _flatten, table, _handle_shared_axes, _get_all_lines, _get_xlim, _set_ticks_props, format_date_labels) try: from pandas.plotting import _converter except ImportError: _HAS_MPL = False else: _HAS_MPL = True if get_option('plotting.matplotlib.register_converters'): _converter.register(explicit=True) def _raise_if_no_mpl(): # TODO(mpl_converter): remove once converter is explicit if not _HAS_MPL: raise ImportError("matplotlib is required for plotting.") def _get_standard_kind(kind): return {'density': 'kde'}.get(kind, kind) def _gca(rc=None): import matplotlib.pyplot as plt with plt.rc_context(rc): return plt.gca() def _gcf(): import matplotlib.pyplot as plt return plt.gcf() class MPLPlot(object): """ Base class for assembling a pandas plot using matplotlib Parameters ---------- data : """ @property def _kind(self): """Specify kind str. Must be overridden in child class""" raise NotImplementedError _layout_type = 'vertical' _default_rot = 0 orientation = None _pop_attributes = ['label', 'style', 'logy', 'logx', 'loglog', 'mark_right', 'stacked'] _attr_defaults = {'logy': False, 'logx': False, 'loglog': False, 'mark_right': True, 'stacked': False} def __init__(self, data, kind=None, by=None, subplots=False, sharex=None, sharey=False, use_index=True, figsize=None, grid=None, legend=True, rot=None, ax=None, fig=None, title=None, xlim=None, ylim=None, xticks=None, yticks=None, sort_columns=False, fontsize=None, secondary_y=False, colormap=None, table=False, layout=None, **kwds): _raise_if_no_mpl() _converter._WARN = False self.data = data self.by = by self.kind = kind self.sort_columns = sort_columns self.subplots = subplots if sharex is None: if ax is None: self.sharex = True else: # if we get an axis, the users should do the visibility # setting... self.sharex = False else: self.sharex = sharex self.sharey = sharey self.figsize = figsize self.layout = layout self.xticks = xticks self.yticks = yticks self.xlim = xlim self.ylim = ylim self.title = title self.use_index = use_index self.fontsize = fontsize if rot is not None: self.rot = rot # need to know for format_date_labels since it's rotated to 30 by # default self._rot_set = True else: self._rot_set = False self.rot = self._default_rot if grid is None: grid = False if secondary_y else self.plt.rcParams['axes.grid'] self.grid = grid self.legend = legend self.legend_handles = [] self.legend_labels = [] for attr in self._pop_attributes: value = kwds.pop(attr, self._attr_defaults.get(attr, None)) setattr(self, attr, value) self.ax = ax self.fig = fig self.axes = None # parse errorbar input if given xerr = kwds.pop('xerr', None) yerr = kwds.pop('yerr', None) self.errors = {} for kw, err in zip(['xerr', 'yerr'], [xerr, yerr]): self.errors[kw] = self._parse_errorbars(kw, err) if not isinstance(secondary_y, (bool, tuple, list, np.ndarray, ABCIndexClass)): secondary_y = [secondary_y] self.secondary_y = secondary_y # ugly TypeError if user passes matplotlib's `cmap` name. # Probably better to accept either. if 'cmap' in kwds and colormap: raise TypeError("Only specify one of `cmap` and `colormap`.") elif 'cmap' in kwds: self.colormap = kwds.pop('cmap') else: self.colormap = colormap self.table = table self.kwds = kwds self._validate_color_args() def _validate_color_args(self): if 'color' not in self.kwds and 'colors' in self.kwds: warnings.warn(("'colors' is being deprecated. Please use 'color'" "instead of 'colors'")) colors = self.kwds.pop('colors') self.kwds['color'] = colors if ('color' in self.kwds and self.nseries == 1 and not is_list_like(self.kwds['color'])): # support series.plot(color='green') self.kwds['color'] = [self.kwds['color']] if ('color' in self.kwds and isinstance(self.kwds['color'], tuple) and self.nseries == 1 and len(self.kwds['color']) in (3, 4)): # support RGB and RGBA tuples in series plot self.kwds['color'] = [self.kwds['color']] if ('color' in self.kwds or 'colors' in self.kwds) and \ self.colormap is not None: warnings.warn("'color' and 'colormap' cannot be used " "simultaneously. Using 'color'") if 'color' in self.kwds and self.style is not None: if is_list_like(self.style): styles = self.style else: styles = [self.style] # need only a single match for s in styles: if re.match('^[a-z]+?', s) is not None: raise ValueError( "Cannot pass 'style' string with a color " "symbol and 'color' keyword argument. Please" " use one or the other or pass 'style' " "without a color symbol") def _iter_data(self, data=None, keep_index=False, fillna=None): if data is None: data = self.data if fillna is not None: data = data.fillna(fillna) # TODO: unused? # if self.sort_columns: # columns = com.try_sort(data.columns) # else: # columns = data.columns for col, values in data.iteritems(): if keep_index is True: yield col, values else: yield col, values.values @property def nseries(self): if self.data.ndim == 1: return 1 else: return self.data.shape[1] def draw(self): self.plt.draw_if_interactive() def generate(self): self._args_adjust() self._compute_plot_data() self._setup_subplots() self._make_plot() self._add_table() self._make_legend() self._adorn_subplots() for ax in self.axes: self._post_plot_logic_common(ax, self.data) self._post_plot_logic(ax, self.data) def _args_adjust(self): pass def _has_plotted_object(self, ax): """check whether ax has data""" return (len(ax.lines) != 0 or len(ax.artists) != 0 or len(ax.containers) != 0) def _maybe_right_yaxis(self, ax, axes_num): if not self.on_right(axes_num): # secondary axes may be passed via ax kw return self._get_ax_layer(ax) if hasattr(ax, 'right_ax'): # if it has right_ax proparty, ``ax`` must be left axes return ax.right_ax elif hasattr(ax, 'left_ax'): # if it has left_ax proparty, ``ax`` must be right axes return ax else: # otherwise, create twin axes orig_ax, new_ax = ax, ax.twinx() # TODO: use Matplotlib public API when available new_ax._get_lines = orig_ax._get_lines new_ax._get_patches_for_fill = orig_ax._get_patches_for_fill orig_ax.right_ax, new_ax.left_ax = new_ax, orig_ax if not self._has_plotted_object(orig_ax): # no data on left y orig_ax.get_yaxis().set_visible(False) return new_ax def _setup_subplots(self): if self.subplots: fig, axes = _subplots(naxes=self.nseries, sharex=self.sharex, sharey=self.sharey, figsize=self.figsize, ax=self.ax, layout=self.layout, layout_type=self._layout_type) else: if self.ax is None: fig = self.plt.figure(figsize=self.figsize) axes = fig.add_subplot(111) else: fig = self.ax.get_figure() if self.figsize is not None: fig.set_size_inches(self.figsize) axes = self.ax axes = _flatten(axes) if self.logx or self.loglog: [a.set_xscale('log') for a in axes] if self.logy or self.loglog: [a.set_yscale('log') for a in axes] self.fig = fig self.axes = axes @property def result(self): """ Return result axes """ if self.subplots: if self.layout is not None and not is_list_like(self.ax): return self.axes.reshape(*self.layout) else: return self.axes else: sec_true = isinstance(self.secondary_y, bool) and self.secondary_y all_sec = (is_list_like(self.secondary_y) and len(self.secondary_y) == self.nseries) if (sec_true or all_sec): # if all data is plotted on secondary, return right axes return self._get_ax_layer(self.axes[0], primary=False) else: return self.axes[0] def _compute_plot_data(self): data = self.data if isinstance(data, ABCSeries): label = self.label if label is None and data.name is None: label = 'None' data = data.to_frame(name=label) # GH16953, _convert is needed as fallback, for ``Series`` # with ``dtype == object`` data = data._convert(datetime=True, timedelta=True) numeric_data = data.select_dtypes(include=[np.number, "datetime", "datetimetz", "timedelta"]) try: is_empty = numeric_data.empty except AttributeError: is_empty = not len(numeric_data) # no empty frames or series allowed if is_empty: raise TypeError('Empty {0!r}: no numeric data to ' 'plot'.format(numeric_data.__class__.__name__)) self.data = numeric_data def _make_plot(self): raise com.AbstractMethodError(self) def _add_table(self): if self.table is False: return elif self.table is True: data = self.data.transpose() else: data = self.table ax = self._get_ax(0) table(ax, data) def _post_plot_logic_common(self, ax, data): """Common post process for each axes""" def get_label(i): try: return pprint_thing(data.index[i]) except Exception: return '' if self.orientation == 'vertical' or self.orientation is None: if self._need_to_set_index: xticklabels = [get_label(x) for x in ax.get_xticks()] ax.set_xticklabels(xticklabels) self._apply_axis_properties(ax.xaxis, rot=self.rot, fontsize=self.fontsize) self._apply_axis_properties(ax.yaxis, fontsize=self.fontsize) if hasattr(ax, 'right_ax'): self._apply_axis_properties(ax.right_ax.yaxis, fontsize=self.fontsize) elif self.orientation == 'horizontal': if self._need_to_set_index: yticklabels = [get_label(y) for y in ax.get_yticks()] ax.set_yticklabels(yticklabels) self._apply_axis_properties(ax.yaxis, rot=self.rot, fontsize=self.fontsize) self._apply_axis_properties(ax.xaxis, fontsize=self.fontsize) if hasattr(ax, 'right_ax'): self._apply_axis_properties(ax.right_ax.yaxis, fontsize=self.fontsize) else: # pragma no cover raise ValueError def _post_plot_logic(self, ax, data): """Post process for each axes. Overridden in child classes""" pass def _adorn_subplots(self): """Common post process unrelated to data""" if len(self.axes) > 0: all_axes = self._get_subplots() nrows, ncols = self._get_axes_layout() _handle_shared_axes(axarr=all_axes, nplots=len(all_axes), naxes=nrows * ncols, nrows=nrows, ncols=ncols, sharex=self.sharex, sharey=self.sharey) for ax in self.axes: if self.yticks is not None: ax.set_yticks(self.yticks) if self.xticks is not None: ax.set_xticks(self.xticks) if self.ylim is not None: ax.set_ylim(self.ylim) if self.xlim is not None: ax.set_xlim(self.xlim) ax.grid(self.grid) if self.title: if self.subplots: if is_list_like(self.title): if len(self.title) != self.nseries: msg = ('The length of `title` must equal the number ' 'of columns if using `title` of type `list` ' 'and `subplots=True`.\n' 'length of title = {}\n' 'number of columns = {}').format( len(self.title), self.nseries) raise ValueError(msg) for (ax, title) in zip(self.axes, self.title): ax.set_title(title) else: self.fig.suptitle(self.title) else: if is_list_like(self.title): msg = ('Using `title` of type `list` is not supported ' 'unless `subplots=True` is passed') raise ValueError(msg) self.axes[0].set_title(self.title) def _apply_axis_properties(self, axis, rot=None, fontsize=None): labels = axis.get_majorticklabels() + axis.get_minorticklabels() for label in labels: if rot is not None: label.set_rotation(rot) if fontsize is not None: label.set_fontsize(fontsize) @property def legend_title(self): if not isinstance(self.data.columns, ABCMultiIndex): name = self.data.columns.name if name is not None: name = pprint_thing(name) return name else: stringified = map(pprint_thing, self.data.columns.names) return ','.join(stringified) def _add_legend_handle(self, handle, label, index=None): if label is not None: if self.mark_right and index is not None: if self.on_right(index): label = label + ' (right)' self.legend_handles.append(handle) self.legend_labels.append(label) def _make_legend(self): ax, leg = self._get_ax_legend(self.axes[0]) handles = [] labels = [] title = '' if not self.subplots: if leg is not None: title = leg.get_title().get_text() handles = leg.legendHandles labels = [x.get_text() for x in leg.get_texts()] if self.legend: if self.legend == 'reverse': self.legend_handles = reversed(self.legend_handles) self.legend_labels = reversed(self.legend_labels) handles += self.legend_handles labels += self.legend_labels if self.legend_title is not None: title = self.legend_title if len(handles) > 0: ax.legend(handles, labels, loc='best', title=title) elif self.subplots and self.legend: for ax in self.axes: if ax.get_visible(): ax.legend(loc='best') def _get_ax_legend(self, ax): leg = ax.get_legend() other_ax = (getattr(ax, 'left_ax', None) or getattr(ax, 'right_ax', None)) other_leg = None if other_ax is not None: other_leg = other_ax.get_legend() if leg is None and other_leg is not None: leg = other_leg ax = other_ax return ax, leg @cache_readonly def plt(self): import matplotlib.pyplot as plt return plt _need_to_set_index = False def _get_xticks(self, convert_period=False): index = self.data.index is_datetype = index.inferred_type in ('datetime', 'date', 'datetime64', 'time') if self.use_index: if convert_period and isinstance(index, ABCPeriodIndex): self.data = self.data.reindex(index=index.sort_values()) x = self.data.index.to_timestamp()._mpl_repr() elif index.is_numeric(): """ Matplotlib supports numeric values or datetime objects as xaxis values. Taking LBYL approach here, by the time matplotlib raises exception when using non numeric/datetime values for xaxis, several actions are already taken by plt. """ x = index._mpl_repr() elif is_datetype: self.data = self.data[notna(self.data.index)] self.data = self.data.sort_index() x = self.data.index._mpl_repr() else: self._need_to_set_index = True x = lrange(len(index)) else: x = lrange(len(index)) return x @classmethod def _plot(cls, ax, x, y, style=None, is_errorbar=False, **kwds): mask = isna(y) if mask.any(): y = np.ma.array(y) y = np.ma.masked_where(mask, y) if isinstance(x, ABCIndexClass): x = x._mpl_repr() if is_errorbar: if 'xerr' in kwds: kwds['xerr'] = np.array(kwds.get('xerr')) if 'yerr' in kwds: kwds['yerr'] = np.array(kwds.get('yerr')) return ax.errorbar(x, y, **kwds) else: # prevent style kwarg from going to errorbar, where it is # unsupported if style is not None: args = (x, y, style) else: args = (x, y) return ax.plot(*args, **kwds) def _get_index_name(self): if isinstance(self.data.index, ABCMultiIndex): name = self.data.index.names if com._any_not_none(*name): name = ','.join(pprint_thing(x) for x in name) else: name = None else: name = self.data.index.name if name is not None: name = pprint_thing(name) return name @classmethod def _get_ax_layer(cls, ax, primary=True): """get left (primary) or right (secondary) axes""" if primary: return getattr(ax, 'left_ax', ax) else: return getattr(ax, 'right_ax', ax) def _get_ax(self, i): # get the twinx ax if appropriate if self.subplots: ax = self.axes[i] ax = self._maybe_right_yaxis(ax, i) self.axes[i] = ax else: ax = self.axes[0] ax = self._maybe_right_yaxis(ax, i) ax.get_yaxis().set_visible(True) return ax def on_right(self, i): if isinstance(self.secondary_y, bool): return self.secondary_y if isinstance(self.secondary_y, (tuple, list, np.ndarray, ABCIndexClass)): return self.data.columns[i] in self.secondary_y def _apply_style_colors(self, colors, kwds, col_num, label): """ Manage style and color based on column number and its label. Returns tuple of appropriate style and kwds which "color" may be added. """ style = None if self.style is not None: if isinstance(self.style, list): try: style = self.style[col_num] except IndexError: pass elif isinstance(self.style, dict): style = self.style.get(label, style) else: style = self.style has_color = 'color' in kwds or self.colormap is not None nocolor_style = style is None or re.match('[a-z]+', style) is None if (has_color or self.subplots) and nocolor_style: kwds['color'] = colors[col_num % len(colors)] return style, kwds def _get_colors(self, num_colors=None, color_kwds='color'): if num_colors is None: num_colors = self.nseries return _get_standard_colors(num_colors=num_colors, colormap=self.colormap, color=self.kwds.get(color_kwds)) def _parse_errorbars(self, label, err): """ Look for error keyword arguments and return the actual errorbar data or return the error DataFrame/dict Error bars can be specified in several ways: Series: the user provides a pandas.Series object of the same length as the data ndarray: provides a np.ndarray of the same length as the data DataFrame/dict: error values are paired with keys matching the key in the plotted DataFrame str: the name of the column within the plotted DataFrame """ if err is None: return None def match_labels(data, e): e = e.reindex(data.index) return e # key-matched DataFrame if isinstance(err, ABCDataFrame): err = match_labels(self.data, err) # key-matched dict elif isinstance(err, dict): pass # Series of error values elif isinstance(err, ABCSeries): # broadcast error series across data err = match_labels(self.data, err) err = np.atleast_2d(err) err = np.tile(err, (self.nseries, 1)) # errors are a column in the dataframe elif isinstance(err, string_types): evalues = self.data[err].values self.data = self.data[self.data.columns.drop(err)] err = np.atleast_2d(evalues) err = np.tile(err, (self.nseries, 1)) elif is_list_like(err): if is_iterator(err): err = np.atleast_2d(list(err)) else: # raw error values err = np.atleast_2d(err) err_shape = err.shape # asymmetrical error bars if err.ndim == 3: if (err_shape[0] != self.nseries) or \ (err_shape[1] != 2) or \ (err_shape[2] != len(self.data)): msg = "Asymmetrical error bars should be provided " + \ "with the shape (%u, 2, %u)" % \ (self.nseries, len(self.data)) raise ValueError(msg) # broadcast errors to each data series if len(err) == 1: err = np.tile(err, (self.nseries, 1)) elif is_number(err): err = np.tile([err], (self.nseries, len(self.data))) else: msg = "No valid {label} detected".format(label=label) raise ValueError(msg) return err def _get_errorbars(self, label=None, index=None, xerr=True, yerr=True): errors = {} for kw, flag in zip(['xerr', 'yerr'], [xerr, yerr]): if flag: err = self.errors[kw] # user provided label-matched dataframe of errors if isinstance(err, (ABCDataFrame, dict)): if label is not None and label in err.keys(): err = err[label] else: err = None elif index is not None and err is not None: err = err[index] if err is not None: errors[kw] = err return errors def _get_subplots(self): from matplotlib.axes import Subplot return [ax for ax in self.axes[0].get_figure().get_axes() if isinstance(ax, Subplot)] def _get_axes_layout(self): axes = self._get_subplots() x_set = set() y_set = set() for ax in axes: # check axes coordinates to estimate layout points = ax.get_position().get_points() x_set.add(points[0][0]) y_set.add(points[0][1]) return (len(y_set), len(x_set)) class PlanePlot(MPLPlot): """ Abstract class for plotting on plane, currently scatter and hexbin. """ _layout_type = 'single' def __init__(self, data, x, y, **kwargs): MPLPlot.__init__(self, data, **kwargs) if x is None or y is None: raise ValueError(self._kind + ' requires an x and y column') if is_integer(x) and not self.data.columns.holds_integer(): x = self.data.columns[x] if is_integer(y) and not self.data.columns.holds_integer(): y = self.data.columns[y] if len(self.data[x]._get_numeric_data()) == 0: raise ValueError(self._kind + ' requires x column to be numeric') if len(self.data[y]._get_numeric_data()) == 0: raise ValueError(self._kind + ' requires y column to be numeric') self.x = x self.y = y @property def nseries(self): return 1 def _post_plot_logic(self, ax, data): x, y = self.x, self.y ax.set_ylabel(pprint_thing(y)) ax.set_xlabel(pprint_thing(x)) def _plot_colorbar(self, ax, **kwds): # Addresses issues #10611 and #10678: # When plotting scatterplots and hexbinplots in IPython # inline backend the colorbar axis height tends not to # exactly match the parent axis height. # The difference is due to small fractional differences # in floating points with similar representation. # To deal with this, this method forces the colorbar # height to take the height of the parent axes. # For a more detailed description of the issue # see the following link: # https://github.com/ipython/ipython/issues/11215 img = ax.collections[0] cbar = self.fig.colorbar(img, ax=ax, **kwds) if _mpl_ge_3_0_0(): # The workaround below is no longer necessary. return points = ax.get_position().get_points() cbar_points = cbar.ax.get_position().get_points() cbar.ax.set_position([cbar_points[0, 0], points[0, 1], cbar_points[1, 0] - cbar_points[0, 0], points[1, 1] - points[0, 1]]) # To see the discrepancy in axis heights uncomment # the following two lines: # print(points[1, 1] - points[0, 1]) # print(cbar_points[1, 1] - cbar_points[0, 1]) class ScatterPlot(PlanePlot): _kind = 'scatter' def __init__(self, data, x, y, s=None, c=None, **kwargs): if s is None: # hide the matplotlib default for size, in case we want to change # the handling of this argument later s = 20 super(ScatterPlot, self).__init__(data, x, y, s=s, **kwargs) if is_integer(c) and not self.data.columns.holds_integer(): c = self.data.columns[c] self.c = c def _make_plot(self): x, y, c, data = self.x, self.y, self.c, self.data ax = self.axes[0] c_is_column = is_hashable(c) and c in self.data.columns # plot a colorbar only if a colormap is provided or necessary cb = self.kwds.pop('colorbar', self.colormap or c_is_column) # pandas uses colormap, matplotlib uses cmap. cmap = self.colormap or 'Greys' cmap = self.plt.cm.get_cmap(cmap) color = self.kwds.pop("color", None) if c is not None and color is not None: raise TypeError('Specify exactly one of `c` and `color`') elif c is None and color is None: c_values = self.plt.rcParams['patch.facecolor'] elif color is not None: c_values = color elif c_is_column: c_values = self.data[c].values else: c_values = c if self.legend and hasattr(self, 'label'): label = self.label else: label = None scatter = ax.scatter(data[x].values, data[y].values, c=c_values, label=label, cmap=cmap, **self.kwds) if cb: cbar_label = c if c_is_column else '' self._plot_colorbar(ax, label=cbar_label) if label is not None: self._add_legend_handle(scatter, label) else: self.legend = False errors_x = self._get_errorbars(label=x, index=0, yerr=False) errors_y = self._get_errorbars(label=y, index=0, xerr=False) if len(errors_x) > 0 or len(errors_y) > 0: err_kwds = dict(errors_x, **errors_y) err_kwds['ecolor'] = scatter.get_facecolor()[0] ax.errorbar(data[x].values, data[y].values, linestyle='none', **err_kwds) class HexBinPlot(PlanePlot): _kind = 'hexbin' def __init__(self, data, x, y, C=None, **kwargs): super(HexBinPlot, self).__init__(data, x, y, **kwargs) if is_integer(C) and not self.data.columns.holds_integer(): C = self.data.columns[C] self.C = C def _make_plot(self): x, y, data, C = self.x, self.y, self.data, self.C ax = self.axes[0] # pandas uses colormap, matplotlib uses cmap. cmap = self.colormap or 'BuGn' cmap = self.plt.cm.get_cmap(cmap) cb = self.kwds.pop('colorbar', True) if C is None: c_values = None else: c_values = data[C].values ax.hexbin(data[x].values, data[y].values, C=c_values, cmap=cmap, **self.kwds) if cb: self._plot_colorbar(ax) def _make_legend(self): pass class LinePlot(MPLPlot): _kind = 'line' _default_rot = 0 orientation = 'vertical' def __init__(self, data, **kwargs): MPLPlot.__init__(self, data, **kwargs) if self.stacked: self.data = self.data.fillna(value=0) self.x_compat = plot_params['x_compat'] if 'x_compat' in self.kwds: self.x_compat = bool(self.kwds.pop('x_compat')) def _is_ts_plot(self): # this is slightly deceptive return not self.x_compat and self.use_index and self._use_dynamic_x() def _use_dynamic_x(self): from pandas.plotting._timeseries import _use_dynamic_x return _use_dynamic_x(self._get_ax(0), self.data) def _make_plot(self): if self._is_ts_plot(): from pandas.plotting._timeseries import _maybe_convert_index data = _maybe_convert_index(self._get_ax(0), self.data) x = data.index # dummy, not used plotf = self._ts_plot it = self._iter_data(data=data, keep_index=True) else: x = self._get_xticks(convert_period=True) plotf = self._plot it = self._iter_data() stacking_id = self._get_stacking_id() is_errorbar = com._any_not_none(*self.errors.values()) colors = self._get_colors() for i, (label, y) in enumerate(it): ax = self._get_ax(i) kwds = self.kwds.copy() style, kwds = self._apply_style_colors(colors, kwds, i, label) errors = self._get_errorbars(label=label, index=i) kwds = dict(kwds, **errors) label = pprint_thing(label) # .encode('utf-8') kwds['label'] = label newlines = plotf(ax, x, y, style=style, column_num=i, stacking_id=stacking_id, is_errorbar=is_errorbar, **kwds) self._add_legend_handle(newlines[0], label, index=i) lines = _get_all_lines(ax) left, right = _get_xlim(lines) ax.set_xlim(left, right) @classmethod def _plot(cls, ax, x, y, style=None, column_num=None, stacking_id=None, **kwds): # column_num is used to get the target column from protf in line and # area plots if column_num == 0: cls._initialize_stacker(ax, stacking_id, len(y)) y_values = cls._get_stacked_values(ax, stacking_id, y, kwds['label']) lines = MPLPlot._plot(ax, x, y_values, style=style, **kwds) cls._update_stacker(ax, stacking_id, y) return lines @classmethod def _ts_plot(cls, ax, x, data, style=None, **kwds): from pandas.plotting._timeseries import (_maybe_resample, _decorate_axes, format_dateaxis) # accept x to be consistent with normal plot func, # x is not passed to tsplot as it uses data.index as x coordinate # column_num must be in kwds for stacking purpose freq, data = _maybe_resample(data, ax, kwds) # Set ax with freq info _decorate_axes(ax, freq, kwds) # digging deeper if hasattr(ax, 'left_ax'): _decorate_axes(ax.left_ax, freq, kwds) if hasattr(ax, 'right_ax'): _decorate_axes(ax.right_ax, freq, kwds) ax._plot_data.append((data, cls._kind, kwds)) lines = cls._plot(ax, data.index, data.values, style=style, **kwds) # set date formatter, locators and rescale limits format_dateaxis(ax, ax.freq, data.index) return lines def _get_stacking_id(self): if self.stacked: return id(self.data) else: return None @classmethod def _initialize_stacker(cls, ax, stacking_id, n): if stacking_id is None: return if not hasattr(ax, '_stacker_pos_prior'): ax._stacker_pos_prior = {} if not hasattr(ax, '_stacker_neg_prior'): ax._stacker_neg_prior = {} ax._stacker_pos_prior[stacking_id] = np.zeros(n) ax._stacker_neg_prior[stacking_id] = np.zeros(n) @classmethod def _get_stacked_values(cls, ax, stacking_id, values, label): if stacking_id is None: return values if not hasattr(ax, '_stacker_pos_prior'): # stacker may not be initialized for subplots cls._initialize_stacker(ax, stacking_id, len(values)) if (values >= 0).all(): return ax._stacker_pos_prior[stacking_id] + values elif (values <= 0).all(): return ax._stacker_neg_prior[stacking_id] + values raise ValueError('When stacked is True, each column must be either ' 'all positive or negative.' '{0} contains both positive and negative values' .format(label)) @classmethod def _update_stacker(cls, ax, stacking_id, values): if stacking_id is None: return if (values >= 0).all(): ax._stacker_pos_prior[stacking_id] += values elif (values <= 0).all(): ax._stacker_neg_prior[stacking_id] += values def _post_plot_logic(self, ax, data): condition = (not self._use_dynamic_x() and data.index.is_all_dates and not self.subplots or (self.subplots and self.sharex)) index_name = self._get_index_name() if condition: # irregular TS rotated 30 deg. by default # probably a better place to check / set this. if not self._rot_set: self.rot = 30 format_date_labels(ax, rot=self.rot) if index_name is not None and self.use_index: ax.set_xlabel(index_name) class AreaPlot(LinePlot): _kind = 'area' def __init__(self, data, **kwargs): kwargs.setdefault('stacked', True) data = data.fillna(value=0) LinePlot.__init__(self, data, **kwargs) if not self.stacked: # use smaller alpha to distinguish overlap self.kwds.setdefault('alpha', 0.5) if self.logy or self.loglog: raise ValueError("Log-y scales are not supported in area plot") @classmethod def _plot(cls, ax, x, y, style=None, column_num=None, stacking_id=None, is_errorbar=False, **kwds): if column_num == 0: cls._initialize_stacker(ax, stacking_id, len(y)) y_values = cls._get_stacked_values(ax, stacking_id, y, kwds['label']) # need to remove label, because subplots uses mpl legend as it is line_kwds = kwds.copy() line_kwds.pop('label') lines = MPLPlot._plot(ax, x, y_values, style=style, **line_kwds) # get data from the line to get coordinates for fill_between xdata, y_values = lines[0].get_data(orig=False) # unable to use ``_get_stacked_values`` here to get starting point if stacking_id is None: start = np.zeros(len(y)) elif (y >= 0).all(): start = ax._stacker_pos_prior[stacking_id] elif (y <= 0).all(): start = ax._stacker_neg_prior[stacking_id] else: start = np.zeros(len(y)) if 'color' not in kwds: kwds['color'] = lines[0].get_color() rect = ax.fill_between(xdata, start, y_values, **kwds) cls._update_stacker(ax, stacking_id, y) # LinePlot expects list of artists res = [rect] return res def _post_plot_logic(self, ax, data): LinePlot._post_plot_logic(self, ax, data) if self.ylim is None: if (data >= 0).all().all(): ax.set_ylim(0, None) elif (data <= 0).all().all(): ax.set_ylim(None, 0) class BarPlot(MPLPlot): _kind = 'bar' _default_rot = 90 orientation = 'vertical' def __init__(self, data, **kwargs): # we have to treat a series differently than a # 1-column DataFrame w.r.t. color handling self._is_series = isinstance(data, ABCSeries) self.bar_width = kwargs.pop('width', 0.5) pos = kwargs.pop('position', 0.5) kwargs.setdefault('align', 'center') self.tick_pos = np.arange(len(data)) self.bottom = kwargs.pop('bottom', 0) self.left = kwargs.pop('left', 0) self.log = kwargs.pop('log', False) MPLPlot.__init__(self, data, **kwargs) if self.stacked or self.subplots: self.tickoffset = self.bar_width * pos if kwargs['align'] == 'edge': self.lim_offset = self.bar_width / 2 else: self.lim_offset = 0 else: if kwargs['align'] == 'edge': w = self.bar_width / self.nseries self.tickoffset = self.bar_width * (pos - 0.5) + w * 0.5 self.lim_offset = w * 0.5 else: self.tickoffset = self.bar_width * pos self.lim_offset = 0 self.ax_pos = self.tick_pos - self.tickoffset def _args_adjust(self): if is_list_like(self.bottom): self.bottom = np.array(self.bottom) if is_list_like(self.left): self.left = np.array(self.left) @classmethod def _plot(cls, ax, x, y, w, start=0, log=False, **kwds): return ax.bar(x, y, w, bottom=start, log=log, **kwds) @property def _start_base(self): return self.bottom def _make_plot(self): import matplotlib as mpl colors = self._get_colors() ncolors = len(colors) pos_prior = neg_prior = np.zeros(len(self.data)) K = self.nseries for i, (label, y) in enumerate(self._iter_data(fillna=0)): ax = self._get_ax(i) kwds = self.kwds.copy() if self._is_series: kwds['color'] = colors else: kwds['color'] = colors[i % ncolors] errors = self._get_errorbars(label=label, index=i) kwds = dict(kwds, **errors) label = pprint_thing(label) if (('yerr' in kwds) or ('xerr' in kwds)) \ and (kwds.get('ecolor') is None): kwds['ecolor'] = mpl.rcParams['xtick.color'] start = 0 if self.log and (y >= 1).all(): start = 1 start = start + self._start_base if self.subplots: w = self.bar_width / 2 rect = self._plot(ax, self.ax_pos + w, y, self.bar_width, start=start, label=label, log=self.log, **kwds) ax.set_title(label) elif self.stacked: mask = y > 0 start = np.where(mask, pos_prior, neg_prior) + self._start_base w = self.bar_width / 2 rect = self._plot(ax, self.ax_pos + w, y, self.bar_width, start=start, label=label, log=self.log, **kwds) pos_prior = pos_prior + np.where(mask, y, 0) neg_prior = neg_prior + np.where(mask, 0, y) else: w = self.bar_width / K rect = self._plot(ax, self.ax_pos + (i + 0.5) * w, y, w, start=start, label=label, log=self.log, **kwds) self._add_legend_handle(rect, label, index=i) def _post_plot_logic(self, ax, data): if self.use_index: str_index = [pprint_thing(key) for key in data.index] else: str_index = [pprint_thing(key) for key in range(data.shape[0])] name = self._get_index_name() s_edge = self.ax_pos[0] - 0.25 + self.lim_offset e_edge = self.ax_pos[-1] + 0.25 + self.bar_width + self.lim_offset self._decorate_ticks(ax, name, str_index, s_edge, e_edge) def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge): ax.set_xlim((start_edge, end_edge)) ax.set_xticks(self.tick_pos) ax.set_xticklabels(ticklabels) if name is not None and self.use_index: ax.set_xlabel(name) class BarhPlot(BarPlot): _kind = 'barh' _default_rot = 0 orientation = 'horizontal' @property def _start_base(self): return self.left @classmethod def _plot(cls, ax, x, y, w, start=0, log=False, **kwds): return ax.barh(x, y, w, left=start, log=log, **kwds) def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge): # horizontal bars ax.set_ylim((start_edge, end_edge)) ax.set_yticks(self.tick_pos) ax.set_yticklabels(ticklabels) if name is not None and self.use_index: ax.set_ylabel(name) class HistPlot(LinePlot): _kind = 'hist' def __init__(self, data, bins=10, bottom=0, **kwargs): self.bins = bins # use mpl default self.bottom = bottom # Do not call LinePlot.__init__ which may fill nan MPLPlot.__init__(self, data, **kwargs) def _args_adjust(self): if is_integer(self.bins): # create common bin edge values = (self.data._convert(datetime=True)._get_numeric_data()) values = np.ravel(values) values = values[~isna(values)] hist, self.bins = np.histogram( values, bins=self.bins, range=self.kwds.get('range', None), weights=self.kwds.get('weights', None)) if is_list_like(self.bottom): self.bottom = np.array(self.bottom) @classmethod def _plot(cls, ax, y, style=None, bins=None, bottom=0, column_num=0, stacking_id=None, **kwds): if column_num == 0: cls._initialize_stacker(ax, stacking_id, len(bins) - 1) y = y[~isna(y)] base = np.zeros(len(bins) - 1) bottom = bottom + \ cls._get_stacked_values(ax, stacking_id, base, kwds['label']) # ignore style n, bins, patches = ax.hist(y, bins=bins, bottom=bottom, **kwds) cls._update_stacker(ax, stacking_id, n) return patches def _make_plot(self): colors = self._get_colors() stacking_id = self._get_stacking_id() for i, (label, y) in enumerate(self._iter_data()): ax = self._get_ax(i) kwds = self.kwds.copy() label = pprint_thing(label) kwds['label'] = label style, kwds = self._apply_style_colors(colors, kwds, i, label) if style is not None: kwds['style'] = style kwds = self._make_plot_keywords(kwds, y) artists = self._plot(ax, y, column_num=i, stacking_id=stacking_id, **kwds) self._add_legend_handle(artists[0], label, index=i) def _make_plot_keywords(self, kwds, y): """merge BoxPlot/KdePlot properties to passed kwds""" # y is required for KdePlot kwds['bottom'] = self.bottom kwds['bins'] = self.bins return kwds def _post_plot_logic(self, ax, data): if self.orientation == 'horizontal': ax.set_xlabel('Frequency') else: ax.set_ylabel('Frequency') @property def orientation(self): if self.kwds.get('orientation', None) == 'horizontal': return 'horizontal' else: return 'vertical' _kde_docstring = """ Generate Kernel Density Estimate plot using Gaussian kernels. In statistics, `kernel density estimation`_ (KDE) is a non-parametric way to estimate the probability density function (PDF) of a random variable. This function uses Gaussian kernels and includes automatic bandwidth determination. .. _kernel density estimation: https://en.wikipedia.org/wiki/Kernel_density_estimation Parameters ---------- bw_method : str, scalar or callable, optional The method used to calculate the estimator bandwidth. This can be 'scott', 'silverman', a scalar constant or a callable. If None (default), 'scott' is used. See :class:`scipy.stats.gaussian_kde` for more information. ind : NumPy array or integer, optional Evaluation points for the estimated PDF. If None (default), 1000 equally spaced points are used. If `ind` is a NumPy array, the KDE is evaluated at the points passed. If `ind` is an integer, `ind` number of equally spaced points are used. **kwds : optional Additional keyword arguments are documented in :meth:`pandas.%(this-datatype)s.plot`. Returns ------- axes : matplotlib.axes.Axes or numpy.ndarray of them See Also -------- scipy.stats.gaussian_kde : Representation of a kernel-density estimate using Gaussian kernels. This is the function used internally to estimate the PDF. %(sibling-datatype)s.plot.kde : Generate a KDE plot for a %(sibling-datatype)s. Examples -------- %(examples)s """ class KdePlot(HistPlot): _kind = 'kde' orientation = 'vertical' def __init__(self, data, bw_method=None, ind=None, **kwargs): MPLPlot.__init__(self, data, **kwargs) self.bw_method = bw_method self.ind = ind def _args_adjust(self): pass def _get_ind(self, y): if self.ind is None: # np.nanmax() and np.nanmin() ignores the missing values sample_range = np.nanmax(y) - np.nanmin(y) ind = np.linspace(np.nanmin(y) - 0.5 * sample_range, np.nanmax(y) + 0.5 * sample_range, 1000) elif is_integer(self.ind): sample_range = np.nanmax(y) - np.nanmin(y) ind = np.linspace(np.nanmin(y) - 0.5 * sample_range, np.nanmax(y) + 0.5 * sample_range, self.ind) else: ind = self.ind return ind @classmethod def _plot(cls, ax, y, style=None, bw_method=None, ind=None, column_num=None, stacking_id=None, **kwds): from scipy.stats import gaussian_kde from scipy import __version__ as spv y = remove_na_arraylike(y) if LooseVersion(spv) >= '0.11.0': gkde = gaussian_kde(y, bw_method=bw_method) else: gkde = gaussian_kde(y) if bw_method is not None: msg = ('bw_method was added in Scipy 0.11.0.' + ' Scipy version in use is {spv}.'.format(spv=spv)) warnings.warn(msg) y = gkde.evaluate(ind) lines = MPLPlot._plot(ax, ind, y, style=style, **kwds) return lines def _make_plot_keywords(self, kwds, y): kwds['bw_method'] = self.bw_method kwds['ind'] = self._get_ind(y) return kwds def _post_plot_logic(self, ax, data): ax.set_ylabel('Density') class PiePlot(MPLPlot): _kind = 'pie' _layout_type = 'horizontal' def __init__(self, data, kind=None, **kwargs): data = data.fillna(value=0) if (data < 0).any().any(): raise ValueError("{0} doesn't allow negative values".format(kind)) MPLPlot.__init__(self, data, kind=kind, **kwargs) def _args_adjust(self): self.grid = False self.logy = False self.logx = False self.loglog = False def _validate_color_args(self): pass def _make_plot(self): colors = self._get_colors( num_colors=len(self.data), color_kwds='colors') self.kwds.setdefault('colors', colors) for i, (label, y) in enumerate(self._iter_data()): ax = self._get_ax(i) if label is not None: label = pprint_thing(label) ax.set_ylabel(label) kwds = self.kwds.copy() def blank_labeler(label, value): if value == 0: return '' else: return label idx = [pprint_thing(v) for v in self.data.index] labels = kwds.pop('labels', idx) # labels is used for each wedge's labels # Blank out labels for values of 0 so they don't overlap # with nonzero wedges if labels is not None: blabels = [blank_labeler(l, value) for l, value in zip(labels, y)] else: blabels = None results = ax.pie(y, labels=blabels, **kwds) if kwds.get('autopct', None) is not None: patches, texts, autotexts = results else: patches, texts = results autotexts = [] if self.fontsize is not None: for t in texts + autotexts: t.set_fontsize(self.fontsize) # leglabels is used for legend labels leglabels = labels if labels is not None else idx for p, l in zip(patches, leglabels): self._add_legend_handle(p, l) class BoxPlot(LinePlot): _kind = 'box' _layout_type = 'horizontal' _valid_return_types = (None, 'axes', 'dict', 'both') # namedtuple to hold results BP = namedtuple("Boxplot", ['ax', 'lines']) def __init__(self, data, return_type='axes', **kwargs): # Do not call LinePlot.__init__ which may fill nan if return_type not in self._valid_return_types: raise ValueError( "return_type must be {None, 'axes', 'dict', 'both'}") self.return_type = return_type MPLPlot.__init__(self, data, **kwargs) def _args_adjust(self): if self.subplots: # Disable label ax sharing. Otherwise, all subplots shows last # column label if self.orientation == 'vertical': self.sharex = False else: self.sharey = False @classmethod def _plot(cls, ax, y, column_num=None, return_type='axes', **kwds): if y.ndim == 2: y = [remove_na_arraylike(v) for v in y] # Boxplot fails with empty arrays, so need to add a NaN # if any cols are empty # GH 8181 y = [v if v.size > 0 else np.array([np.nan]) for v in y] else: y = remove_na_arraylike(y) bp = ax.boxplot(y, **kwds) if return_type == 'dict': return bp, bp elif return_type == 'both': return cls.BP(ax=ax, lines=bp), bp else: return ax, bp def _validate_color_args(self): if 'color' in self.kwds: if self.colormap is not None: warnings.warn("'color' and 'colormap' cannot be used " "simultaneously. Using 'color'") self.color = self.kwds.pop('color') if isinstance(self.color, dict): valid_keys = ['boxes', 'whiskers', 'medians', 'caps'] for key, values in compat.iteritems(self.color): if key not in valid_keys: raise ValueError("color dict contains invalid " "key '{0}' " "The key must be either {1}" .format(key, valid_keys)) else: self.color = None # get standard colors for default colors = _get_standard_colors(num_colors=3, colormap=self.colormap, color=None) # use 2 colors by default, for box/whisker and median # flier colors isn't needed here # because it can be specified by ``sym`` kw self._boxes_c = colors[0] self._whiskers_c = colors[0] self._medians_c = colors[2] self._caps_c = 'k' # mpl default def _get_colors(self, num_colors=None, color_kwds='color'): pass def maybe_color_bp(self, bp): if isinstance(self.color, dict): boxes = self.color.get('boxes', self._boxes_c) whiskers = self.color.get('whiskers', self._whiskers_c) medians = self.color.get('medians', self._medians_c) caps = self.color.get('caps', self._caps_c) else: # Other types are forwarded to matplotlib # If None, use default colors boxes = self.color or self._boxes_c whiskers = self.color or self._whiskers_c medians = self.color or self._medians_c caps = self.color or self._caps_c from matplotlib.artist import setp setp(bp['boxes'], color=boxes, alpha=1) setp(bp['whiskers'], color=whiskers, alpha=1) setp(bp['medians'], color=medians, alpha=1) setp(bp['caps'], color=caps, alpha=1) def _make_plot(self): if self.subplots: from pandas.core.series import Series self._return_obj = Series() for i, (label, y) in enumerate(self._iter_data()): ax = self._get_ax(i) kwds = self.kwds.copy() ret, bp = self._plot(ax, y, column_num=i, return_type=self.return_type, **kwds) self.maybe_color_bp(bp) self._return_obj[label] = ret label = [pprint_thing(label)] self._set_ticklabels(ax, label) else: y = self.data.values.T ax = self._get_ax(0) kwds = self.kwds.copy() ret, bp = self._plot(ax, y, column_num=0, return_type=self.return_type, **kwds) self.maybe_color_bp(bp) self._return_obj = ret labels = [l for l, _ in self._iter_data()] labels = [pprint_thing(l) for l in labels] if not self.use_index: labels = [pprint_thing(key) for key in range(len(labels))] self._set_ticklabels(ax, labels) def _set_ticklabels(self, ax, labels): if self.orientation == 'vertical': ax.set_xticklabels(labels) else: ax.set_yticklabels(labels) def _make_legend(self): pass def _post_plot_logic(self, ax, data): pass @property def orientation(self): if self.kwds.get('vert', True): return 'vertical' else: return 'horizontal' @property def result(self): if self.return_type is None: return super(BoxPlot, self).result else: return self._return_obj # kinds supported by both dataframe and series _common_kinds = ['line', 'bar', 'barh', 'kde', 'density', 'area', 'hist', 'box'] # kinds supported by dataframe _dataframe_kinds = ['scatter', 'hexbin'] # kinds supported only by series or dataframe single column _series_kinds = ['pie'] _all_kinds = _common_kinds + _dataframe_kinds + _series_kinds _klasses = [LinePlot, BarPlot, BarhPlot, KdePlot, HistPlot, BoxPlot, ScatterPlot, HexBinPlot, AreaPlot, PiePlot] _plot_klass = {} for klass in _klasses: _plot_klass[klass._kind] = klass def _plot(data, x=None, y=None, subplots=False, ax=None, kind='line', **kwds): kind = _get_standard_kind(kind.lower().strip()) if kind in _all_kinds: klass = _plot_klass[kind] else: raise ValueError("%r is not a valid plot kind" % kind) if kind in _dataframe_kinds: if isinstance(data, ABCDataFrame): plot_obj = klass(data, x=x, y=y, subplots=subplots, ax=ax, kind=kind, **kwds) else: raise ValueError("plot kind %r can only be used for data frames" % kind) elif kind in _series_kinds: if isinstance(data, ABCDataFrame): if y is None and subplots is False: msg = "{0} requires either y column or 'subplots=True'" raise ValueError(msg.format(kind)) elif y is not None: if is_integer(y) and not data.columns.holds_integer(): y = data.columns[y] # converted to series actually. copy to not modify data = data[y].copy() data.index.name = y plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds) else: if isinstance(data, ABCDataFrame): data_cols = data.columns if x is not None: if is_integer(x) and not data.columns.holds_integer(): x = data_cols[x] elif not isinstance(data[x], ABCSeries): raise ValueError("x must be a label or position") data = data.set_index(x) if y is not None: # check if we have y as int or list of ints int_ylist = is_list_like(y) and all(is_integer(c) for c in y) int_y_arg = is_integer(y) or int_ylist if int_y_arg and not data.columns.holds_integer(): y = data_cols[y] label_kw = kwds['label'] if 'label' in kwds else False for kw in ['xerr', 'yerr']: if (kw in kwds) and \ (isinstance(kwds[kw], string_types) or is_integer(kwds[kw])): try: kwds[kw] = data[kwds[kw]] except (IndexError, KeyError, TypeError): pass # don't overwrite data = data[y].copy() if isinstance(data, ABCSeries): label_name = label_kw or y data.name = label_name else: match = is_list_like(label_kw) and len(label_kw) == len(y) if label_kw and not match: raise ValueError( "label should be list-like and same length as y" ) label_name = label_kw or data.columns data.columns = label_name plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds) plot_obj.generate() plot_obj.draw() return plot_obj.result df_kind = """- 'scatter' : scatter plot - 'hexbin' : hexbin plot""" series_kind = "" df_coord = """x : label or position, default None y : label, position or list of label, positions, default None Allows plotting of one column versus another""" series_coord = "" df_unique = """stacked : boolean, default False in line and bar plots, and True in area plot. If True, create stacked plot. sort_columns : boolean, default False Sort column names to determine plot ordering secondary_y : boolean or sequence, default False Whether to plot on the secondary y-axis If a list/tuple, which columns to plot on secondary y-axis""" series_unique = """label : label argument to provide to plot secondary_y : boolean or sequence of ints, default False If True then y-axis will be on the right""" df_ax = """ax : matplotlib axes object, default None subplots : boolean, default False Make separate subplots for each column sharex : boolean, default True if ax is None else False In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in; Be aware, that passing in both an ax and sharex=True will alter all x axis labels for all axis in a figure! sharey : boolean, default False In case subplots=True, share y axis and set some y axis labels to invisible layout : tuple (optional) (rows, columns) for the layout of subplots""" series_ax = """ax : matplotlib axes object If not passed, uses gca()""" df_note = """- If `kind` = 'scatter' and the argument `c` is the name of a dataframe column, the values of that column are used to color each point. - If `kind` = 'hexbin', you can control the size of the bins with the `gridsize` argument. By default, a histogram of the counts around each `(x, y)` point is computed. You can specify alternative aggregations by passing values to the `C` and `reduce_C_function` arguments. `C` specifies the value at each `(x, y)` point and `reduce_C_function` is a function of one argument that reduces all the values in a bin to a single number (e.g. `mean`, `max`, `sum`, `std`).""" series_note = "" _shared_doc_df_kwargs = dict(klass='DataFrame', klass_obj='df', klass_kind=df_kind, klass_coord=df_coord, klass_ax=df_ax, klass_unique=df_unique, klass_note=df_note) _shared_doc_series_kwargs = dict(klass='Series', klass_obj='s', klass_kind=series_kind, klass_coord=series_coord, klass_ax=series_ax, klass_unique=series_unique, klass_note=series_note) _shared_docs['plot'] = """ Make plots of %(klass)s using matplotlib / pylab. *New in version 0.17.0:* Each plot kind has a corresponding method on the ``%(klass)s.plot`` accessor: ``%(klass_obj)s.plot(kind='line')`` is equivalent to ``%(klass_obj)s.plot.line()``. Parameters ---------- data : %(klass)s %(klass_coord)s kind : str - 'line' : line plot (default) - 'bar' : vertical bar plot - 'barh' : horizontal bar plot - 'hist' : histogram - 'box' : boxplot - 'kde' : Kernel Density Estimation plot - 'density' : same as 'kde' - 'area' : area plot - 'pie' : pie plot %(klass_kind)s %(klass_ax)s figsize : a tuple (width, height) in inches use_index : boolean, default True Use index as ticks for x axis title : string or list Title to use for the plot. If a string is passed, print the string at the top of the figure. If a list is passed and `subplots` is True, print each item in the list above the corresponding subplot. grid : boolean, default None (matlab style default) Axis grid lines legend : False/True/'reverse' Place legend on axis subplots style : list or dict matplotlib line style per column logx : boolean, default False Use log scaling on x axis logy : boolean, default False Use log scaling on y axis loglog : boolean, default False Use log scaling on both x and y axes xticks : sequence Values to use for the xticks yticks : sequence Values to use for the yticks xlim : 2-tuple/list ylim : 2-tuple/list rot : int, default None Rotation for ticks (xticks for vertical, yticks for horizontal plots) fontsize : int, default None Font size for xticks and yticks colormap : str or matplotlib colormap object, default None Colormap to select colors from. If string, load colormap with that name from matplotlib. colorbar : boolean, optional If True, plot colorbar (only relevant for 'scatter' and 'hexbin' plots) position : float Specify relative alignments for bar plot layout. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center) table : boolean, Series or DataFrame, default False If True, draw a table using the data in the DataFrame and the data will be transposed to meet matplotlib's default layout. If a Series or DataFrame is passed, use passed data to draw a table. yerr : DataFrame, Series, array-like, dict and str See :ref:`Plotting with Error Bars <visualization.errorbars>` for detail. xerr : same types as yerr. %(klass_unique)s mark_right : boolean, default True When using a secondary_y axis, automatically mark the column labels with "(right)" in the legend `**kwds` : keywords Options to pass to matplotlib plotting method Returns ------- axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them Notes ----- - See matplotlib documentation online for more on this subject - If `kind` = 'bar' or 'barh', you can specify relative alignments for bar plot layout by `position` keyword. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center) %(klass_note)s """ @Appender(_shared_docs['plot'] % _shared_doc_df_kwargs) def plot_frame(data, x=None, y=None, kind='line', ax=None, subplots=False, sharex=None, sharey=False, layout=None, figsize=None, use_index=True, title=None, grid=None, legend=True, style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None, rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, secondary_y=False, sort_columns=False, **kwds): return _plot(data, kind=kind, x=x, y=y, ax=ax, subplots=subplots, sharex=sharex, sharey=sharey, layout=layout, figsize=figsize, use_index=use_index, title=title, grid=grid, legend=legend, style=style, logx=logx, logy=logy, loglog=loglog, xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim, rot=rot, fontsize=fontsize, colormap=colormap, table=table, yerr=yerr, xerr=xerr, secondary_y=secondary_y, sort_columns=sort_columns, **kwds) @Appender(_shared_docs['plot'] % _shared_doc_series_kwargs) def plot_series(data, kind='line', ax=None, # Series unique figsize=None, use_index=True, title=None, grid=None, legend=False, style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None, rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, label=None, secondary_y=False, # Series unique **kwds): import matplotlib.pyplot as plt if ax is None and len(plt.get_fignums()) > 0: ax = _gca() ax = MPLPlot._get_ax_layer(ax) return _plot(data, kind=kind, ax=ax, figsize=figsize, use_index=use_index, title=title, grid=grid, legend=legend, style=style, logx=logx, logy=logy, loglog=loglog, xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim, rot=rot, fontsize=fontsize, colormap=colormap, table=table, yerr=yerr, xerr=xerr, label=label, secondary_y=secondary_y, **kwds) _shared_docs['boxplot'] = """ Make a box plot from DataFrame columns. Make a box-and-whisker plot from DataFrame columns, optionally grouped by some other columns. A box plot is a method for graphically depicting groups of numerical data through their quartiles. The box extends from the Q1 to Q3 quartile values of the data, with a line at the median (Q2). The whiskers extend from the edges of box to show the range of the data. The position of the whiskers is set by default to `1.5 * IQR (IQR = Q3 - Q1)` from the edges of the box. Outlier points are those past the end of the whiskers. For further details see Wikipedia's entry for `boxplot <https://en.wikipedia.org/wiki/Box_plot>`_. Parameters ---------- column : str or list of str, optional Column name or list of names, or vector. Can be any valid input to :meth:`pandas.DataFrame.groupby`. by : str or array-like, optional Column in the DataFrame to :meth:`pandas.DataFrame.groupby`. One box-plot will be done per value of columns in `by`. ax : object of class matplotlib.axes.Axes, optional The matplotlib axes to be used by boxplot. fontsize : float or str Tick label font size in points or as a string (e.g., `large`). rot : int or float, default 0 The rotation angle of labels (in degrees) with respect to the screen coordinate system. grid : boolean, default True Setting this to True will show the grid. figsize : A tuple (width, height) in inches The size of the figure to create in matplotlib. layout : tuple (rows, columns), optional For example, (3, 5) will display the subplots using 3 columns and 5 rows, starting from the top-left. return_type : {'axes', 'dict', 'both'} or None, default 'axes' The kind of object to return. The default is ``axes``. * 'axes' returns the matplotlib axes the boxplot is drawn on. * 'dict' returns a dictionary whose values are the matplotlib Lines of the boxplot. * 'both' returns a namedtuple with the axes and dict. * when grouping with ``by``, a Series mapping columns to ``return_type`` is returned. If ``return_type`` is `None`, a NumPy array of axes with the same shape as ``layout`` is returned. **kwds All other plotting keyword arguments to be passed to :func:`matplotlib.pyplot.boxplot`. Returns ------- result : The return type depends on the `return_type` parameter: * 'axes' : object of class matplotlib.axes.Axes * 'dict' : dict of matplotlib.lines.Line2D objects * 'both' : a namedtuple with structure (ax, lines) For data grouped with ``by``: * :class:`~pandas.Series` * :class:`~numpy.array` (for ``return_type = None``) See Also -------- Series.plot.hist: Make a histogram. matplotlib.pyplot.boxplot : Matplotlib equivalent plot. Notes ----- Use ``return_type='dict'`` when you want to tweak the appearance of the lines after plotting. In this case a dict containing the Lines making up the boxes, caps, fliers, medians, and whiskers is returned. Examples -------- Boxplots can be created for every column in the dataframe by ``df.boxplot()`` or indicating the columns to be used: .. plot:: :context: close-figs >>> np.random.seed(1234) >>> df = pd.DataFrame(np.random.randn(10,4), ... columns=['Col1', 'Col2', 'Col3', 'Col4']) >>> boxplot = df.boxplot(column=['Col1', 'Col2', 'Col3']) Boxplots of variables distributions grouped by the values of a third variable can be created using the option ``by``. For instance: .. plot:: :context: close-figs >>> df = pd.DataFrame(np.random.randn(10, 2), ... columns=['Col1', 'Col2']) >>> df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A', ... 'B', 'B', 'B', 'B', 'B']) >>> boxplot = df.boxplot(by='X') A list of strings (i.e. ``['X', 'Y']``) can be passed to boxplot in order to group the data by combination of the variables in the x-axis: .. plot:: :context: close-figs >>> df = pd.DataFrame(np.random.randn(10,3), ... columns=['Col1', 'Col2', 'Col3']) >>> df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A', ... 'B', 'B', 'B', 'B', 'B']) >>> df['Y'] = pd.Series(['A', 'B', 'A', 'B', 'A', ... 'B', 'A', 'B', 'A', 'B']) >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by=['X', 'Y']) The layout of boxplot can be adjusted giving a tuple to ``layout``: .. plot:: :context: close-figs >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X', ... layout=(2, 1)) Additional formatting can be done to the boxplot, like suppressing the grid (``grid=False``), rotating the labels in the x-axis (i.e. ``rot=45``) or changing the fontsize (i.e. ``fontsize=15``): .. plot:: :context: close-figs >>> boxplot = df.boxplot(grid=False, rot=45, fontsize=15) The parameter ``return_type`` can be used to select the type of element returned by `boxplot`. When ``return_type='axes'`` is selected, the matplotlib axes on which the boxplot is drawn are returned: >>> boxplot = df.boxplot(column=['Col1','Col2'], return_type='axes') >>> type(boxplot) <class 'matplotlib.axes._subplots.AxesSubplot'> When grouping with ``by``, a Series mapping columns to ``return_type`` is returned: >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X', ... return_type='axes') >>> type(boxplot) <class 'pandas.core.series.Series'> If ``return_type`` is `None`, a NumPy array of axes with the same shape as ``layout`` is returned: >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X', ... return_type=None) >>> type(boxplot) <class 'numpy.ndarray'> """ @Appender(_shared_docs['boxplot'] % _shared_doc_kwargs) def boxplot(data, column=None, by=None, ax=None, fontsize=None, rot=0, grid=True, figsize=None, layout=None, return_type=None, **kwds): # validate return_type: if return_type not in BoxPlot._valid_return_types: raise ValueError("return_type must be {'axes', 'dict', 'both'}") if isinstance(data, ABCSeries): data = data.to_frame('x') column = 'x' def _get_colors(): return _get_standard_colors(color=kwds.get('color'), num_colors=1) def maybe_color_bp(bp): if 'color' not in kwds: from matplotlib.artist import setp setp(bp['boxes'], color=colors[0], alpha=1) setp(bp['whiskers'], color=colors[0], alpha=1) setp(bp['medians'], color=colors[2], alpha=1) def plot_group(keys, values, ax): keys = [pprint_thing(x) for x in keys] values = [np.asarray(remove_na_arraylike(v)) for v in values] bp = ax.boxplot(values, **kwds) if fontsize is not None: ax.tick_params(axis='both', labelsize=fontsize) if kwds.get('vert', 1): ax.set_xticklabels(keys, rotation=rot) else: ax.set_yticklabels(keys, rotation=rot) maybe_color_bp(bp) # Return axes in multiplot case, maybe revisit later # 985 if return_type == 'dict': return bp elif return_type == 'both': return BoxPlot.BP(ax=ax, lines=bp) else: return ax colors = _get_colors() if column is None: columns = None else: if isinstance(column, (list, tuple)): columns = column else: columns = [column] if by is not None: # Prefer array return type for 2-D plots to match the subplot layout # https://github.com/pandas-dev/pandas/pull/12216#issuecomment-241175580 result = _grouped_plot_by_column(plot_group, data, columns=columns, by=by, grid=grid, figsize=figsize, ax=ax, layout=layout, return_type=return_type) else: if return_type is None: return_type = 'axes' if layout is not None: raise ValueError("The 'layout' keyword is not supported when " "'by' is None") if ax is None: rc = {'figure.figsize': figsize} if figsize is not None else {} ax = _gca(rc) data = data._get_numeric_data() if columns is None: columns = data.columns else: data = data[columns] result = plot_group(columns, data.values.T, ax) ax.grid(grid) return result @Appender(_shared_docs['boxplot'] % _shared_doc_kwargs) def boxplot_frame(self, column=None, by=None, ax=None, fontsize=None, rot=0, grid=True, figsize=None, layout=None, return_type=None, **kwds): import matplotlib.pyplot as plt _converter._WARN = False ax = boxplot(self, column=column, by=by, ax=ax, fontsize=fontsize, grid=grid, rot=rot, figsize=figsize, layout=layout, return_type=return_type, **kwds) plt.draw_if_interactive() return ax def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False, **kwargs): """ Make a scatter plot from two DataFrame columns Parameters ---------- data : DataFrame x : Column name for the x-axis values y : Column name for the y-axis values ax : Matplotlib axis object figsize : A tuple (width, height) in inches grid : Setting this to True will show the grid kwargs : other plotting keyword arguments To be passed to scatter function Returns ------- fig : matplotlib.Figure """ import matplotlib.pyplot as plt kwargs.setdefault('edgecolors', 'none') def plot_group(group, ax): xvals = group[x].values yvals = group[y].values ax.scatter(xvals, yvals, **kwargs) ax.grid(grid) if by is not None: fig = _grouped_plot(plot_group, data, by=by, figsize=figsize, ax=ax) else: if ax is None: fig = plt.figure() ax = fig.add_subplot(111) else: fig = ax.get_figure() plot_group(data, ax) ax.set_ylabel(pprint_thing(y)) ax.set_xlabel(pprint_thing(x)) ax.grid(grid) return fig def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, bins=10, **kwds): """ Make a histogram of the DataFrame's. A `histogram`_ is a representation of the distribution of data. This function calls :meth:`matplotlib.pyplot.hist`, on each series in the DataFrame, resulting in one histogram per column. .. _histogram: https://en.wikipedia.org/wiki/Histogram Parameters ---------- data : DataFrame The pandas object holding the data. column : string or sequence If passed, will be used to limit data to a subset of columns. by : object, optional If passed, then used to form histograms for separate groups. grid : boolean, default True Whether to show axis grid lines. xlabelsize : int, default None If specified changes the x-axis label size. xrot : float, default None Rotation of x axis labels. For example, a value of 90 displays the x labels rotated 90 degrees clockwise. ylabelsize : int, default None If specified changes the y-axis label size. yrot : float, default None Rotation of y axis labels. For example, a value of 90 displays the y labels rotated 90 degrees clockwise. ax : Matplotlib axes object, default None The axes to plot the histogram on. sharex : boolean, default True if ax is None else False In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in. Note that passing in both an ax and sharex=True will alter all x axis labels for all subplots in a figure. sharey : boolean, default False In case subplots=True, share y axis and set some y axis labels to invisible. figsize : tuple The size in inches of the figure to create. Uses the value in `matplotlib.rcParams` by default. layout : tuple, optional Tuple of (rows, columns) for the layout of the histograms. bins : integer or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. **kwds All other plotting keyword arguments to be passed to :meth:`matplotlib.pyplot.hist`. Returns ------- axes : matplotlib.AxesSubplot or numpy.ndarray of them See Also -------- matplotlib.pyplot.hist : Plot a histogram using matplotlib. Examples -------- .. plot:: :context: close-figs This example draws a histogram based on the length and width of some animals, displayed in three bins >>> df = pd.DataFrame({ ... 'length': [1.5, 0.5, 1.2, 0.9, 3], ... 'width': [0.7, 0.2, 0.15, 0.2, 1.1] ... }, index= ['pig', 'rabbit', 'duck', 'chicken', 'horse']) >>> hist = df.hist(bins=3) """ _raise_if_no_mpl() _converter._WARN = False if by is not None: axes = grouped_hist(data, column=column, by=by, ax=ax, grid=grid, figsize=figsize, sharex=sharex, sharey=sharey, layout=layout, bins=bins, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot, **kwds) return axes if column is not None: if not isinstance(column, (list, np.ndarray, ABCIndexClass)): column = [column] data = data[column] data = data._get_numeric_data() naxes = len(data.columns) fig, axes = _subplots(naxes=naxes, ax=ax, squeeze=False, sharex=sharex, sharey=sharey, figsize=figsize, layout=layout) _axes = _flatten(axes) for i, col in enumerate(com.try_sort(data.columns)): ax = _axes[i] ax.hist(data[col].dropna().values, bins=bins, **kwds) ax.set_title(col) ax.grid(grid) _set_ticks_props(axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot) fig.subplots_adjust(wspace=0.3, hspace=0.3) return axes def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, figsize=None, bins=10, **kwds): """ Draw histogram of the input series using matplotlib Parameters ---------- by : object, optional If passed, then used to form histograms for separate groups ax : matplotlib axis object If not passed, uses gca() grid : boolean, default True Whether to show axis grid lines xlabelsize : int, default None If specified changes the x-axis label size xrot : float, default None rotation of x axis labels ylabelsize : int, default None If specified changes the y-axis label size yrot : float, default None rotation of y axis labels figsize : tuple, default None figure size in inches by default bins : integer or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. bins: integer, default 10 Number of histogram bins to be used `**kwds` : keywords To be passed to the actual plotting function See Also -------- matplotlib.axes.Axes.hist : Plot a histogram using matplotlib. """ import matplotlib.pyplot as plt if by is None: if kwds.get('layout', None) is not None: raise ValueError("The 'layout' keyword is not supported when " "'by' is None") # hack until the plotting interface is a bit more unified fig = kwds.pop('figure', plt.gcf() if plt.get_fignums() else plt.figure(figsize=figsize)) if (figsize is not None and tuple(figsize) != tuple(fig.get_size_inches())): fig.set_size_inches(*figsize, forward=True) if ax is None: ax = fig.gca() elif ax.get_figure() != fig: raise AssertionError('passed axis not bound to passed figure') values = self.dropna().values ax.hist(values, bins=bins, **kwds) ax.grid(grid) axes = np.array([ax]) _set_ticks_props(axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot) else: if 'figure' in kwds: raise ValueError("Cannot pass 'figure' when using the " "'by' argument, since a new 'Figure' instance " "will be created") axes = grouped_hist(self, by=by, ax=ax, grid=grid, figsize=figsize, bins=bins, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot, **kwds) if hasattr(axes, 'ndim'): if axes.ndim == 1 and len(axes) == 1: return axes[0] return axes def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None, layout=None, sharex=False, sharey=False, rot=90, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, **kwargs): """ Grouped histogram Parameters ---------- data: Series/DataFrame column: object, optional by: object, optional ax: axes, optional bins: int, default 50 figsize: tuple, optional layout: optional sharex: boolean, default False sharey: boolean, default False rot: int, default 90 grid: bool, default True kwargs: dict, keyword arguments passed to matplotlib.Axes.hist Returns ------- axes: collection of Matplotlib Axes """ _raise_if_no_mpl() _converter._WARN = False def plot_group(group, ax): ax.hist(group.dropna().values, bins=bins, **kwargs) xrot = xrot or rot fig, axes = _grouped_plot(plot_group, data, column=column, by=by, sharex=sharex, sharey=sharey, ax=ax, figsize=figsize, layout=layout, rot=rot) _set_ticks_props(axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot) fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, hspace=0.5, wspace=0.3) return axes def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None, rot=0, grid=True, ax=None, figsize=None, layout=None, sharex=False, sharey=True, **kwds): """ Make box plots from DataFrameGroupBy data. Parameters ---------- grouped : Grouped DataFrame subplots : * ``False`` - no subplots will be used * ``True`` - create a subplot for each group column : column name or list of names, or vector Can be any valid input to groupby fontsize : int or string rot : label rotation angle grid : Setting this to True will show the grid ax : Matplotlib axis object, default None figsize : A tuple (width, height) in inches layout : tuple (optional) (rows, columns) for the layout of the plot sharex : bool, default False Whether x-axes will be shared among subplots .. versionadded:: 0.23.1 sharey : bool, default True Whether y-axes will be shared among subplots .. versionadded:: 0.23.1 `**kwds` : Keyword Arguments All other plotting keyword arguments to be passed to matplotlib's boxplot function Returns ------- dict of key/value = group key/DataFrame.boxplot return value or DataFrame.boxplot return value in case subplots=figures=False Examples -------- >>> import itertools >>> tuples = [t for t in itertools.product(range(1000), range(4))] >>> index = pd.MultiIndex.from_tuples(tuples, names=['lvl0', 'lvl1']) >>> data = np.random.randn(len(index),4) >>> df = pd.DataFrame(data, columns=list('ABCD'), index=index) >>> >>> grouped = df.groupby(level='lvl1') >>> boxplot_frame_groupby(grouped) >>> >>> grouped = df.unstack(level='lvl1').groupby(level=0, axis=1) >>> boxplot_frame_groupby(grouped, subplots=False) """ _raise_if_no_mpl() _converter._WARN = False if subplots is True: naxes = len(grouped) fig, axes = _subplots(naxes=naxes, squeeze=False, ax=ax, sharex=sharex, sharey=sharey, figsize=figsize, layout=layout) axes = _flatten(axes) from pandas.core.series import Series ret = Series() for (key, group), ax in zip(grouped, axes): d = group.boxplot(ax=ax, column=column, fontsize=fontsize, rot=rot, grid=grid, **kwds) ax.set_title(pprint_thing(key)) ret.loc[key] = d fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2) else: from pandas.core.reshape.concat import concat keys, frames = zip(*grouped) if grouped.axis == 0: df = concat(frames, keys=keys, axis=1) else: if len(frames) > 1: df = frames[0].join(frames[1::]) else: df = frames[0] ret = df.boxplot(column=column, fontsize=fontsize, rot=rot, grid=grid, ax=ax, figsize=figsize, layout=layout, **kwds) return ret def _grouped_plot(plotf, data, column=None, by=None, numeric_only=True, figsize=None, sharex=True, sharey=True, layout=None, rot=0, ax=None, **kwargs): if figsize == 'default': # allowed to specify mpl default with 'default' warnings.warn("figsize='default' is deprecated. Specify figure" "size by tuple instead", FutureWarning, stacklevel=4) figsize = None grouped = data.groupby(by) if column is not None: grouped = grouped[column] naxes = len(grouped) fig, axes = _subplots(naxes=naxes, figsize=figsize, sharex=sharex, sharey=sharey, ax=ax, layout=layout) _axes = _flatten(axes) for i, (key, group) in enumerate(grouped): ax = _axes[i] if numeric_only and isinstance(group, ABCDataFrame): group = group._get_numeric_data() plotf(group, ax, **kwargs) ax.set_title(pprint_thing(key)) return fig, axes def _grouped_plot_by_column(plotf, data, columns=None, by=None, numeric_only=True, grid=False, figsize=None, ax=None, layout=None, return_type=None, **kwargs): grouped = data.groupby(by) if columns is None: if not isinstance(by, (list, tuple)): by = [by] columns = data._get_numeric_data().columns.difference(by) naxes = len(columns) fig, axes = _subplots(naxes=naxes, sharex=True, sharey=True, figsize=figsize, ax=ax, layout=layout) _axes = _flatten(axes) ax_values = [] for i, col in enumerate(columns): ax = _axes[i] gp_col = grouped[col] keys, values = zip(*gp_col) re_plotf = plotf(keys, values, ax, **kwargs) ax.set_title(col) ax.set_xlabel(pprint_thing(by)) ax_values.append(re_plotf) ax.grid(grid) from pandas.core.series import Series result = Series(ax_values, index=columns) # Return axes in multiplot case, maybe revisit later # 985 if return_type is None: result = axes byline = by[0] if len(by) == 1 else by fig.suptitle('Boxplot grouped by {byline}'.format(byline=byline)) fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2) return result class BasePlotMethods(PandasObject): def __init__(self, data): self._parent = data # can be Series or DataFrame def __call__(self, *args, **kwargs): raise NotImplementedError class SeriesPlotMethods(BasePlotMethods): """Series plotting accessor and method Examples -------- >>> s.plot.line() >>> s.plot.bar() >>> s.plot.hist() Plotting methods can also be accessed by calling the accessor as a method with the ``kind`` argument: ``s.plot(kind='line')`` is equivalent to ``s.plot.line()`` """ def __call__(self, kind='line', ax=None, figsize=None, use_index=True, title=None, grid=None, legend=False, style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None, rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, label=None, secondary_y=False, **kwds): return plot_series(self._parent, kind=kind, ax=ax, figsize=figsize, use_index=use_index, title=title, grid=grid, legend=legend, style=style, logx=logx, logy=logy, loglog=loglog, xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim, rot=rot, fontsize=fontsize, colormap=colormap, table=table, yerr=yerr, xerr=xerr, label=label, secondary_y=secondary_y, **kwds) __call__.__doc__ = plot_series.__doc__ def line(self, **kwds): """ Line plot Parameters ---------- `**kwds` : optional Additional keyword arguments are documented in :meth:`pandas.Series.plot`. Returns ------- axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them Examples -------- .. plot:: :context: close-figs >>> s = pd.Series([1, 3, 2]) >>> s.plot.line() """ return self(kind='line', **kwds) def bar(self, **kwds): """ Vertical bar plot Parameters ---------- `**kwds` : optional Additional keyword arguments are documented in :meth:`pandas.Series.plot`. Returns ------- axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them """ return self(kind='bar', **kwds) def barh(self, **kwds): """ Horizontal bar plot Parameters ---------- `**kwds` : optional Additional keyword arguments are documented in :meth:`pandas.Series.plot`. Returns ------- axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them """ return self(kind='barh', **kwds) def box(self, **kwds): """ Boxplot Parameters ---------- `**kwds` : optional Additional keyword arguments are documented in :meth:`pandas.Series.plot`. Returns ------- axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them """ return self(kind='box', **kwds) def hist(self, bins=10, **kwds): """ Histogram Parameters ---------- bins: integer, default 10 Number of histogram bins to be used `**kwds` : optional Additional keyword arguments are documented in :meth:`pandas.Series.plot`. Returns ------- axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them """ return self(kind='hist', bins=bins, **kwds) @Appender(_kde_docstring % { 'this-datatype': 'Series', 'sibling-datatype': 'DataFrame', 'examples': """ Given a Series of points randomly sampled from an unknown distribution, estimate its PDF using KDE with automatic bandwidth determination and plot the results, evaluating them at 1000 equally spaced points (default): .. plot:: :context: close-figs >>> s = pd.Series([1, 2, 2.5, 3, 3.5, 4, 5]) >>> ax = s.plot.kde() A scalar bandwidth can be specified. Using a small bandwidth value can lead to over-fitting, while using a large bandwidth value may result in under-fitting: .. plot:: :context: close-figs >>> ax = s.plot.kde(bw_method=0.3) .. plot:: :context: close-figs >>> ax = s.plot.kde(bw_method=3) Finally, the `ind` parameter determines the evaluation points for the plot of the estimated PDF: .. plot:: :context: close-figs >>> ax = s.plot.kde(ind=[1, 2, 3, 4, 5]) """.strip() }) def kde(self, bw_method=None, ind=None, **kwds): return self(kind='kde', bw_method=bw_method, ind=ind, **kwds) density = kde def area(self, **kwds): """ Area plot Parameters ---------- `**kwds` : optional Additional keyword arguments are documented in :meth:`pandas.Series.plot`. Returns ------- axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them """ return self(kind='area', **kwds) def pie(self, **kwds): """ Pie chart Parameters ---------- `**kwds` : optional Additional keyword arguments are documented in :meth:`pandas.Series.plot`. Returns ------- axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them """ return self(kind='pie', **kwds) class FramePlotMethods(BasePlotMethods): """DataFrame plotting accessor and method Examples -------- >>> df.plot.line() >>> df.plot.scatter('x', 'y') >>> df.plot.hexbin() These plotting methods can also be accessed by calling the accessor as a method with the ``kind`` argument: ``df.plot(kind='line')`` is equivalent to ``df.plot.line()`` """ def __call__(self, x=None, y=None, kind='line', ax=None, subplots=False, sharex=None, sharey=False, layout=None, figsize=None, use_index=True, title=None, grid=None, legend=True, style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None, rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, secondary_y=False, sort_columns=False, **kwds): return plot_frame(self._parent, kind=kind, x=x, y=y, ax=ax, subplots=subplots, sharex=sharex, sharey=sharey, layout=layout, figsize=figsize, use_index=use_index, title=title, grid=grid, legend=legend, style=style, logx=logx, logy=logy, loglog=loglog, xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim, rot=rot, fontsize=fontsize, colormap=colormap, table=table, yerr=yerr, xerr=xerr, secondary_y=secondary_y, sort_columns=sort_columns, **kwds) __call__.__doc__ = plot_frame.__doc__ def line(self, x=None, y=None, **kwds): """ Plot DataFrame columns as lines. This function is useful to plot lines using DataFrame's values as coordinates. Parameters ---------- x : int or str, optional Columns to use for the horizontal axis. Either the location or the label of the columns to be used. By default, it will use the DataFrame indices. y : int, str, or list of them, optional The values to be plotted. Either the location or the label of the columns to be used. By default, it will use the remaining DataFrame numeric columns. **kwds Keyword arguments to pass on to :meth:`pandas.DataFrame.plot`. Returns ------- axes : :class:`matplotlib.axes.Axes` or :class:`numpy.ndarray` Returns an ndarray when ``subplots=True``. See Also -------- matplotlib.pyplot.plot : Plot y versus x as lines and/or markers. Examples -------- .. plot:: :context: close-figs The following example shows the populations for some animals over the years. >>> df = pd.DataFrame({ ... 'pig': [20, 18, 489, 675, 1776], ... 'horse': [4, 25, 281, 600, 1900] ... }, index=[1990, 1997, 2003, 2009, 2014]) >>> lines = df.plot.line() .. plot:: :context: close-figs An example with subplots, so an array of axes is returned. >>> axes = df.plot.line(subplots=True) >>> type(axes) <class 'numpy.ndarray'> .. plot:: :context: close-figs The following example shows the relationship between both populations. >>> lines = df.plot.line(x='pig', y='horse') """ return self(kind='line', x=x, y=y, **kwds) def bar(self, x=None, y=None, **kwds): """ Vertical bar plot. A bar plot is a plot that presents categorical data with rectangular bars with lengths proportional to the values that they represent. A bar plot shows comparisons among discrete categories. One axis of the plot shows the specific categories being compared, and the other axis represents a measured value. Parameters ---------- x : label or position, optional Allows plotting of one column versus another. If not specified, the index of the DataFrame is used. y : label or position, optional Allows plotting of one column versus another. If not specified, all numerical columns are used. **kwds Additional keyword arguments are documented in :meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.axes.Axes or np.ndarray of them An ndarray is returned with one :class:`matplotlib.axes.Axes` per column when ``subplots=True``. See Also -------- pandas.DataFrame.plot.barh : Horizontal bar plot. pandas.DataFrame.plot : Make plots of a DataFrame. matplotlib.pyplot.bar : Make a bar plot with matplotlib. Examples -------- Basic plot. .. plot:: :context: close-figs >>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]}) >>> ax = df.plot.bar(x='lab', y='val', rot=0) Plot a whole dataframe to a bar plot. Each column is assigned a distinct color, and each row is nested in a group along the horizontal axis. .. plot:: :context: close-figs >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88] >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28] >>> index = ['snail', 'pig', 'elephant', ... 'rabbit', 'giraffe', 'coyote', 'horse'] >>> df = pd.DataFrame({'speed': speed, ... 'lifespan': lifespan}, index=index) >>> ax = df.plot.bar(rot=0) Instead of nesting, the figure can be split by column with ``subplots=True``. In this case, a :class:`numpy.ndarray` of :class:`matplotlib.axes.Axes` are returned. .. plot:: :context: close-figs >>> axes = df.plot.bar(rot=0, subplots=True) >>> axes[1].legend(loc=2) # doctest: +SKIP Plot a single column. .. plot:: :context: close-figs >>> ax = df.plot.bar(y='speed', rot=0) Plot only selected categories for the DataFrame. .. plot:: :context: close-figs >>> ax = df.plot.bar(x='lifespan', rot=0) """ return self(kind='bar', x=x, y=y, **kwds) def barh(self, x=None, y=None, **kwds): """ Make a horizontal bar plot. A horizontal bar plot is a plot that presents quantitative data with rectangular bars with lengths proportional to the values that they represent. A bar plot shows comparisons among discrete categories. One axis of the plot shows the specific categories being compared, and the other axis represents a measured value. Parameters ---------- x : label or position, default DataFrame.index Column to be used for categories. y : label or position, default All numeric columns in dataframe Columns to be plotted from the DataFrame. **kwds Keyword arguments to pass on to :meth:`pandas.DataFrame.plot`. Returns ------- axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them. See Also -------- pandas.DataFrame.plot.bar: Vertical bar plot. pandas.DataFrame.plot : Make plots of DataFrame using matplotlib. matplotlib.axes.Axes.bar : Plot a vertical bar plot using matplotlib. Examples -------- Basic example .. plot:: :context: close-figs >>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]}) >>> ax = df.plot.barh(x='lab', y='val') Plot a whole DataFrame to a horizontal bar plot .. plot:: :context: close-figs >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88] >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28] >>> index = ['snail', 'pig', 'elephant', ... 'rabbit', 'giraffe', 'coyote', 'horse'] >>> df = pd.DataFrame({'speed': speed, ... 'lifespan': lifespan}, index=index) >>> ax = df.plot.barh() Plot a column of the DataFrame to a horizontal bar plot .. plot:: :context: close-figs >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88] >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28] >>> index = ['snail', 'pig', 'elephant', ... 'rabbit', 'giraffe', 'coyote', 'horse'] >>> df = pd.DataFrame({'speed': speed, ... 'lifespan': lifespan}, index=index) >>> ax = df.plot.barh(y='speed') Plot DataFrame versus the desired column .. plot:: :context: close-figs >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88] >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28] >>> index = ['snail', 'pig', 'elephant', ... 'rabbit', 'giraffe', 'coyote', 'horse'] >>> df = pd.DataFrame({'speed': speed, ... 'lifespan': lifespan}, index=index) >>> ax = df.plot.barh(x='lifespan') """ return self(kind='barh', x=x, y=y, **kwds) def box(self, by=None, **kwds): r""" Make a box plot of the DataFrame columns. A box plot is a method for graphically depicting groups of numerical data through their quartiles. The box extends from the Q1 to Q3 quartile values of the data, with a line at the median (Q2). The whiskers extend from the edges of box to show the range of the data. The position of the whiskers is set by default to 1.5*IQR (IQR = Q3 - Q1) from the edges of the box. Outlier points are those past the end of the whiskers. For further details see Wikipedia's entry for `boxplot <https://en.wikipedia.org/wiki/Box_plot>`__. A consideration when using this chart is that the box and the whiskers can overlap, which is very common when plotting small sets of data. Parameters ---------- by : string or sequence Column in the DataFrame to group by. **kwds : optional Additional keywords are documented in :meth:`pandas.DataFrame.plot`. Returns ------- axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them See Also -------- pandas.DataFrame.boxplot: Another method to draw a box plot. pandas.Series.plot.box: Draw a box plot from a Series object. matplotlib.pyplot.boxplot: Draw a box plot in matplotlib. Examples -------- Draw a box plot from a DataFrame with four columns of randomly generated data. .. plot:: :context: close-figs >>> data = np.random.randn(25, 4) >>> df = pd.DataFrame(data, columns=list('ABCD')) >>> ax = df.plot.box() """ return self(kind='box', by=by, **kwds) def hist(self, by=None, bins=10, **kwds): """ Draw one histogram of the DataFrame's columns. A histogram is a representation of the distribution of data. This function groups the values of all given Series in the DataFrame into bins and draws all bins in one :class:`matplotlib.axes.Axes`. This is useful when the DataFrame's Series are in a similar scale. Parameters ---------- by : str or sequence, optional Column in the DataFrame to group by. bins : int, default 10 Number of histogram bins to be used. **kwds Additional keyword arguments are documented in :meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.AxesSubplot histogram. See Also -------- DataFrame.hist : Draw histograms per DataFrame's Series. Series.hist : Draw a histogram with Series' data. Examples -------- When we draw a dice 6000 times, we expect to get each value around 1000 times. But when we draw two dices and sum the result, the distribution is going to be quite different. A histogram illustrates those distributions. .. plot:: :context: close-figs >>> df = pd.DataFrame( ... np.random.randint(1, 7, 6000), ... columns = ['one']) >>> df['two'] = df['one'] + np.random.randint(1, 7, 6000) >>> ax = df.plot.hist(bins=12, alpha=0.5) """ return self(kind='hist', by=by, bins=bins, **kwds) @Appender(_kde_docstring % { 'this-datatype': 'DataFrame', 'sibling-datatype': 'Series', 'examples': """ Given several Series of points randomly sampled from unknown distributions, estimate their PDFs using KDE with automatic bandwidth determination and plot the results, evaluating them at 1000 equally spaced points (default): .. plot:: :context: close-figs >>> df = pd.DataFrame({ ... 'x': [1, 2, 2.5, 3, 3.5, 4, 5], ... 'y': [4, 4, 4.5, 5, 5.5, 6, 6], ... }) >>> ax = df.plot.kde() A scalar bandwidth can be specified. Using a small bandwidth value can lead to over-fitting, while using a large bandwidth value may result in under-fitting: .. plot:: :context: close-figs >>> ax = df.plot.kde(bw_method=0.3) .. plot:: :context: close-figs >>> ax = df.plot.kde(bw_method=3) Finally, the `ind` parameter determines the evaluation points for the plot of the estimated PDF: .. plot:: :context: close-figs >>> ax = df.plot.kde(ind=[1, 2, 3, 4, 5, 6]) """.strip() }) def kde(self, bw_method=None, ind=None, **kwds): return self(kind='kde', bw_method=bw_method, ind=ind, **kwds) density = kde def area(self, x=None, y=None, **kwds): """ Draw a stacked area plot. An area plot displays quantitative data visually. This function wraps the matplotlib area function. Parameters ---------- x : label or position, optional Coordinates for the X axis. By default uses the index. y : label or position, optional Column to plot. By default uses all columns. stacked : bool, default True Area plots are stacked by default. Set to False to create a unstacked plot. **kwds : optional Additional keyword arguments are documented in :meth:`pandas.DataFrame.plot`. Returns ------- matplotlib.axes.Axes or numpy.ndarray Area plot, or array of area plots if subplots is True See Also -------- DataFrame.plot : Make plots of DataFrame using matplotlib / pylab. Examples -------- Draw an area plot based on basic business metrics: .. plot:: :context: close-figs >>> df = pd.DataFrame({ ... 'sales': [3, 2, 3, 9, 10, 6], ... 'signups': [5, 5, 6, 12, 14, 13], ... 'visits': [20, 42, 28, 62, 81, 50], ... }, index=pd.date_range(start='2018/01/01', end='2018/07/01', ... freq='M')) >>> ax = df.plot.area() Area plots are stacked by default. To produce an unstacked plot, pass ``stacked=False``: .. plot:: :context: close-figs >>> ax = df.plot.area(stacked=False) Draw an area plot for a single column: .. plot:: :context: close-figs >>> ax = df.plot.area(y='sales') Draw with a different `x`: .. plot:: :context: close-figs >>> df = pd.DataFrame({ ... 'sales': [3, 2, 3], ... 'visits': [20, 42, 28], ... 'day': [1, 2, 3], ... }) >>> ax = df.plot.area(x='day') """ return self(kind='area', x=x, y=y, **kwds) def pie(self, y=None, **kwds): """ Generate a pie plot. A pie plot is a proportional representation of the numerical data in a column. This function wraps :meth:`matplotlib.pyplot.pie` for the specified column. If no column reference is passed and ``subplots=True`` a pie plot is drawn for each numerical column independently. Parameters ---------- y : int or label, optional Label or position of the column to plot. If not provided, ``subplots=True`` argument must be passed. **kwds Keyword arguments to pass on to :meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.axes.Axes or np.ndarray of them. A NumPy array is returned when `subplots` is True. See Also -------- Series.plot.pie : Generate a pie plot for a Series. DataFrame.plot : Make plots of a DataFrame. Examples -------- In the example below we have a DataFrame with the information about planet's mass and radius. We pass the the 'mass' column to the pie function to get a pie plot. .. plot:: :context: close-figs >>> df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97], ... 'radius': [2439.7, 6051.8, 6378.1]}, ... index=['Mercury', 'Venus', 'Earth']) >>> plot = df.plot.pie(y='mass', figsize=(5, 5)) .. plot:: :context: close-figs >>> plot = df.plot.pie(subplots=True, figsize=(6, 3)) """ return self(kind='pie', y=y, **kwds) def scatter(self, x, y, s=None, c=None, **kwds): """ Create a scatter plot with varying marker point size and color. The coordinates of each point are defined by two dataframe columns and filled circles are used to represent each point. This kind of plot is useful to see complex correlations between two variables. Points could be for instance natural 2D coordinates like longitude and latitude in a map or, in general, any pair of metrics that can be plotted against each other. Parameters ---------- x : int or str The column name or column position to be used as horizontal coordinates for each point. y : int or str The column name or column position to be used as vertical coordinates for each point. s : scalar or array_like, optional The size of each point. Possible values are: - A single scalar so all points have the same size. - A sequence of scalars, which will be used for each point's size recursively. For instance, when passing [2,14] all points size will be either 2 or 14, alternatively. c : str, int or array_like, optional The color of each point. Possible values are: - A single color string referred to by name, RGB or RGBA code, for instance 'red' or '#a98d19'. - A sequence of color strings referred to by name, RGB or RGBA code, which will be used for each point's color recursively. For instance ['green','yellow'] all points will be filled in green or yellow, alternatively. - A column name or position whose values will be used to color the marker points according to a colormap. **kwds Keyword arguments to pass on to :meth:`pandas.DataFrame.plot`. Returns ------- axes : :class:`matplotlib.axes.Axes` or numpy.ndarray of them See Also -------- matplotlib.pyplot.scatter : scatter plot using multiple input data formats. Examples -------- Let's see how to draw a scatter plot using coordinates from the values in a DataFrame's columns. .. plot:: :context: close-figs >>> df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1], ... [6.4, 3.2, 1], [5.9, 3.0, 2]], ... columns=['length', 'width', 'species']) >>> ax1 = df.plot.scatter(x='length', ... y='width', ... c='DarkBlue') And now with the color determined by a column as well. .. plot:: :context: close-figs >>> ax2 = df.plot.scatter(x='length', ... y='width', ... c='species', ... colormap='viridis') """ return self(kind='scatter', x=x, y=y, c=c, s=s, **kwds) def hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None, **kwds): """ Generate a hexagonal binning plot. Generate a hexagonal binning plot of `x` versus `y`. If `C` is `None` (the default), this is a histogram of the number of occurrences of the observations at ``(x[i], y[i])``. If `C` is specified, specifies values at given coordinates ``(x[i], y[i])``. These values are accumulated for each hexagonal bin and then reduced according to `reduce_C_function`, having as default the NumPy's mean function (:meth:`numpy.mean`). (If `C` is specified, it must also be a 1-D sequence of the same length as `x` and `y`, or a column label.) Parameters ---------- x : int or str The column label or position for x points. y : int or str The column label or position for y points. C : int or str, optional The column label or position for the value of `(x, y)` point. reduce_C_function : callable, default `np.mean` Function of one argument that reduces all the values in a bin to a single number (e.g. `np.mean`, `np.max`, `np.sum`, `np.std`). gridsize : int or tuple of (int, int), default 100 The number of hexagons in the x-direction. The corresponding number of hexagons in the y-direction is chosen in a way that the hexagons are approximately regular. Alternatively, gridsize can be a tuple with two elements specifying the number of hexagons in the x-direction and the y-direction. **kwds Additional keyword arguments are documented in :meth:`pandas.DataFrame.plot`. Returns ------- matplotlib.AxesSubplot The matplotlib ``Axes`` on which the hexbin is plotted. See Also -------- DataFrame.plot : Make plots of a DataFrame. matplotlib.pyplot.hexbin : hexagonal binning plot using matplotlib, the matplotlib function that is used under the hood. Examples -------- The following examples are generated with random data from a normal distribution. .. plot:: :context: close-figs >>> n = 10000 >>> df = pd.DataFrame({'x': np.random.randn(n), ... 'y': np.random.randn(n)}) >>> ax = df.plot.hexbin(x='x', y='y', gridsize=20) The next example uses `C` and `np.sum` as `reduce_C_function`. Note that `'observations'` values ranges from 1 to 5 but the result plot shows values up to more than 25. This is because of the `reduce_C_function`. .. plot:: :context: close-figs >>> n = 500 >>> df = pd.DataFrame({ ... 'coord_x': np.random.uniform(-3, 3, size=n), ... 'coord_y': np.random.uniform(30, 50, size=n), ... 'observations': np.random.randint(1,5, size=n) ... }) >>> ax = df.plot.hexbin(x='coord_x', ... y='coord_y', ... C='observations', ... reduce_C_function=np.sum, ... gridsize=10, ... cmap="viridis") """ if reduce_C_function is not None: kwds['reduce_C_function'] = reduce_C_function if gridsize is not None: kwds['gridsize'] = gridsize return self(kind='hexbin', x=x, y=y, C=C, **kwds)
harisbal/pandas
pandas/plotting/_core.py
Python
bsd-3-clause
128,319
[ "Gaussian" ]
9c8e499361eb7c8b995e8b236780c79dbdcdfd4a6f78ea7296ffd6384d0c2e6a
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright (c) 2015--, The Horizomer Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- # # Parse output files of HGT tools. # import click import sys from skbio import Sequence # T-REX version 3.6 # RANGER-DTL-U version 1.0 # RIATA-HGT version 3.5.6 # JANE version 4 # each tuple consists of three strings, first string is the unique string to # identify the line with HGT information, second and third strings are the # bounds for the actual number of HGTs hgt_parse_strs = { 'ranger-dtl': ('The minimum reconciliation cost is: ', 'Transfers: ', ', Losses'), 'trex': ('hgt : number of HGT(s) found = ', 'hgt : number of HGT(s) found = ', ' '), 'jane4': ('Host Switch: ', 'Host Switch: ', ' '), 'riata-hgt': ('There are ', 'There are ', ' component(s)')} def parse_hgts(input_f, method): """ Extract number of HGTs found. Parameters ---------- input_f: string file descriptor for T-REX output results method: string HGT detection method Returns ------- number_of_hgts: string number of HGTs reported by a tool, or NaN if an entry was not found """ for line in input_f: if hgt_parse_strs[method][0] in line: return line.strip().split( hgt_parse_strs[method][1])[1].split( hgt_parse_strs[method][2])[0] return 'NaN' def parse_consel(input_f): """ Parse output of Consel version 0.20. Parameters ---------- input_f: string file descriptor for Consel output results Returns ------- pvalues: list list of P-values """ pvalues = [] # skip header lines skip_lines = 3 for s in range(skip_lines): next(input_f) for line in input_f: line = line.split() # skip empty line at bottom of file if not line: continue pv_au = line[4] if 0 <= float(pv_au) <= 1: pvalues.append("%.2f" % float(pv_au)) return pvalues def parse_darkhorse(input_f, output_fp, low_lpi=0.0, high_lpi=0.6): """ Parse output of DarkHorse (smry file). Paramters --------- input_f: string file descriptor for Consel output results output_fp: str Filepath to output best hit genome IDs low_lpi: float lower LPI (lineage probability index) score bound high_lpi: float upper LPI score bound Returns ------- hgts: string one putative HGT-derived gene per line columns: query_id, besthit_id, tax_id, species, lineage, pct_id, pct_coverage, norm_LPI Notes ----- Parse output of DarkHorse to return tab-separated file of putative HGTs using the LPI bounds and a file with all best hit genome IDs. """ best_hit_ids = set() hgts = [] # skip header next(input_f) for line in input_f: x = line.strip('\r\n').split('\t') best_hit_ids.add(x[3]) if low_lpi < float(x[5]) < high_lpi: hgt = '\t'.join((x[0], x[3], x[12], x[13], x[14], x[6], x[9], x[4])) hgts.append(hgt) if output_fp: with open(output_fp, 'w') as output_f: output_f.write('\n'.join(best_hit_ids)) return '\n'.join(hgts) def parse_hgtector(input_f): """ Parse output of HGTector version 0.2.1. Parameters ---------- input_f: string file descriptor for HGTector output results Returns ------- output: string one putative HGT-derived gene per line columns: query_id, donor_taxid, donor_species, donor_lineage, pct_id, pct_coverage """ hgts = [] for line in input_f: x = line.strip('\r\n').split('\t') if (len(x) == 15) and (x[7] == '1'): hgt = '\t'.join((x[0], x[12], x[13], x[14], x[10], x[11])) hgts.append(hgt) return '\n'.join(hgts) def parse_egid(input_f, genbank_fp): """ Extract genes contained in GIs identified by EGID Parameters ---------- input_f: string file descriptor for EGID output results (GI coordinates) genbank_fp: string file path to genome in GenBank format (containing gene coordinates) Notes ----- genbank_fp is the intermediate GenBank file generated by reformat_input.py, in which multiple sequences are concantenated, instead of the original GenBank file. Returns ------- output: string gene names (protein_ids) separated by newline """ genes = {} gb = Sequence.read(genbank_fp, format='genbank') for feature in gb.interval_metadata.query(metadata={'type': 'CDS'}): m = feature.metadata if 'protein_id' in m: protein_id = m['protein_id'].replace('\"', '') if protein_id not in genes: # in scikit-bio, this number is the start location - 1 start = feature.bounds[0][0] + 1 end = feature.bounds[0][1] genes[protein_id] = (start, end) genes_in_gi = {} for line in input_f: x = line.strip().split() # a valid GI definition should have at least 2 columns if len(x) < 2: continue start = int(x[0]) end = int(x[1]) for (gene, pos) in genes.items(): if (pos[0] >= start and pos[1] <= end): if gene not in genes_in_gi: genes_in_gi[gene] = 1 return '\n'.join(sorted(genes_in_gi)) def parse_genemark(input_f, genbank_fp): """ Extract atypical genes identified by GeneMark Parameters ---------- input_f: string file descriptor for GeneMark output gene list (*.lst) genbank_fp: string file path to genome in GenBank format Notes ----- genbank_fp is the intermediate GenBank file generated by reformat_input.py, in which multiple sequences are concantenated, instead of the original GenBank file. Returns ------- output: string gene names (protein_ids) separated by newline """ genes = {} gb = Sequence.read(genbank_fp, format='genbank') for feature in gb.interval_metadata._intervals: m = feature.metadata if m['type'] == 'CDS' and 'protein_id' in m: protein_id = m['protein_id'].replace('\"', '') if protein_id not in genes: strand = m['strand'] start = feature.bounds[0][0] + 1 end = feature.bounds[0][1] genes[protein_id] = (start, end, strand) atypical_genes = [] reading = False for line in input_f: x = line.strip().split() if len(x) == 2 and x == ['#', 'Length']: reading = True # atypical genes have class '2' in the 6th column elif reading and len(x) == 6 and x[5] == '2': (start, end, strand) = (int(x[2].lstrip('<>')), int(x[3].lstrip('<>')), x[1]) for (gene, x) in genes.items(): if x[0] == start and x[1] == end and x[2] == strand: atypical_genes.append(gene) return '\n'.join(sorted(atypical_genes)) def parse_output(hgt_results_fp, method, genbank_fp=None, low_lpi=0.0, high_lpi=0.6, output_fp=None): """Call parse_hgts() based on HGT detection method used. Parameters ---------- hgt_results_fp: str filepath to detected HGTs genbank_fp: string file path to genome in GenBank format method: string tool used to detect HGTs output_fp: str output file storing best hit IDs (DarkHorse) low_lpi: float lower bound LPI score (DarkHorse Lineage Probability Index) high_lpi: float upper bound LPI score (DarkHorse Lineage Probability Index) Returns ------- output: string number of HGTs detected """ with open(hgt_results_fp, 'r') as input_f: if (method == 'ranger-dtl' or method == 'trex' or method == 'jane4' or method == 'riata-hgt'): output = parse_hgts(input_f=input_f, method=method) elif method == 'consel': output = parse_consel(input_f=input_f) elif method == 'darkhorse': output = parse_darkhorse(input_f=input_f, output_fp=output_fp, low_lpi=low_lpi, high_lpi=high_lpi) elif method == 'hgtector': output = parse_hgtector(input_f=input_f) elif method == 'egid': output = parse_egid(input_f=input_f, genbank_fp=genbank_fp) elif method == 'genemark': output = parse_genemark(input_f=input_f, genbank_fp=genbank_fp) else: raise ValueError("Method is not supported: %s" % method) return output @click.command() @click.option('--hgt-results-fp', required=True, type=click.Path(resolve_path=True, readable=True, exists=True, file_okay=True), help='Output file containing HGT information') @click.option('--genbank-fp', required=False, type=click.Path(resolve_path=True, readable=True, exists=True, file_okay=True), help='Output file containing HGT information') @click.option('--ncbi-nr', required=False, type=click.Path(resolve_path=True, readable=True, exists=True, file_okay=True), help='NCBI nr database in FASTA format to link' 'taxon ids with accession numbers for DarkHorse output') @click.option('--method', required=True, type=click.Choice(['trex', 'ranger-dtl', 'riata-hgt', 'consel', 'darkhorse', 'hgtector', 'genemark', 'egid', 'jane4', 'tree-puzzle']), help='The method used for HGT detection') @click.option('--darkhorse-low-lpi', type=float, default=0.0, show_default=True, required=False, help='Lower bound LPI score') @click.option('--darkhorse-high-lpi', type=float, default=0.6, show_default=True, required=False, help='Upper bound LPI score') @click.option('--darkhorse-output-fp', required=False, type=click.Path(resolve_path=True, readable=True, exists=False, file_okay=True), help='Output all best hit IDs from DarkHorse summary') def main(hgt_results_fp, genbank_fp, method, ncbi_nr, darkhorse_low_lpi, darkhorse_high_lpi, darkhorse_output_fp=None): """ Parsing functions for various HGT detection tool outputs. """ output = parse_output(hgt_results_fp=hgt_results_fp, method=method, genbank_fp=genbank_fp, low_lpi=darkhorse_low_lpi, high_lpi=darkhorse_high_lpi, output_fp=darkhorse_output_fp) sys.stdout.write(output) if __name__ == "__main__": main()
biocore/WGS-HGT
horizomer/benchmark/parse_output.py
Python
bsd-3-clause
11,853
[ "scikit-bio" ]
1c6fdaad78bca11e1210e70e8d6c957a9dbfbfbbeeab5dcc4185ba7dfb146406
from DIRAC import S_OK, S_ERROR from DIRAC.AccountingSystem.Client.Types.Pilot import Pilot from DIRAC.AccountingSystem.private.Plotters.BaseReporter import BaseReporter class PilotPlotter( BaseReporter ): _typeName = "Pilot" _typeKeyFields = [ dF[0] for dF in Pilot().definitionKeyFields ] def _reportCumulativeNumberOfJobs( self, reportRequest ): selectFields = ( self._getSelectStringForGrouping( reportRequest[ 'groupingFields' ] ) + ", %s, %s, SUM(%s)", reportRequest[ 'groupingFields' ][1] + [ 'startTime', 'bucketLength', 'Jobs' ] ) retVal = self._getTimedData( reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], selectFields, reportRequest[ 'condDict' ], reportRequest[ 'groupingFields' ], {} ) if not retVal[ 'OK' ]: return retVal dataDict, granularity = retVal[ 'Value' ] self.stripDataField( dataDict, 0 ) dataDict = self._fillWithZero( granularity, reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], dataDict ) dataDict = self._accumulate( granularity, reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], dataDict ) baseDataDict, graphDataDict, maxValue, unitName = self._findSuitableUnit( dataDict, self._getAccumulationMaxValue( dataDict ), "jobs" ) return S_OK( { 'data' : baseDataDict, 'graphDataDict' : graphDataDict, 'granularity' : granularity, 'unit' : unitName } ) def _plotCumulativeNumberOfJobs( self, reportRequest, plotInfo, filename ): metadata = { 'title' : 'Cumulative Jobs by %s' % reportRequest[ 'grouping' ], 'starttime' : reportRequest[ 'startTime' ], 'endtime' : reportRequest[ 'endTime' ], 'span' : plotInfo[ 'granularity' ], 'ylabel' : plotInfo[ 'unit' ], 'sort_labels' : 'last_value' } return self._generateCumulativePlot( filename, plotInfo[ 'graphDataDict' ], metadata ) def _reportNumberOfJobs( self, reportRequest ): selectFields = ( self._getSelectStringForGrouping( reportRequest[ 'groupingFields' ] ) + ", %s, %s, SUM(%s)", reportRequest[ 'groupingFields' ][1] + [ 'startTime', 'bucketLength', 'Jobs' ] ) retVal = self._getTimedData( reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], selectFields, reportRequest[ 'condDict' ], reportRequest[ 'groupingFields' ], {} ) if not retVal[ 'OK' ]: return retVal dataDict, granularity = retVal[ 'Value' ] self.stripDataField( dataDict, 0 ) dataDict, maxValue = self._divideByFactor( dataDict, granularity ) dataDict = self._fillWithZero( granularity, reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], dataDict ) baseDataDict, graphDataDict, maxValue, unitName = self._findSuitableRateUnit( dataDict, self._getAccumulationMaxValue( dataDict ), "jobs" ) return S_OK( { 'data' : baseDataDict, 'graphDataDict' : graphDataDict, 'granularity' : granularity, 'unit' : unitName } ) def _plotNumberOfJobs( self, reportRequest, plotInfo, filename ): metadata = { 'title' : 'Jobs by %s' % reportRequest[ 'grouping' ], 'starttime' : reportRequest[ 'startTime' ], 'endtime' : reportRequest[ 'endTime' ], 'span' : plotInfo[ 'granularity' ], 'ylabel' : plotInfo[ 'unit' ] } return self._generateTimedStackedBarPlot( filename, plotInfo[ 'graphDataDict' ], metadata ) def _reportCumulativeNumberOfPilots( self, reportRequest ): selectFields = ( self._getSelectStringForGrouping( reportRequest[ 'groupingFields' ] ) + ", %s, %s, SUM(%s)", reportRequest[ 'groupingFields' ][1] + [ 'startTime', 'bucketLength', 'entriesInBucket' ] ) retVal = self._getTimedData( reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], selectFields, reportRequest[ 'condDict' ], reportRequest[ 'groupingFields' ], {} ) if not retVal[ 'OK' ]: return retVal dataDict, granularity = retVal[ 'Value' ] self.stripDataField( dataDict, 0 ) dataDict = self._fillWithZero( granularity, reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], dataDict ) dataDict = self._accumulate( granularity, reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], dataDict ) baseDataDict, graphDataDict, maxValue, unitName = self._findSuitableUnit( dataDict, self._getAccumulationMaxValue( dataDict ), "jobs" ) return S_OK( { 'data' : baseDataDict, 'graphDataDict' : graphDataDict, 'granularity' : granularity, 'unit' : unitName } ) def _plotCumulativeNumberOfPilots( self, reportRequest, plotInfo, filename ): metadata = { 'title' : 'Cumulative Pilots by %s' % reportRequest[ 'grouping' ], 'starttime' : reportRequest[ 'startTime' ], 'endtime' : reportRequest[ 'endTime' ], 'span' : plotInfo[ 'granularity' ], 'ylabel' : plotInfo[ 'unit' ].replace( 'job', 'pilot' ), 'sort_labels' : 'last_value' } return self._generateCumulativePlot( filename, plotInfo[ 'graphDataDict' ], metadata ) def _reportNumberOfPilots( self, reportRequest ): selectFields = ( self._getSelectStringForGrouping( reportRequest[ 'groupingFields' ] ) + ", %s, %s, SUM(%s)", reportRequest[ 'groupingFields' ][1] + [ 'startTime', 'bucketLength', 'entriesInBucket' ] ) retVal = self._getTimedData( reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], selectFields, reportRequest[ 'condDict' ], reportRequest[ 'groupingFields' ], {} ) if not retVal[ 'OK' ]: return retVal dataDict, granularity = retVal[ 'Value' ] self.stripDataField( dataDict, 0 ) dataDict, maxValue = self._divideByFactor( dataDict, granularity ) dataDict = self._fillWithZero( granularity, reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], dataDict ) baseDataDict, graphDataDict, maxValue, unitName = self._findSuitableRateUnit( dataDict, self._getAccumulationMaxValue( dataDict ), "jobs" ) return S_OK( { 'data' : baseDataDict, 'graphDataDict' : graphDataDict, 'granularity' : granularity, 'unit' : unitName } ) def _plotNumberOfPilots( self, reportRequest, plotInfo, filename ): metadata = { 'title' : 'Pilots by %s' % reportRequest[ 'grouping' ], 'starttime' : reportRequest[ 'startTime' ], 'endtime' : reportRequest[ 'endTime' ], 'span' : plotInfo[ 'granularity' ], 'ylabel' : plotInfo[ 'unit' ].replace( 'job', 'pilot' ) } return self._generateTimedStackedBarPlot( filename, plotInfo[ 'graphDataDict' ], metadata ) def _reportJobsPerPilot( self, reportRequest ): selectFields = ( self._getSelectStringForGrouping( reportRequest[ 'groupingFields' ] ) + ", %s, %s, SUM(%s), SUM(%s)", reportRequest[ 'groupingFields' ][1] + [ 'startTime', 'bucketLength', 'Jobs', 'entriesInBucket' ] ) retVal = self._getTimedData( reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], selectFields, reportRequest[ 'condDict' ], reportRequest[ 'groupingFields' ], { 'checkNone' : True, 'convertToGranularity' : 'sum', 'calculateProportionalGauges' : True } ) if not retVal[ 'OK' ]: return retVal dataDict, granularity = retVal[ 'Value' ] self.stripDataField( dataDict, 0 ) dataDict = self._fillWithZero( granularity, reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], dataDict ) return S_OK( { 'data' : dataDict, 'granularity' : granularity } ) def _plotJobsPerPilot( self, reportRequest, plotInfo, filename ): metadata = { 'title' : 'Jobs per pilot by %s' % reportRequest[ 'grouping' ], 'starttime' : reportRequest[ 'startTime' ], 'endtime' : reportRequest[ 'endTime' ], 'span' : plotInfo[ 'granularity' ], 'ylabel' : "jobs/pilot" } return self._generateTimedStackedBarPlot( filename, plotInfo[ 'data' ], metadata ) def _reportTotalNumberOfPilots( self, reportRequest ): selectFields = ( self._getSelectStringForGrouping( reportRequest[ 'groupingFields' ] ) + ", SUM(%s)", reportRequest[ 'groupingFields' ][1] + [ 'entriesInBucket' ] ) retVal = self._getSummaryData( reportRequest[ 'startTime' ], reportRequest[ 'endTime' ], selectFields, reportRequest[ 'condDict' ], reportRequest[ 'groupingFields' ], {} ) if not retVal[ 'OK' ]: return retVal dataDict = retVal[ 'Value' ] return S_OK( { 'data' : dataDict } ) def _plotTotalNumberOfPilots( self, reportRequest, plotInfo, filename ): metadata = { 'title' : 'Total Number of Pilots by %s' % reportRequest[ 'grouping' ], 'ylabel' : 'Pilots', 'starttime' : reportRequest[ 'startTime' ], 'endtime' : reportRequest[ 'endTime' ] } return self._generatePiePlot( filename, plotInfo[ 'data'], metadata )
Sbalbp/DIRAC
AccountingSystem/private/Plotters/PilotPlotter.py
Python
gpl-3.0
11,095
[ "DIRAC" ]
581d99f8e2af617fcdd3ca96fc1ba96d460742e4d9e6381de6f87c4aff3f3b7f
import requests import xmltodict import DateTime from tkinter.tix import * screen_width = 950 screen_height = 700 def get_vertrektijden(station='ut'): """ Input: stationscode Aanroepen database, Output: dict met vertrektijden vanuit de stations """ auth_details = ('philip.vanexel@student.hu.nl', 'u6H5dlZpHsjHbIBac4aMHJNPfLtliEZ7cQJJDYjd-ijeBWF4-Zawbw') response = requests.get('http://webservices.ns.nl/ns-api-avt?station='+station, auth=auth_details) final = xmltodict.parse(response.text) printvar = {} x = 0 for i in final['ActueleVertrekTijden']['VertrekkendeTrein']: vertrekkende_trein = dict(i) printvar[x] = vertrekkende_trein x += 1 return printvar def get_stations(): """ Aanroepen database output: dict met alle gegevens van stations """ auth_details = ('philip.vanexel@student.hu.nl', 'u6H5dlZpHsjHbIBac4aMHJNPfLtliEZ7cQJJDYjd-ijeBWF4-Zawbw') response = requests.get('http://webservices.ns.nl/ns-api-stations-v2', auth=auth_details) final = xmltodict.parse(response.text) printvar = {} x = 0 for i in final['Stations']['Station']: station = dict(i) printvar[x] = station x += 1 return printvar def change_time(time): """ Input: Datum en Tijd Veranderen van de tijd naar het goede formaat. Output: Tijd in HH:MM """ dt = DateTime.DateTime(time) return str(dt.TimeMinutes()) def get_stations_code(inputvar): """ Input: Stationsnaam in string Output: Stationscode die gebruikt kan worden in de API. """ stations = get_stations() for station in stations: st = stations[station] if inputvar == st['Namen']['Kort']: return st['Code'] if inputvar == st['Namen']['Middel']: return st['Code'] if inputvar == st['Namen']['Lang']: return st['Code'] if st['Synoniemen']: if st['Synoniemen']['Synoniem']: if isinstance(st['Synoniemen']['Synoniem'], list): for synoniem in st['Synoniemen']['Synoniem']: if inputvar == synoniem: return st['Code'] else: if inputvar == st['Synoniemen']['Synoniem']: return st['Code'] def geef_vertrektijden(inputvar): """ Input: output van de functie get_vertrektijden() Output: Een geformatteerde lijst zoals weergegeven in de schermen. """ returnvar = '{0:14s} {1:25s} {2:45s} {3:6s} {4:10s}'.format("Tijd", "Eindstation", "Route", "Sp.", "Treinsoort") for trein in inputvar: x = inputvar[trein] if 'VertrekTijd' in x: vertrek_tijd = change_time(x['VertrekTijd']) else: vertrek_tijd = "" if 'VertrekVertragingTekst' in x: vertrek_vertraging_tekst = " "+x['VertrekVertragingTekst'] else: vertrek_vertraging_tekst = "" if 'EindBestemming' in x: eind_bestemming = x['EindBestemming'] else: eind_bestemming = "" if "TreinSoort" in x: trein_soort = x['TreinSoort'] else: trein_soort = "" if 'RouteTekst' in x: route_tekst = x['RouteTekst'] else: route_tekst = "" if 'VertrekSpoor' in x: vertrek_spoor = x['VertrekSpoor']['#text'] else: vertrek_spoor = "" if x['VertrekSpoor']['@wijziging'] == 'true': spoor_wijziging = " !" else: spoor_wijziging = "" returnvar += '\n'+'{0:14s} {1:25s} {2:45s} {3:6s} {4:10s}'.format(str(vertrek_tijd)+str(vertrek_vertraging_tekst), str(eind_bestemming), str(route_tekst), str(vertrek_spoor)+str(spoor_wijziging), str(trein_soort)) return returnvar def schermindeling(scherm): """ Input: Variabele scherm Hierin wordt de basis van elk scherm aangemaakt. """ blauwe_balk = Canvas(scherm, bg="#003366", width=screen_width, height=50, highlightthickness=0) blauwe_balk.pack(side=BOTTOM) scherm.maxsize(screen_width, screen_height) scherm.minsize(screen_width, screen_height) scherm.wm_state("zoomed") scherm.configure(background='#ffcc33') scherm.title("NS Vertrektijden") def scherm_1(): """ Welkomstscherm """ s1 = Tk() schermindeling(s1) text1 = Label(s1, text="Welkom bij NS", bg="#ffcc33", fg="#003366", font=("Frutiger", 36)) text1.pack() text1.place(anchor=CENTER, x=screen_width/2, y=100) ns_foto = PhotoImage(file="NS.png") ns_foto_label = Label(s1, image=ns_foto, bg="#ffcc33") ns_foto_label.pack() ns_foto_label.place(anchor=CENTER, x=screen_width/2, y=270) visa_master_foto = PhotoImage(file="visaMaster.png") visa_master_foto_label = Label(s1, image=visa_master_foto, bg="#003366") visa_master_foto_label.pack() visa_master_foto_label.place(anchor=CENTER, x=screen_width/2, y=675) begin_button = Button(s1, text="Actuele vertrektijden", width=20, height=2, bg="#003366", fg="white", font=("Frutiger", 10), activebackground="#003366", activeforeground="white", command=lambda: scherm_2()) begin_button.pack() begin_button.place(anchor=CENTER, x=screen_width/2-100, y=520) afsluit_button = Button(s1, width=20, height=2, text="Afsluiten", fg="white", bg="#003366", font=("Frutiger", 10), activebackground="#003366", activeforeground="white", command=lambda: s1.destroy()) afsluit_button.pack() afsluit_button.place(anchor=CENTER, x=screen_width/2+100, y=520) s1.mainloop() def scherm_2(): """ Scherm met de output van de vertrektijden van het standaardstation (Utrecht Centraal). """ s2 = Toplevel() schermindeling(s2) text1 = Label(s2, text="Utrecht Centraal", bg="#ffcc33", fg="#003366", font=("Frutiger", 25)) text1.pack(side=TOP) button_terug = Button(s2, width=12, height=3, text="Terug", fg="white", bg="#003366", font=("Frutiger", 10), activebackground="#003366", activeforeground="white", command=lambda: s2.destroy()) button_terug.pack() button_terug.place(x=10, y=10) button_ander_station = Button(s2, width=12, height=3, text="Ander station", fg="white", bg="#003366", font=("Frutiger", 10), activebackground="#003366", activeforeground="white", command=lambda: scherm_3()) button_ander_station.pack() button_ander_station.place(x=10, y=75) scroll_win = ScrolledWindow(s2, width=800, height=600) scroll_win.config_all("background", "#ffcc33") scroll_win.config_all("borderwidth", "0") scroll_win.pack(side=RIGHT) win = scroll_win.window label_widget = Label(win, text=geef_vertrektijden(get_vertrektijden()), justify=LEFT, font=("Courier New", 8), bg="#ffcc33") label_widget.pack() scroll_win.mainloop() s2.mainloop() def scherm_3(): """ Scherm met de output van de vertrektijden van het inputstation. """ s3 = Toplevel() schermindeling(s3) def vraag_station(): """ Output: formuliergegevens voor de aanvraag van welk station de vertrektijden opgevraagd worden """ def ok_button(): """ Wat er gebeurt als je op de OK button klikt. """ inputfieldLabel.destroy() inputfield.destroy() inputButton.destroy() inputvar = inputtext.get() return controleer_station(inputvar) inputtext = StringVar() inputfieldLabel = Label(s3, text="Voer een station in", bg="#ffcc33", fg="#003366", font=("Frutiger", 25)) inputfieldLabel.pack(side=TOP) inputfield = Entry(s3, bd=1, textvariable=inputtext, bg="#ffcc33", fg="#003366", highlightthickness=0) inputfield.pack() inputfield.place(anchor=CENTER, x=screen_width/2, y=55) inputButton = Button(s3, text='OK', command=ok_button, bg="#ffcc33", fg="#003366", activebackground="#ffcc33", font=("Frutiger", 7)) inputButton.pack() inputButton.place(anchor=CENTER, x=screen_width/2+73, y=55) def output(inputvar): """ input: Gecontroleerde stationsnaam Output: Weergave van de vertrektijden van het station wat ingevoerd is. """ text2 = Label(s3, text=inputvar, bg="#ffcc33", fg="#003366", font=("Frutiger", 25)) text2.pack(side=TOP) scroll_win = ScrolledWindow(s3, width=800, height=600, bg="#ffcc33") scroll_win.config_all("background", "#ffcc33") scroll_win.config_all("borderwidth", "0") scroll_win.pack(side=RIGHT) win = scroll_win.window label_widget = Label(win, text=geef_vertrektijden(get_vertrektijden(get_stations_code(inputvar))), justify=LEFT, font=("Courier New", 8), bg="#ffcc33") label_widget.pack() scroll_win.mainloop() def controleer_station(inputvar): """ Input: Input die de user geeft. Controleren of het ingevoerde overeenkomt met een station in de API van de NS. Als dit niet zo is dan wordt opnieuw voor een station gevraagd. Output: - Opnieuw aanvragen station - Doorgaan naar output() functie. """ stations = get_stations() namen_lijstje = [] for station in stations: st = stations[station] if st['Namen']['Kort']: namen_lijstje += [st['Namen']['Kort']] if st['Namen']['Middel']: namen_lijstje += [st['Namen']['Middel']] if st['Namen']['Lang']: namen_lijstje += [st['Namen']['Lang']] if st['Synoniemen']: if st['Synoniemen']['Synoniem']: if isinstance(st['Synoniemen']['Synoniem'], list): namen_lijstje += (st['Synoniemen']['Synoniem']) else: namen_lijstje += [st['Synoniemen']['Synoniem']] if inputvar not in namen_lijstje: return vraag_station() else: return output(inputvar) vraag_station() button_terug = Button(s3, width=12, height=3, text="Terug", fg="white", bg="#003366", font=("Frutiger", 10), activebackground="#003366", activeforeground="white", command=lambda: s3.destroy()) button_terug.pack() button_terug.place(x=10, y=10) s3.mainloop() scherm_1()
Flipje666/Actuele_vertrektijden
final gui + api.py
Python
mit
10,519
[ "Elk" ]
7422a0b5e08b8d4fb914321f98148343fa862a5c06d64394a6ccfc6293bf692e
# -*- coding: utf-8 -*- import csv import copy import datetime import logging import io import json import re import time import zipfile import codecs from collections import defaultdict, deque, OrderedDict from django.contrib import messages from django.contrib.auth.decorators import login_required, user_passes_test from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.core.urlresolvers import reverse from django.db import IntegrityError, transaction, connection from django.db.models import Q from django.db.models.expressions import RawSQL from django.forms import ValidationError from django.http import HttpResponse, JsonResponse, HttpResponseRedirect, \ Http404, QueryDict from django.shortcuts import redirect, render, render_to_response from django.template import RequestContext from django.template import Template from django.db.models.query_utils import DeferredAttribute from django.core.exceptions import ObjectDoesNotExist from django.views.decorators.csrf import csrf_protect from django.views.generic.edit import FormView from django.utils.decorators import method_decorator from reversion.models import Revision, Version from ielex.settings import LIMIT_TO, META_TAGS from ielex.forms import AddCitationForm, \ AddCogClassTableForm, \ AddLanguageListForm, \ AddLanguageListTableForm, \ AddMeaningListForm, \ AddLexemeForm, \ AuthorCreationForm, \ AuthorDeletionForm, \ AuthorTableForm, \ AuthorRowForm, \ ChooseCognateClassForm, \ CladeCreationForm, \ CladeDeletionForm, \ CladeTableForm, \ CloneLanguageForm, \ CognateJudgementSplitTable, \ EditCitationForm, \ AddLanguageForm, \ EditLanguageListForm, \ EditLanguageListMembersForm, \ EditLexemeForm, \ EditMeaningForm, \ EditMeaningListForm, \ EditMeaningListMembersForm, \ EditSourceForm, \ LanguageListProgressForm, \ EditSingleLanguageForm, \ LexemeTableEditCognateClassesForm, \ LexemeTableLanguageWordlistForm, \ LexemeTableViewMeaningsForm, \ MeaningListTableForm, \ MergeCognateClassesForm, \ SearchLexemeForm, \ SndCompCreationForm, \ SndCompDeletionForm, \ SndCompTableForm, \ make_reorder_languagelist_form, \ make_reorder_meaninglist_form, \ AddMissingLexemsForLanguageForm, \ RemoveEmptyLexemsForLanguageForm, \ CognateClassEditForm, \ SourceDetailsForm, \ SourceEditForm, \ UploadBiBTeXFileForm, \ CognateJudgementFormSet, \ CognateClassFormSet, \ LexemeFormSet, \ AssignCognateClassesFromLexemeForm, \ LanguageDistributionTableForm, \ TwoLanguageWordlistTableForm from ielex.lexicon.models import Author, \ Clade, \ CognateClass, \ CognateClassCitation, \ CognateJudgement, \ CognateJudgementCitation, \ Language, \ LanguageClade, \ LanguageList, \ LanguageListOrder, \ Lexeme, \ LexemeCitation, \ Meaning, \ MeaningList, \ SndComp, \ Source, \ NexusExport, \ MeaningListOrder, \ RomanisedSymbol from ielex.lexicon.defaultModels import getDefaultLanguage, \ getDefaultLanguageId, \ getDefaultLanguagelist, \ getDefaultLanguagelistId, \ getDefaultMeaning, \ getDefaultMeaningId, \ getDefaultWordlist, \ getDefaultWordlistId, \ getDefaultSourceLanguage, \ setDefaultLanguage, \ setDefaultLanguageId, \ setDefaultLanguagelist, \ setDefaultMeaning, \ setDefaultMeaningId, \ setDefaultWordlist, \ setDefaultSourceLanguage from ielex.shortcuts import render_template from ielex.utilities import next_alias, \ anchored, oneline, logExceptions, fetchMarkdown from ielex.languageCladeLogic import updateLanguageCladeRelations from ielex.tables import SourcesTable, SourcesUpdateTable import bibtexparser from bibtexparser.bparser import BibTexParser from bibtexparser.bwriter import BibTexWriter from bibtexparser.bibdatabase import BibDatabase from django_tables2 import RequestConfig from dal import autocomplete # -- Database input, output and maintenance functions ------------------------ @logExceptions def view_changes(request, username=None, revision_id=None, object_id=None): """Recent changes""" boring_models = [LanguageListOrder, LanguageList, MeaningList] boring_model_ids = [ContentType.objects.get_for_model(m).id for m in boring_models] def interesting_versions(self): return self.version_set.exclude(content_type_id__in=boring_model_ids) Revision.add_to_class("interesting_versions", interesting_versions) if not username: recent_changes = Revision.objects.all().order_by("-id") else: recent_changes = Revision.objects.filter( user__username=username).order_by("-id") paginator = Paginator(recent_changes, 50) try: # Make sure page request is an int. If not, deliver first page. page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: # If page request is out of range, deliver last page of results. changes = paginator.page(page) except (EmptyPage, InvalidPage): changes = paginator.page(paginator.num_pages) userIds = set(Revision.objects.values_list("user", flat=True).distinct()) contributors = sorted([(User.objects.get(id=user_id), Revision.objects.filter(user=user_id).count()) for user_id in userIds if user_id is not None], key=lambda x: -x[1]) return render_template(request, "view_changes.html", {"changes": changes, "contributors": contributors}) @login_required @logExceptions def revert_version(request, revision_id): """Roll back the object saved in a Version to the previous Version""" referer = request.META.get("HTTP_REFERER", "/") revision_obj = Revision.objects.get(pk=revision_id) revision_obj.revert() # revert all associated objects too msg = "Rolled back revision %s" % (revision_obj.id) messages.info(request, msg) return HttpResponseRedirect(referer) @logExceptions def view_object_history(request, version_id): version = Version.objects.get(pk=version_id) obj = version.content_type.get_object_for_this_type(id=version.object_id) fields = [field.name for field in obj._meta.fields] versions = [[v.field_dict[f] for f in fields] + [v.id] for v in Version.objects.get_for_object(obj).order_by( "revision__date_created")] return render_template(request, "view_object_history.html", {"object": obj, "versions": versions, "fields": fields}) # -- General purpose queries and functions ----------------------------------- @logExceptions def get_canonical_meaning(meaning): """Identify meaning from id number or partial name""" try: if meaning.isdigit(): meaning = Meaning.objects.get(id=meaning) else: meaning = Meaning.objects.get(gloss=meaning) except Meaning.DoesNotExist: raise Http404("Meaning '%s' does not exist" % meaning) return meaning @logExceptions def get_canonical_language(language, request=None): """Identify language from id number or partial name""" if not language: raise Language.DoesNotExist if language.isdigit(): language = Language.objects.get(id=language) else: try: language = Language.objects.get(ascii_name=language) except Language.DoesNotExist: try: language = Language.objects.get( ascii_name__istartswith=language) except Language.MultipleObjectsReturned: if request: messages.info( request, "There are multiple languages matching" " '%s' in the database" % language) raise Http404 except Language.DoesNotExist: if request: messages.info( request, "There is no language named or starting" " with '%s' in the database" % language) raise Http404 return language @logExceptions def get_prev_and_next_languages(request, current_language, language_list=None): if language_list is None: language_list = LanguageList.objects.get( name=getDefaultLanguagelist(request)) elif isinstance(language_list, str): language_list = LanguageList.objects.get(name=language_list) ids = list(language_list.languages.exclude( level0=0).values_list("id", flat=True)) try: current_idx = ids.index(current_language.id) except ValueError: current_idx = 0 try: prev_language = Language.objects.get(id=ids[current_idx - 1]) except IndexError: try: prev_language = Language.objects.get(id=ids[len(ids) - 1]) except IndexError: prev_language = current_language try: next_language = Language.objects.get(id=ids[current_idx + 1]) except IndexError: try: next_language = Language.objects.get(id=ids[0]) except IndexError: next_language = current_language return (prev_language, next_language) @logExceptions def get_prev_and_next_meanings(request, current_meaning, meaning_list=None): if meaning_list is None: meaning_list = MeaningList.objects.get( name=getDefaultWordlist(request)) elif isinstance(meaning_list, str): meaning_list = MeaningList.objects.get(name=meaning_list) meanings = list(meaning_list.meanings.all().order_by("meaninglistorder")) ids = [m.id for m in meanings] try: current_idx = ids.index(current_meaning.id) except ValueError: current_idx = 0 try: prev_meaning = meanings[current_idx - 1] except IndexError: prev_meaning = meanings[len(meanings) - 1] try: next_meaning = meanings[current_idx + 1] except IndexError: next_meaning = meanings[0] return (prev_meaning, next_meaning) @logExceptions def get_prev_and_next_lexemes(request, current_lexeme): """Get the previous and next lexeme from the same language, ordered by meaning and then alphabetically by form""" lexemes = list(Lexeme.objects.filter( language=current_lexeme.language).order_by( "meaning", "phon_form", "romanised", "id")) ids = [l.id for l in lexemes] try: current_idx = ids.index(current_lexeme.id) except ValueError: current_idx = 0 prev_lexeme = lexemes[current_idx - 1] try: next_lexeme = lexemes[current_idx + 1] except IndexError: next_lexeme = lexemes[0] return (prev_lexeme, next_lexeme) @logExceptions def update_object_from_form(model_object, form): """Update an object with data from a form.""" assert set(form.cleaned_data).issubset(set(model_object.__dict__)) model_object.__dict__.update(form.cleaned_data) model_object.save() # -- /language(s)/ ---------------------------------------------------------- @logExceptions def get_canonical_language_list(language_list=None, request=None): """Returns a LanguageList object""" try: if language_list is None: language_list = LanguageList.objects.get(name=LanguageList.DEFAULT) elif language_list.isdigit(): language_list = LanguageList.objects.get(id=language_list) else: language_list = LanguageList.objects.get(name=language_list) except LanguageList.DoesNotExist: if request: messages.info( request, "There is no language list matching" " '%s' in the database" % language_list) raise Http404 return language_list @logExceptions def get_canonical_meaning_list(meaning_list=None, request=None): """Returns a MeaningList object""" try: if meaning_list is None: meaning_list = MeaningList.objects.get(name=MeaningList.DEFAULT) elif meaning_list.isdigit(): meaning_list = MeaningList.objects.get(id=meaning_list) else: meaning_list = MeaningList.objects.get(name=meaning_list) except MeaningList.DoesNotExist: if request: messages.info( request, "There is no meaning list matching" " '%s' in the database" % meaning_list) raise Http404 return meaning_list @csrf_protect @logExceptions def view_language_list(request, language_list=None): current_list = get_canonical_language_list(language_list, request) setDefaultLanguagelist(request, current_list.name) languages = current_list.languages.all().prefetch_related( "lexeme_set", "lexeme_set__meaning", "languageclade_set", "clades") if (request.method == 'POST') and ('langlist_form' in request.POST): languageListTableForm = AddLanguageListTableForm(request.POST) try: languageListTableForm.validate() except Exception as e: logging.exception( 'Exception in POST validation for view_language_list') messages.error(request, 'Sorry, the form data sent ' 'did not pass server side validation: %s' % e) return HttpResponseRedirect( reverse("view-language-list", args=[current_list.name])) # Updating languages and gathering clades to update: updateClades = languageListTableForm.handle(request) # Updating clade relations for changes languages: if updateClades: updateLanguageCladeRelations(languages=updateClades) # Redirecting so that UA makes a GET. return HttpResponseRedirect( reverse("view-language-list", args=[current_list.name])) elif (request.method == 'POST') and ('cloneLanguage' in request.POST): # Cloning language and lexemes: form = CloneLanguageForm(request.POST) try: form.validate() form.handle(request, current_list) # Redirect to newly created language: messages.success(request, 'Language cloned.') return HttpResponseRedirect( reverse("view-language-list", args=[current_list.name])) except Exception as e: logging.exception('Problem cloning Language in view_language_list') messages.error(request, 'Sorry, a problem occured ' 'when cloning the language: %s' % e) return HttpResponseRedirect( reverse("view-language-list", args=[current_list.name])) elif (request.method == 'GET') and ('exportCsv' in request.GET): # Handle csv export iff desired: return exportLanguageListCsv(request, languages) meaningList = MeaningList.objects.get(name=getDefaultWordlist(request)) languages_editabletable_form = AddLanguageListTableForm() exportMethod = '' if request.method == 'GET': if 'onlyexport' in request.path.split('/'): exportMethod = 'onlyexport' elif 'onlynotexport' in request.path.split('/'): exportMethod = 'onlynotexport' for lang in languages: lang.idField = lang.id lang.computeCounts(meaningList, exportMethod) languages_editabletable_form.langlist.append_entry(lang) otherLanguageLists = LanguageList.objects.exclude(name=current_list).all() return render_template(request, "language_list.html", {"languages": languages, 'lang_ed_form': languages_editabletable_form, "current_list": current_list, "otherLanguageLists": otherLanguageLists, "wordlist": getDefaultWordlist(request), "clades": Clade.objects.all()}) @csrf_protect @logExceptions def exportLanguageListCsv(request, languages=[]): """ @param languages :: [Language] """ fields = request.GET['exportCsv'].split(',') rows = [l.getCsvRow(*fields) for l in languages] rows.insert(0, ['"' + f + '"' for f in fields]) # Add headline # Composing .csv data: data = '\n'.join([','.join(row) for row in rows]) # Filename: filename = "%s.%s.csv" % \ (datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d'), getDefaultLanguagelist(request)) # Answering request: response = HttpResponse(data) response['Content-Disposition'] = ('attachment;filename="%s"' % filename) response['Control-Type'] = 'text/csv; charset=utf-8' response['Pragma'] = 'public' response['Expires'] = 0 response['Cache-Control'] = 'must-revalidate, post-check=0, pre-check=0' return response @csrf_protect @logExceptions def view_clades(request): if request.method == 'POST': # Updating existing clades: if 'clades' in request.POST: cladeTableForm = CladeTableForm(request.POST) # Flag to see if a clade changed: cladeChanged = False # Updating individual clades: try: cladeTableForm.validate() cladeChanged = cladeTableForm.handle(request) except Exception as e: logging.exception('Problem updating clades in view_clades.') messages.error(request, 'Sorry, the server had problems ' 'updating at least on clade: %s' % e) # Updating language clade relations for changed clades: if cladeChanged: updateLanguageCladeRelations() # Adding a new clade: elif 'addClade' in request.POST: cladeCreationForm = CladeCreationForm(request.POST) try: cladeCreationForm.validate() newClade = Clade(**cladeCreationForm.data) with transaction.atomic(): newClade.save(force_insert=True) except Exception as e: logging.exception('Problem creating clade in view_clades.') messages.error(request, 'Sorry, the server had problems ' 'creating the clade: %s' % e) # Deleting an existing clade: elif 'deleteClade' in request.POST: cladeDeletionForm = CladeDeletionForm(request.POST) try: cladeDeletionForm.validate() with transaction.atomic(): # Making sure the clade exists: clade = Clade.objects.get(**cladeDeletionForm.data) # Make sure to update things referencing clade here! # Deleting the clade: Clade.objects.filter(id=clade.id).delete() # Write message about clade deletion: messages.success(request, 'Deleted clade "%s".' % clade.cladeName) except Exception as e: logging.exception('Problem deleting clade in view_clades.') messages.error(request, 'Sorry, the server had problems ' 'deleting the clade: %s' % e) return HttpResponseRedirect('/clades/') # Extra handling for graphs. See #145. if request.method == 'GET': if 'plot' in request.GET: return render_template(request, "distributionPlot.html") form = CladeTableForm() for clade in Clade.objects.all(): clade.idField = clade.id form.elements.append_entry(clade) return render_template(request, "clades.html", {'clades': form}) @csrf_protect @logExceptions def view_sndComp(request): if request.method == 'POST': if 'sndComps' in request.POST: form = SndCompTableForm(request.POST) for entry in form.elements: data = entry.data try: with transaction.atomic(): sndComp = SndComp.objects.get(id=data['idField']) if sndComp.isChanged(**data): try: problem = sndComp.setDelta(**data) if problem is None: sndComp.save() else: messages.error( request, sndComp.deltaReport(**problem)) except Exception: logging.exception('Exception while saving ' 'POST in view_sndComp.') messages.error(request, 'The server had ' 'problems saving the change ' 'to "%s".' % sndComp.lgSetName) except Exception as e: logging.exception('Exception while accessing ' 'entry in view_sndComp.', extra=data) messages.error(request, 'Sorry, the server had problems ' 'saving at least one SndComp entry: %s' % e) # Adding a new SndComp: elif 'addSndComp' in request.POST: sndCompCreationForm = SndCompCreationForm(request.POST) try: sndCompCreationForm.validate() newSndComp = SndComp(**sndCompCreationForm.data) with transaction.atomic(): newSndComp.save(force_insert=True) except Exception as e: logging.exception('Problem creating entry in view_sndComp.') messages.error(request, 'Sorry, the server had problems ' 'creating the SndComp language set: %s' % e) # Deleting an existing SndComp: elif 'deleteSndComp' in request.POST: sndCompDeletionForm = SndCompDeletionForm(request.POST) try: sndCompDeletionForm.validate() with transaction.atomic(): # Making sure the SndComp exists: sndComp = SndComp.objects.get(**sndCompDeletionForm.data) # Make sure to update things referencing SndCom here! # Deleting the SndComp: SndComp.objects.filter(id=sndComp.id).delete() # Write message about SndComp deletion: messages.success(request, 'Deleted set "%s"' % sndComp.lgSetName) except Exception as e: logging.exception('Problem deleting entry in view_sndComp.') messages.error(request, 'Sorry, the server had problems ' 'deleting the SndComp language set: %s' % e) form = SndCompTableForm() sndComps = SndComp.objects.order_by( "lv0", "lv1", "lv2", "lv3").all() for s in sndComps: s.idField = s.id c = s.getClade() if c is not None: s.cladeName = c.cladeName form.elements.append_entry(s) return render_template(request, "sndComp.html", {'sndComps': form}) @logExceptions def reorder_language_list(request, language_list): language_id = getDefaultLanguageId(request) language_list = LanguageList.objects.get(name=language_list) languages = language_list.languages.all().order_by("languagelistorder") ReorderForm = make_reorder_languagelist_form(languages) if request.method == "POST": form = ReorderForm(request.POST, initial={"language": language_id}) if form.is_valid(): language_id = int(form.cleaned_data["language"]) setDefaultLanguageId(request, language_id) language = Language.objects.get(id=language_id) if form.data["submit"] == "Finish": language_list.sequentialize() return HttpResponseRedirect( reverse("view-language-list", args=[language_list.name])) else: if form.data["submit"] == "Move up": move_language(language, language_list, -1) elif form.data["submit"] == "Move down": move_language(language, language_list, 1) else: assert False, "This shouldn't be able to happen" return HttpResponseRedirect( reverse("reorder-language-list", args=[language_list.name])) else: # pressed Finish without submitting changes return HttpResponseRedirect( reverse("view-language-list", args=[language_list.name])) else: # first visit form = ReorderForm(initial={"language": language_id}) return render_template( request, "reorder_language_list.html", {"language_list": language_list, "form": form}) @logExceptions def reorder_meaning_list(request, meaning_list): meaning_id = getDefaultLanguageId(request) meaning_list = MeaningList.objects.get(name=meaning_list) meanings = meaning_list.meanings.all().order_by("meaninglistorder") ReorderForm = make_reorder_meaninglist_form(meanings) if request.method == "POST": form = ReorderForm(request.POST, initial={"meaning": meaning_id}) if form.is_valid(): meaning_id = int(form.cleaned_data["meaning"]) setDefaultMeaningId(request, meaning_id) meaning = Meaning.objects.get(id=meaning_id) if form.data["submit"] == "Finish": meaning_list.sequentialize() return HttpResponseRedirect( reverse("view-wordlist", args=[meaning_list.name])) else: if form.data["submit"] == "Move up": move_meaning(meaning, meaning_list, -1) elif form.data["submit"] == "Move down": move_meaning(meaning, meaning_list, 1) else: assert False, "This shouldn't be able to happen" return HttpResponseRedirect( reverse("reorder-meaning-list", args=[meaning_list.name])) else: # pressed Finish without submitting changes return HttpResponseRedirect( reverse("view-wordlist", args=[meaning_list.name])) else: # first visit form = ReorderForm(initial={"meaning": meaning_id}) return render_template( request, "reorder_meaning_list.html", {"meaning_list": meaning_list, "form": form}) @logExceptions def move_language(language, language_list, direction): assert direction in (-1, 1) languages = list(language_list.languages.order_by("languagelistorder")) index = languages.index(language) if index == 0 and direction == -1: language_list.remove(language) language_list.append(language) else: try: neighbour = languages[index + direction] language_list.swap(language, neighbour) except IndexError: language_list.insert(0, language) @logExceptions def move_meaning(meaning, meaning_list, direction): assert direction in (-1, 1) meanings = list(meaning_list.meanings.order_by("meaninglistorder")) index = meanings.index(meaning) if index == 0 and direction == -1: meaning_list.remove(meaning) meaning_list.append(meaning) else: try: neighbour = meanings[index + direction] meaning_list.swap(meaning, neighbour) except IndexError: meaning_list.insert(0, meaning) @csrf_protect @logExceptions def view_language_wordlist(request, language, wordlist): setDefaultLanguage(request, language) setDefaultWordlist(request, wordlist) try: wordlist = MeaningList.objects.get(name=wordlist) except MeaningList.DoesNotExist: raise Http404("MeaningList '%s' does not exist" % wordlist) # clean language name try: language = Language.objects.get(ascii_name=language) except Language.DoesNotExist: language = get_canonical_language(language, request) return HttpResponseRedirect( reverse("view-language-wordlist", args=[language.ascii_name, wordlist.name])) if request.method == 'POST': # Updating lexeme table data: if 'lex_form' in request.POST: try: form = LexemeTableLanguageWordlistForm(request.POST) form.validate() form.handle(request) except Exception as e: logging.exception('Problem updating lexemes ' 'in view_language_wordlist.') messages.error(request, 'Sorry, the server had problems ' 'updating at least one lexeme: %s' % e) elif 'editCognateClass' in request.POST: try: form = LexemeTableEditCognateClassesForm(request.POST) form.validate() form.handle(request) except Exception: logging.exception('Problem handling editCognateClass.') elif 'addMissingLexemes' in request.POST: try: form = AddMissingLexemsForLanguageForm(request.POST) form.validate() form.handle(request) except Exception as e: logging.exception( 'Problem with AddMissingLexemsForLanguageForm ' 'in view_language_wordlist') messages.error(request, 'Sorry, the server had problems ' 'adding missing lexemes: %s' % e) elif 'removeEmptyLexemes' in request.POST: try: form = RemoveEmptyLexemsForLanguageForm(request.POST) form.validate() form.handle(request) except Exception as e: logging.exception( 'Problem with RemoveEmptyLexemsForLanguageForm ' 'in view_language_wordlist') messages.error(request, 'Sorry, the server had problems ' 'removing empty lexemes: %s' % e) return HttpResponseRedirect( reverse("view-language-wordlist", args=[language.ascii_name, wordlist.name])) # collect data lexemes = Lexeme.objects.filter( language=language, meaning__in=wordlist.meanings.all() ).select_related( "meaning", "language").order_by( "meaning__gloss").prefetch_related( "cognatejudgement_set", "cognatejudgement_set__cognatejudgementcitation_set", "cognate_class", "lexemecitation_set") # Used for #219: cIdCognateClassMap = {} # :: CognateClass.id -> CognateClass notTargetCountPerMeaning = {} for lex in lexemes: if lex.meaning in notTargetCountPerMeaning: if lex.not_swadesh_term: notTargetCountPerMeaning[lex.meaning] += 1 else: if lex.not_swadesh_term: notTargetCountPerMeaning[lex.meaning] = 1 else: notTargetCountPerMeaning[lex.meaning] = 0 lexemes_editabletable_form = LexemeTableLanguageWordlistForm() for lex in lexemes: lex.notTargetCountPerMeaning = notTargetCountPerMeaning[lex.meaning] lexemes_editabletable_form.lexemes.append_entry(lex) ccs = lex.cognate_class.all() for cc in ccs: cIdCognateClassMap[cc.id] = cc otherMeaningLists = MeaningList.objects.exclude(id=wordlist.id).all() languageList = LanguageList.objects.prefetch_related('languages').get( name=getDefaultLanguagelist(request)) typeahead = json.dumps({ l.utf8_name: reverse( "view-language-wordlist", args=[l.ascii_name, wordlist.name]) for l in languageList.languages.all()}) prev_language, next_language = \ get_prev_and_next_languages(request, language, language_list=languageList) cognateClasses = json.dumps([{'id': c.id, 'alias': c.alias, 'placeholder': c.combinedRootPlaceholder} for c in cIdCognateClassMap.values()]) return render_template(request, "language_wordlist.html", {"language": language, "lexemes": lexemes, "prev_language": prev_language, "next_language": next_language, "wordlist": wordlist, "otherMeaningLists": otherMeaningLists, "lex_ed_form": lexemes_editabletable_form, "cognateClasses": cognateClasses, "notTargetCountPerMeaning": notTargetCountPerMeaning, "typeahead": typeahead}) @login_required @logExceptions def view_language_check(request, language=None, wordlist=None): ''' Provides an html snipped that contains some sanity checks for a given language against a given wordlist. If language or wordlist are omitted they are inferred vie defaultModels. This function is a result of #159. @param language :: str | None @param wordlist :: str | None ''' # Infer defaultModels where neccessary: if language is None: language = getDefaultLanguage(request) if wordlist is None: wordlist = getDefaultWordlist(request) # Fetch data to work with: language = Language.objects.get(ascii_name=language) wordlist = MeaningList.objects.get(name=wordlist) meanings = wordlist.meanings.all() # Calculate meaningCounts: meaningCountDict = {m.id: 0 for m in meanings} mIds = Lexeme.objects.filter( language=language, meaning__in=meanings, not_swadesh_term=0).values_list( "meaning_id", flat=True) for mId in mIds: meaningCountDict[mId] += 1 meaningCounts = [{'count': meaningCountDict[m.id], 'meaning': m.gloss} for m in meanings if meaningCountDict[m.id] != 1] meaningCounts.sort(key=lambda x: x['count']) # Render report: return render_template(request, "language_check.html", {"meaningCounts": meaningCounts}) @login_required @logExceptions def add_language_list(request): """Start a new language list by cloning an old one""" if request.method == "POST": form = AddLanguageListForm(request.POST) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(reverse("view-all-languages")) if form.is_valid(): form.save() new_list = LanguageList.objects.get(name=form.cleaned_data["name"]) other_list = LanguageList.objects.get( name=form.cleaned_data["language_list"]) otherLangs = other_list.languages.all().order_by( "languagelistorder") for language in otherLangs: new_list.append(language) # edit_language_list(request, # language_list=form.cleaned_data["name"]) return HttpResponseRedirect(reverse( "edit-language-list", args=[form.cleaned_data["name"]])) else: form = AddLanguageListForm() return render_template(request, "add_language_list.html", {"form": form}) @login_required @logExceptions def edit_language_list(request, language_list=None): language_list = get_canonical_language_list( language_list, request) # a language list object language_list_all = LanguageList.objects.get(name=LanguageList.ALL) included_languages = language_list.languages.all().order_by( "languagelistorder") excluded_languages = language_list_all.languages.exclude( id__in=language_list.languages.values_list( "id", flat=True)).order_by("languagelistorder") if request.method == "POST": name_form = EditLanguageListForm(request.POST, instance=language_list) if "cancel" in name_form.data: # has to be tested before data is cleaned return HttpResponseRedirect( reverse('view-language-list', args=[language_list.name])) list_form = EditLanguageListMembersForm(request.POST) list_form.fields["included_languages"].queryset = included_languages list_form.fields["excluded_languages"].queryset = excluded_languages if name_form.is_valid() and list_form.is_valid(): changed_members = False exclude = list_form.cleaned_data["excluded_languages"] include = list_form.cleaned_data["included_languages"] if include: language_list.remove(include) changed_members = True if exclude: language_list.append(exclude) changed_members = True if changed_members: language_list.save() name_form.save() return HttpResponseRedirect( reverse('edit-language-list', args=[language_list.name])) # changed name name_form.save() return HttpResponseRedirect( reverse('view-language-list', args=[name_form.cleaned_data["name"]])) else: name_form = EditLanguageListForm(instance=language_list) list_form = EditLanguageListMembersForm() list_form.fields["included_languages"].queryset = included_languages list_form.fields["excluded_languages"].queryset = excluded_languages return render_template(request, "edit_language_list.html", {"name_form": name_form, "list_form": list_form, "n_included": included_languages.count(), "n_excluded": excluded_languages.count()}) @login_required @logExceptions def delete_language_list(request, language_list): language_list = LanguageList.objects.get(name=language_list) language_list.delete() return HttpResponseRedirect(reverse("view-all-languages")) @login_required @logExceptions def language_add_new(request, language_list): language_list = LanguageList.objects.get(name=language_list) if request.method == 'POST': form = AddLanguageForm(request.POST) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(reverse("view-language-list", args=[language_list.name])) if form.is_valid(): with transaction.atomic(): form.save() language = Language.objects.get( ascii_name=form.cleaned_data["ascii_name"]) try: language_list.append(language) except IntegrityError: pass # automatically inserted into LanguageList.DEFAULT return HttpResponseRedirect(reverse("language-edit", args=[language.ascii_name])) else: # first visit form = AddLanguageForm() return render_template(request, "language_add_new.html", {"form": form}) @login_required @user_passes_test(lambda u: u.is_staff) @logExceptions def edit_language(request, language): try: language = Language.objects.get(ascii_name=language) except Language.DoesNotExist: language = get_canonical_language(language, request) return HttpResponseRedirect(reverse("language-edit", args=[language.ascii_name])) if request.method == 'POST': form = EditSingleLanguageForm(request.POST) try: form.validate() data = form.data language = Language.objects.get(id=data['idField']) if language.isChanged(**data): problem = language.setDelta(request, **data) if problem is None: language.save() return HttpResponseRedirect(reverse("view-all-languages")) else: messages.error(request, language.deltaReport(**problem)) except Exception as e: logging.exception('Problem updating single language ' 'in edit_language.') messages.error(request, 'Sorry, the server could not update ' 'the language. %s' % e) language.idField = language.id form = EditSingleLanguageForm(obj=language) return render_template(request, "language_edit.html", {"language": language, "form": form}) @logExceptions def overview_language(request, language): try: language = Language.objects.get(ascii_name=language) except Language.DoesNotExist: language = get_canonical_language(language, request) return HttpResponseRedirect(reverse("language-overview", args=[language.ascii_name])) fileName = "Language-Chapter:-%s.md" % (language.ascii_name) admin_notes = '' if request.user.is_authenticated: admin_notes = """ _For contributors copy the beneath mentioned first template text and follow the link to [create a new page](https://github.com/lingdb/CoBL/wiki/%s)_ ``` #### Notes on Orthography To be written soon. #### Notes on Transliteration (if appropriate) To be written soon. #### Problematic Meanings To be written soon. ``` _and follow this link to [create a new public page](https://github.com/lingdb/CoBL-public/wiki/Language-Chapter:-%s) with the following template:_ ``` Content comming soon. This article is currently worked on in [private](https://github.com/lingdb/CoBL/wiki/Language-Chapter:-%s). ``` """ % (fileName, fileName, fileName) return render_template( request, "language_overview.html", {"language": language, "content": fetchMarkdown(fileName, admin_notes)}) @login_required @logExceptions def delete_language(request, language): try: language = Language.objects.get(ascii_name=language) except Language.DoesNotExist: language = get_canonical_language(language, request) return HttpResponseRedirect(reverse("language-delete"), args=[language.ascii_name]) language.delete() return HttpResponseRedirect(reverse("view-all-languages")) # -- /meaning(s)/ and /wordlist/ ------------------------------------------ @logExceptions def view_wordlists(request): wordlists = MeaningList.objects.all() return render_template(request, "wordlists_list.html", {"wordlists": wordlists}) @csrf_protect @logExceptions def view_wordlist(request, wordlist=MeaningList.DEFAULT): try: wordlist = MeaningList.objects.get(name=wordlist) except MeaningList.DoesNotExist: raise Http404("MeaningList '%s' does not exist" % wordlist) setDefaultWordlist(request, wordlist.name) if request.method == 'POST': if 'wordlist' in request.POST: mltf = MeaningListTableForm(request.POST) mltf.validate() mltf.handle(request) try: languageList = LanguageList.objects.get( name=getDefaultLanguagelist(request)) except LanguageList.DoesNotExist: raise Http404("LanguageList '%s' does not exist" % getDefaultLanguagelist(request)) mltf = MeaningListTableForm() meanings = wordlist.meanings.order_by( "meaninglistorder").prefetch_related('lexeme_set').all() for meaning in meanings: meaning.computeCounts(languageList=languageList) mltf.meanings.append_entry(meaning) return render_template(request, "wordlist.html", {"mltf": mltf, "wordlist": wordlist}) @login_required @logExceptions def edit_wordlist(request, wordlist): wordlist = MeaningList.objects.get(name=wordlist) if request.method == 'POST': form = EditMeaningListForm(request.POST, instance=wordlist) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(reverse("view-wordlist", args=[wordlist.name])) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("view-wordlist", args=[wordlist.name])) else: form = EditMeaningListForm(instance=wordlist) return render_template(request, "edit_wordlist.html", {"wordlist": wordlist, "form": form}) @login_required @logExceptions def reorder_wordlist(request, wordlist): meaning_id = getDefaultMeaningId(request) wordlist = MeaningList.objects.get(name=wordlist) meanings = wordlist.meanings.all().order_by("meaninglistorder") ReorderForm = make_reorder_meaninglist_form(meanings) if request.method == "POST": form = ReorderForm(request.POST, initial={"meaning": meaning_id}) if form.is_valid(): meaning_id = int(form.cleaned_data["meaning"]) setDefaultMeaningId(request, meaning_id) meaning = Meaning.objects.get(id=meaning_id) if form.data["submit"] == "Finish": return HttpResponseRedirect(reverse("view-wordlist", args=[wordlist.name])) else: if form.data["submit"] == "Move up": move_meaning(meaning, wordlist, -1) elif form.data["submit"] == "Move down": move_meaning(meaning, wordlist, 1) else: assert False, "This shouldn't be able to happen" return HttpResponseRedirect(reverse("reorder-wordlist", args=[wordlist.name])) else: # pressed Finish without submitting changes return HttpResponseRedirect(reverse("view-wordlist", args=[wordlist.name])) else: # first visit form = ReorderForm(initial={"meaning": meaning_id}) return render_template(request, "reorder_wordlist.html", {"wordlist": wordlist, "form": form}) @logExceptions def move_meaning(meaning, wordlist, direction): assert direction in (-1, 1) meanings = list(wordlist.meanings.all().order_by("meaninglistorder")) index = meanings.index(meaning) if index == 0 and direction == -1: wordlist.remove(meaning) wordlist.append(meaning) else: try: neighbour = meanings[index + direction] wordlist.swap(meaning, neighbour) except IndexError: wordlist.insert(0, meaning) @login_required @logExceptions def add_meaning_list(request): """Start a new meaning list by cloning an old one if desired""" if request.method == "POST": form = AddMeaningListForm(request.POST) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(reverse("view-all-meanings")) if form.is_valid(): form.save() new_list = MeaningList.objects.get(name=form.cleaned_data["name"]) """check if user wants a clone""" try: other_list = MeaningList.objects.get( name=form.cleaned_data["meaning_list"]) otherMeanings = other_list.meanings.all().order_by( "meaninglistorder") for m in otherMeanings: new_list.append(m) except ObjectDoesNotExist: """create only a new empty meaning list""" pass setDefaultWordlist(request, form.cleaned_data["name"]) return HttpResponseRedirect(reverse( "edit-meaning-list", args=[form.cleaned_data["name"]])) else: form = AddMeaningListForm() return render_template(request, "add_meaning_list.html", {"form": form}) @login_required @logExceptions def edit_meaning_list(request, meaning_list=None): if meaning_list == None: meaning_list = getDefaultWordlist(request) meaning_list = get_canonical_meaning_list( meaning_list, request) # a meaning list object meaning_list_all = MeaningList.objects.get(name=MeaningList.ALL) included_meanings = meaning_list.meanings.all().order_by( "meaninglistorder") excluded_meanings = meaning_list_all.meanings.exclude( id__in=meaning_list.meanings.values_list( "id", flat=True)).order_by("meaninglistorder") if request.method == "POST": name_form = EditMeaningListForm(request.POST, instance=meaning_list) if "cancel" in name_form.data: # has to be tested before data is cleaned return HttpResponseRedirect( reverse('view-wordlist', args=[meaning_list.name])) if "delete" in name_form.data: mname = meaning_list.name try: ml = MeaningListOrder.objects.filter( meaning_list_id=meaning_list.id) ml.delete() except: setDefaultWordlist(request, MeaningList.DEFAULT) messages.error(request, 'Error while deleting "' + mname + '": meanings in meaninglistorder could not be deleted!') return HttpResponseRedirect( reverse('view-frontpage')) try: ml = MeaningList.objects.filter( name=mname) ml.delete() except: setDefaultWordlist(request, MeaningList.DEFAULT) messages.error(request, 'Error while deleting "'+ mname + '": meaninglist "' + mname + '" does not exist!') return HttpResponseRedirect( reverse('view-frontpage')) setDefaultWordlist(request, MeaningList.DEFAULT) messages.success(request, 'The meaning list "' + mname + '" was successfully deleted.') return HttpResponseRedirect( reverse('edit-meaning-list', args=[MeaningList.DEFAULT])) list_form = EditMeaningListMembersForm(request.POST) list_form.fields["included_meanings"].queryset = included_meanings list_form.fields["excluded_meanings"].queryset = excluded_meanings if name_form.is_valid() and list_form.is_valid(): changed_members = False exclude = list_form.cleaned_data["excluded_meanings"] include = list_form.cleaned_data["included_meanings"] if include: meaning_list.remove(include) changed_members = True if exclude: meaning_list.append(exclude) changed_members = True if changed_members: meaning_list.save() name_form.save() return HttpResponseRedirect( reverse('edit-meaning-list', args=[meaning_list.name])) # changed name name_form.save() return HttpResponseRedirect( reverse('view-wordlist', args=[name_form.cleaned_data["name"]])) else: name_form = EditMeaningListForm(instance=meaning_list) list_form = EditMeaningListMembersForm() list_form.fields["included_meanings"].queryset = included_meanings list_form.fields["excluded_meanings"].queryset = excluded_meanings return render_template(request, "edit_meaning_list.html", {"name_form": name_form, "list_form": list_form, "n_included": included_meanings.count(), "n_excluded": excluded_meanings.count()}) @login_required @logExceptions def meaning_add_new(request): if request.method == 'POST': form = EditMeaningForm(request.POST) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(reverse("view-meanings")) if form.is_valid(): form.save() return HttpResponseRedirect( reverse("meaning-report", args=[form.cleaned_data["gloss"]])) else: # first visit form = EditMeaningForm() return render_template(request, "meaning_add_new.html", {"form": form}) @login_required @logExceptions def edit_meaning(request, meaning): try: meaning = Meaning.objects.get(gloss=meaning) except Meaning.DoesNotExist: meaning = get_canonical_meaning(meaning) return HttpResponseRedirect( reverse("edit-meaning", args=[meaning.gloss])) if request.method == 'POST': form = EditMeaningForm(request.POST, instance=meaning) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(meaning.get_absolute_url()) if form.is_valid(): form.save() return HttpResponseRedirect(meaning.get_absolute_url()) else: form = EditMeaningForm(instance=meaning) return render_template(request, "meaning_edit.html", {"meaning": meaning, "form": form}) @logExceptions def view_citations_inline_form(request, model): assert model == Lexeme or model == CognateClass, "Unexpected model" instance = model.objects.get(id=request.POST.get("id")) def getEntries(query): entries = [] for citation in query: entries.append({ 'id': citation.id, 'source_id': citation.source_id, 'source_name': citation.source.shorthand, 'pages': citation.pages, 'comment': citation.comment}) return entries if model == Lexeme: entries = getEntries( instance.lexemecitation_set.all().select_related('source')) return JsonResponse({ 'id': instance.id, 'model': 'Lexeme', 'entries': entries }) elif model == CognateClass: entries = getEntries( instance.cognateclasscitation_set.all().select_related('source')) return JsonResponse({ 'id': instance.id, 'model': 'CognateClass', 'entries': entries }) @logExceptions def submit_citations_inline_form(request, model): assert model == Lexeme or model == CognateClass, "Unexpected model" instance = model.objects.get(id=request.POST.get("id")) if model == Lexeme: citationModel = LexemeCitation querySet = instance.lexemecitation_set elif model == CognateClass: citationModel = CognateClassCitation querySet = instance.cognateclasscitation_set citations = {str(citation.id): citation for citation in querySet.all()} for entry in json.loads(request.POST.get("source_data")): if 'id' in entry and entry['id'] in citations: citation = citations.pop(entry['id']) citation.source_id = int(entry['source_id']) citation.pages = entry['pages'] citation.comment = entry['comment'] citation.save() elif model == Lexeme: LexemeCitation.objects.create( lexeme_id=instance.id, source_id=int(entry['source_id']), pages=entry['pages'], comment=entry['comment']) elif model == CognateClass: CognateClassCitation.objects.create( cognate_class_id=instance.id, source_id=int(entry['source_id']), pages=entry['pages'], comment=entry['comment'], rfcWeblink=entry[rfcWeblink]) citationModel.objects.filter(id__in=citations.keys()).delete() return JsonResponse({ 'id': instance.id, 'model': request.POST.get("model"), 'badgeUpdate': querySet.count()}) @login_required @csrf_protect @logExceptions def citation_form_event(request): model_dict = {'CognateClass': CognateClass, 'Lexeme': Lexeme} handlerDict = {'viewCit': view_citations_inline_form, 'Submit': submit_citations_inline_form} if request.POST.get("model") not in model_dict or\ request.POST.get("action") not in handlerDict: return None model = model_dict[request.POST.get("model")] return handlerDict[request.POST.get("action")](request, model) @csrf_protect @logExceptions def view_meaning(request, meaning, language_list, lexeme_id=None): if request.user.is_authenticated: cit_form_response = citation_form_event(request) if cit_form_response: return cit_form_response setDefaultMeaning(request, meaning) if language_list is None: language_list = getDefaultLanguagelist(request) setDefaultLanguagelist(request, language_list) # Normalize calling parameters canonical_gloss = get_canonical_meaning(meaning).gloss current_language_list = get_canonical_language_list(language_list, request) mNonCan = meaning != canonical_gloss lNonCur = language_list != current_language_list.name if mNonCan or lNonCur: return HttpResponseRedirect( reverse("view-meaning-languages", args=[canonical_gloss, current_language_list.name])) else: meaning = Meaning.objects.get(gloss=meaning) # Handling POST requests: if request.method == 'POST': # Handling LexemeTableViewMeaningsForm: if 'meang_form' in request.POST: try: lexemesTableForm = LexemeTableViewMeaningsForm(request.POST) lexemesTableForm.validate() lexemesTableForm.handle(request) except Exception as e: logging.exception('Problem updating lexemes in view_meaning.') messages.error(request, "Sorry, the server had problems " "updating at least one lexeme: %s" % e) return HttpResponseRedirect( reverse("view-meaning-languages", args=[canonical_gloss, current_language_list.name])) # Handling editCognateClass (#219): elif 'editCognateClass' in request.POST: try: form = LexemeTableEditCognateClassesForm(request.POST) form.validate() form.handle(request) except Exception: logging.exception('Problem handling editCognateClass.') return HttpResponseRedirect( reverse("view-meaning-languages", args=[canonical_gloss, current_language_list.name])) # Handling ChooseCognateClassForm: else: # not ('meang_form' in request.POST) cognate_form = ChooseCognateClassForm(request.POST) if cognate_form.is_valid(): cj = cognate_form.handle(request, lexeme_id) # change this to a reverse() pattern return HttpResponseRedirect(anchored( reverse("lexeme-add-cognate-citation", args=[lexeme_id, cj.id]))) # Gather lexemes: lexemes = Lexeme.objects.filter( meaning=meaning, language__in=current_language_list.languages.exclude(level0=0).all(), language__languagelistorder__language_list=current_language_list ).order_by( "language" ).select_related( "language", "meaning").prefetch_related( "cognatejudgement_set", "cognatejudgement_set__cognatejudgementcitation_set", "lexemecitation_set", "cognate_class", "language__languageclade_set", "language__clades") # Gather cognate classes and provide form: cognateClasses = CognateClass.objects.filter(lexeme__in=lexemes).distinct() cognate_form = ChooseCognateClassForm() cognate_form.fields["cognate_class"].queryset = cognateClasses # Fill lexemes_editabletable_form: lexemes_editabletable_form = LexemeTableViewMeaningsForm() for lex in lexemes: lexemes_editabletable_form.lexemes.append_entry(lex) # Fetch meaningList: meaningList = MeaningList.objects.prefetch_related("meanings").get( name=getDefaultWordlist(request)) # Compute typeahead: typeahead = json.dumps({ m.gloss: reverse( "view-meaning-languages", args=[m.gloss, current_language_list.name]) for m in meaningList.meanings.all()}) # Calculate prev/next meanings: prev_meaning, next_meaning = get_prev_and_next_meanings( request, meaning, meaning_list=meaningList) return render_template( request, "view_meaning.html", {"meaning": meaning, "prev_meaning": prev_meaning, "next_meaning": next_meaning, "lexemes": lexemes, "cognate_form": cognate_form, "cognateClasses": json.dumps([{'id': c.id, 'alias': c.alias, 'placeholder': c.combinedRootPlaceholder} for c in cognateClasses]), "add_cognate_judgement": lexeme_id, "lex_ed_form": lexemes_editabletable_form, "typeahead": typeahead, "clades": Clade.objects.all()}) @csrf_protect @logExceptions def view_cognateclasses(request, meaning): if request.user.is_authenticated: cit_form_response = citation_form_event(request) if cit_form_response: return cit_form_response setDefaultMeaning(request, meaning) # Handle POST of AddCogClassTableForm: if request.method == 'POST': if 'cogclass_form' in request.POST: try: cogClassTableForm = AddCogClassTableForm(request.POST) cogClassTableForm.validate() cogClassTableForm.handle(request) except ValidationError as e: logging.exception( 'Validation did not work in view_cognateclasses.') messages.error(request, ' '.join(e.messages)) except Exception as e: logging.exception('Problem updating CognateClasses ' 'in view_cognateclasses.') messages.error(request, 'Sorry, the server had problems ' 'updating at least one entry: %s' % e) elif 'mergeIds' in request.POST: try: # Parsing and validating data: mergeCCForm = MergeCognateClassesForm(request.POST) mergeCCForm.validate() mergeCCForm.handle(request) except Exception as e: logging.exception('Problem merging CognateClasses ' 'in view_cognateclasses.') messages.error(request, 'Sorry, the server had problems ' 'merging cognate classes: %s' % e) else: logging.error('Unexpected POST request in view_cognateclasses.') messages.error(request, 'Sorry, the server did ' 'not understand your request.') return HttpResponseRedirect(reverse("edit-cogclasses", args=[meaning])) # Acquiring languageList: try: languageList = LanguageList.objects.get( name=getDefaultLanguagelist(request)) except LanguageList.DoesNotExist: languageList = LanguageList.objects.get( name=LanguageList.ALL) # languageIds implicated: languageIds = languageList.languagelistorder_set.exclude( language__level0=0).values_list( 'language_id', flat=True) # Cognate classes to use: ccl_ordered = CognateClass.objects.filter( cognatejudgement__lexeme__meaning__gloss=meaning, cognatejudgement__lexeme__language_id__in=languageIds ).prefetch_related('lexeme_set').order_by('alias').distinct() # Citations count ccl_ordered = ccl_ordered.extra({'citCount': 'SELECT COUNT(*) ' 'FROM lexicon_cognateclasscitation ' 'WHERE ' 'lexicon_cognateclasscitation.' 'cognate_class_id ' '= lexicon_cognateclass.id', }) # Computing counts for ccs: for cc in ccl_ordered: cc.computeCounts(languageList=languageList) def cmpKey(x): return [-x.cladeCount, -x.lexemeCount, len(x.alias)] ccl_ordered = sorted(ccl_ordered, key=cmpKey) # Clades to use for #112: clades = Clade.objects.filter( id__in=LanguageClade.objects.filter( language__languagelistorder__language_list=languageList ).values_list('clade_id', flat=True)).exclude( hexColor='').exclude(shortName='').all() # Compute clade <-> cc connections: for c in clades: c.computeCognateClassConnections(ccl_ordered, languageList) # Filling cogclass_editabletable_form: cogclass_editabletable_form = AddCogClassTableForm(cogclass=ccl_ordered) # Fetch meaningList for typeahead and prev/next calculation: meaningList = MeaningList.objects.prefetch_related("meanings").get( name=getDefaultWordlist(request)) # Compute typeahead: typeahead = json.dumps({m.gloss: reverse("edit-cogclasses", args=[m.gloss]) for m in meaningList.meanings.all()}) # {prev_,next_,}meaning: try: meaning = Meaning.objects.get(gloss=meaning) except Meaning.DoesNotExist: raise Http404("Meaning '%s' does not exist" % meaning) prev_meaning, next_meaning = get_prev_and_next_meanings( request, meaning, meaning_list=meaningList) # Render and done: return render_template(request, "view_cognateclass_editable.html", {"meaning": meaning, "prev_meaning": prev_meaning, "next_meaning": next_meaning, "clades": clades, "cogclass_editable_form": cogclass_editabletable_form, "typeahead": typeahead}) ################################################################## @login_required @logExceptions def delete_meaning(request, meaning): # normalize meaning if meaning.isdigit(): meaning = Meaning.objects.get(id=int(meaning)) # if there are actions and lexeme_ids these should be preserved too return HttpResponseRedirect(reverse("meaning-report", args=[meaning.gloss])) else: meaning = Meaning.objects.get(gloss=meaning) meaning.delete() return HttpResponseRedirect(reverse("view-meanings")) # -- /lexeme/ ------------------------------------------------------------- @logExceptions def view_lexeme(request, lexeme_id): """For un-logged-in users, view only""" try: lexeme = Lexeme.objects.get(id=lexeme_id) except Lexeme.DoesNotExist: messages.info(request, "There is no lexeme with id=%s" % lexeme_id) raise Http404 prev_lexeme, next_lexeme = get_prev_and_next_lexemes(request, lexeme) return render_template(request, "lexeme_report.html", {"lexeme": lexeme, "prev_lexeme": prev_lexeme, "next_lexeme": next_lexeme}) @login_required @logExceptions def lexeme_edit(request, lexeme_id, action="", citation_id=0, cogjudge_id=0): if not action == "deletelist": try: lexeme = Lexeme.objects.get(id=lexeme_id) except Lexeme.DoesNotExist: messages.info(request, "There is no lexeme with id=%s" % lexeme_id) raise Http404 citation_id = int(citation_id) cogjudge_id = int(cogjudge_id) form = None def DELETE_CITATION_WARNING_MSG(): messages.warning( request, oneline("""Deletion of the final citation is not allowed. If you need to, add a new one before deleting the current one.""")) def DELETE_COGJUDGE_WARNING_MSG(citation): msg = Template(oneline("""Deletion of final cognate citation is not allowed (Delete the cognate class {{ alias }} itself instead, if that's what you mean)""")) context = RequestContext(request) context["alias"] = citation.cognate_judgement.cognate_class.alias messages.warning( request, msg.render(context)) def warn_if_lacking_cognate_judgement_citation(): for cognate_judgement in CognateJudgement.objects.filter( lexeme=lexeme): if CognateJudgementCitation.objects.filter( cognate_judgement=cognate_judgement).count() == 0: msg = Template(oneline("""<a href="{% url 'lexeme-add-cognate-citation' lexeme_id cogjudge_id %}#active">Lexeme has been left with cognate judgements lacking citations for cognate class {{ alias }}. Please fix this [click this message].</a>""")) context = RequestContext(request) context["lexeme_id"] = lexeme.id context["cogjudge_id"] = cognate_judgement.id context["alias"] = cognate_judgement.cognate_class.alias messages.warning(request, msg.render(context)) if action: # actions are: edit, edit-citation, add-citation def get_redirect_url(form, citation=None): """Pass citation objects to anchor the view in the lexeme page""" form_data = form.data["submit"].lower() if "new lexeme" in form_data: redirect_url = reverse("language-add-lexeme", args=[lexeme.language.ascii_name]) elif "back to language" in form_data: redirect_url = reverse('language-report', args=[lexeme.language.ascii_name]) elif "back to meaning" in form_data: redirect_url = '%s#lexeme_%s' % ( reverse("meaning-report", args=[lexeme.meaning.gloss]), lexeme.id) elif citation: redirect_url = citation.get_absolute_url() else: redirect_url = lexeme.get_absolute_url() return redirect_url # Handle POST data if request.method == 'POST': if action == "edit": form = EditLexemeForm(request.POST, instance=lexeme) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(lexeme.get_absolute_url()) if form.is_valid(): form.save() return HttpResponseRedirect(get_redirect_url(form)) elif action == "edit-citation": form = EditCitationForm(request.POST) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(lexeme.get_absolute_url()) if form.is_valid(): citation = LexemeCitation.objects.get(id=citation_id) update_object_from_form(citation, form) request.session["previous_citation_id"] = citation.id return HttpResponseRedirect( get_redirect_url(form, citation)) elif action == "add-citation": form = AddCitationForm(request.POST) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(lexeme.get_absolute_url()) if form.is_valid(): cd = form.cleaned_data citation = LexemeCitation( lexeme=lexeme, source=cd["source"], pages=cd["pages"], reliability="A", # `High` comment=cd["comment"]) try: citation.save() except IntegrityError: messages.warning( request, oneline("""Lexeme citations must be unique. This source is already cited for this lexeme.""")) request.session["previous_citation_id"] = citation.id return HttpResponseRedirect( get_redirect_url(form, citation)) elif action == "add-new-citation": form = AddCitationForm(request.POST) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(lexeme.get_absolute_url()) if form.is_valid(): cd = form.cleaned_data citation = LexemeCitation( lexeme=lexeme, source=cd["source"], pages=cd["pages"], reliability=cd["reliability"], comment=cd["comment"]) citation.save() request.session["previous_citation_id"] = citation.id return HttpResponseRedirect( get_redirect_url(form, citation)) elif action == "delink-citation": citation = LexemeCitation.objects.get(id=citation_id) try: citation.delete() except IntegrityError: DELETE_CITATION_WARNING_MSG() return HttpResponseRedirect(lexeme.get_absolute_url()) elif action == "delink-cognate-citation": citation = CognateJudgementCitation.objects.get(id=citation_id) try: citation.delete() except IntegrityError: DELETE_COGJUDGE_WARNING_MSG(citation) # warn_if_lacking_cognate_judgement_citation() return HttpResponseRedirect(get_redirect_url(form)) elif action == "edit-cognate-citation": form = EditCitationForm(request.POST) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(lexeme.get_absolute_url()) if form.is_valid(): citation = CognateJudgementCitation.objects.get( id=citation_id) update_object_from_form(citation, form) request.session[ "previous_cognate_citation_id"] = citation.id return HttpResponseRedirect( get_redirect_url(form, citation)) elif action == "add-cognate-citation": form = AddCitationForm(request.POST) if "cancel" in form.data: warn_if_lacking_cognate_judgement_citation() return HttpResponseRedirect(lexeme.get_absolute_url()) if form.is_valid(): judgements = CognateJudgement.objects.get(id=cogjudge_id) citation = CognateJudgementCitation.objects.create( cognate_judgement=judgements, **form.cleaned_data) request.session[ "previous_cognate_citation_id"] = citation.id return HttpResponseRedirect( get_redirect_url(form, citation)) elif action == "add-cognate": languagelist = get_canonical_language_list( getDefaultLanguagelist(request), request) redirect_url = '%s#lexeme_%s' % ( reverse("view-meaning-languages-add-cognate", args=[lexeme.meaning.gloss, languagelist, lexeme.id]), lexeme.id) return HttpResponseRedirect(redirect_url) else: assert not action # first visit, preload form with previous answer else: if not action == "deletelist": redirect_url = reverse('view-lexeme', args=[lexeme_id]) if action == "deletelist": lexeme_ids = [int(x.strip(" ")) for x in lexeme_id.split(",")] not_deleted_lexemes = [] deleted_lexemes = [] for lx in lexeme_ids: try: lexeme = Lexeme.objects.get(id=lx) deleted_lexemes.append(str(lx)) except Lexeme.DoesNotExist: not_deleted_lexemes.append(str(lx)) continue lexeme.delete() redirect_url = reverse("view-language-wordlist", args=[getDefaultLanguage(request), getDefaultWordlist(request)]) if len(not_deleted_lexemes) == 0: msg = Template(oneline("""All {{ cnt }} lexemes were deleted successfully""")) context = RequestContext(request) context["cnt"] = str(len(lexeme_ids)) messages.success( request, msg.render(context)) else: msg = Template(oneline("""These lexemes were NOT deleted successfully: {{ ids }}""")) context = RequestContext(request) context["ids"] = ", ".join(not_deleted_lexemes) messages.error( request, msg.render(context)) return HttpResponseRedirect(redirect_url) elif action == "edit": form = EditLexemeForm(instance=lexeme) # initial={"romanised":lexeme.romanised, # "phon_form":lexeme.phon_form, # "notes":lexeme.notes, # "meaning":lexeme.meaning}) elif action == "edit-citation": citation = LexemeCitation.objects.get(id=citation_id) form = EditCitationForm( initial={"pages": citation.pages, "reliability": citation.reliability, "comment": citation.comment}) elif action in ("add-citation", "add-new-citation"): previous_citation_id = request.session.get( "previous_citation_id") try: citation = LexemeCitation.objects.get( id=previous_citation_id) form = AddCitationForm( initial={"source": citation.source.id, "pages": citation.pages, "reliability": citation.reliability}) except LexemeCitation.DoesNotExist: form = AddCitationForm() elif action == "edit-cognate-citation": citation = CognateJudgementCitation.objects.get(id=citation_id) form = EditCitationForm( initial={"pages": citation.pages, "reliability": citation.reliability, "comment": citation.comment}) elif action == "delink-cognate": cj = CognateJudgement.objects.get(id=cogjudge_id) cj.delete() return HttpResponseRedirect(redirect_url) elif action == "add-cognate-citation": previous_citation_id = request.session.get( "previous_cognate_citation_id") try: citation = CognateJudgementCitation.objects.get( id=previous_citation_id) form = AddCitationForm( initial={"source": citation.source.id, "pages": citation.pages, "reliability": citation.reliability}) # "comment":citation.comment}) except CognateJudgementCitation.DoesNotExist: form = AddCitationForm() # form = AddCitationForm() elif action == "add-cognate": languagelist = get_canonical_language_list( getDefaultLanguagelist(request), request) redirect_url = '%s#lexeme_%s' % ( reverse("view-meaning-languages-add-cognate", args=[lexeme.meaning.gloss, languagelist, lexeme.id]), lexeme.id) return HttpResponseRedirect(redirect_url) # redirect_url = '%s#lexeme_%s' % (reverse("meaning-report", # args=[lexeme.meaning.gloss]), lexeme.id) # return HttpResponseRedirect(redirect_url) elif action == "delink-citation": citation = LexemeCitation.objects.get(id=citation_id) try: citation.delete() except IntegrityError: DELETE_CITATION_WARNING_MSG() return HttpResponseRedirect(redirect_url) elif action == "delink-cognate-citation": citation = CognateJudgementCitation.objects.get(id=citation_id) try: citation.delete() except IntegrityError: DELETE_COGJUDGE_WARNING_MSG(citation) # warn_if_lacking_cognate_judgement_citation() return HttpResponseRedirect(redirect_url) elif action == "add-new-cognate": current_aliases = CognateClass.objects.filter( lexeme__in=Lexeme.objects.filter( meaning=lexeme.meaning) ).distinct().values_list("alias", flat=True) new_alias = next_alias(list(current_aliases)) cognate_class = CognateClass.objects.create( alias=new_alias) cj = CognateJudgement.objects.create( lexeme=lexeme, cognate_class=cognate_class) return HttpResponseRedirect(anchored( reverse('lexeme-add-cognate-citation', args=[lexeme_id, cj.id]))) elif action == "delete": redirect_url = reverse("view-language-wordlist", args=[lexeme.language.ascii_name, getDefaultWordlist(request)]) lexeme.delete() return HttpResponseRedirect(redirect_url) else: assert not action prev_lexeme, next_lexeme = get_prev_and_next_lexemes(request, lexeme) return render_template(request, "lexeme_report.html", {"lexeme": lexeme, "prev_lexeme": prev_lexeme, "next_lexeme": next_lexeme, "action": action, "form": form, "active_citation_id": citation_id, "active_cogjudge_citation_id": cogjudge_id}) @login_required @logExceptions def lexeme_duplicate(request, lexeme_id): """Useful for processing imported data; currently only available through direct url input, e.g. /lexeme/0000/duplicate/""" original_lexeme = Lexeme.objects.get(id=int(lexeme_id)) SPLIT_RE = re.compile("[,;]") # split on these characters done_split = False if SPLIT_RE.search(original_lexeme.romanised): original_romanised, new_romanised = [ e.strip() for e in SPLIT_RE.split(original_lexeme.romanised, 1)] done_split = True else: original_romanised, new_romanised = original_lexeme.romanised, "" if SPLIT_RE.search(original_lexeme.phon_form): original_phon_form, new_phon_form = [ e.strip() for e in SPLIT_RE.split(original_lexeme.phon_form, 1)] done_split = True else: original_phon_form, new_phon_form = original_lexeme.phon_form, "" if done_split: new_lexeme = Lexeme.objects.create( language=original_lexeme.language, meaning=original_lexeme.meaning, romanised=new_romanised, phon_form=new_phon_form, notes=original_lexeme.notes) for lc in original_lexeme.lexemecitation_set.all(): LexemeCitation.objects.create( lexeme=new_lexeme, source=lc.source, pages=lc.pages, reliability=lc.reliability) for cj in original_lexeme.cognatejudgement_set.all(): new_cj = CognateJudgement.objects.create( lexeme=new_lexeme, cognate_class=cj.cognate_class) for cjc in cj.cognatejudgementcitation_set.all(): CognateJudgementCitation.objects.create( cognate_judgement=new_cj, source=cjc.source, pages=cjc.pages, reliability=cjc.reliability) original_lexeme.romanised = original_romanised original_lexeme.phon_form = original_phon_form original_lexeme.save() redirect_to = "%s#lexeme_%s" % ( reverse("meaning-report", args=[original_lexeme.meaning.gloss]), original_lexeme.id) return HttpResponseRedirect(redirect_to) @login_required @csrf_protect @logExceptions def lexeme_add(request, meaning=None, language=None): if request.method == "POST": form = AddLexemeForm(request.POST) try: form.validate() l = Lexeme(**form.data) l.bump(request) l.save() messages.success(request, 'Created lexeme %s.' % l.id) return HttpResponseRedirect( reverse("view-language-wordlist", args=[l.language.ascii_name, getDefaultWordlist(request)])) except Exception as e: logging.exception('Problem adding Lexeme in lexeme_add.') messages.error(request, 'Sorry, the server could not ' 'add the requested lexeme: %s' % e) data = {} if language: language = get_canonical_language(language, request) data['language_id'] = language.id if meaning: meaning = get_canonical_meaning(meaning) data["meaning_id"] = meaning.id # Computing typeahead info: languageTypeahead = json.dumps(dict( Language.objects.filter( languagelist__name=getDefaultLanguagelist(request) ).values_list( 'utf8_name', 'id'))) meaningTypeahead = json.dumps(dict( Meaning.objects.filter( meaninglist__name=getDefaultWordlist(request) ).values_list('gloss', 'id'))) return render_template(request, "lexeme_add.html", {"form": AddLexemeForm(data=data), "languageTypeahead": languageTypeahead, "meaningTypeahead": meaningTypeahead}) @logExceptions def redirect_lexeme_citation(request, lexeme_id): """From a lexeme, redirect to the first citation""" lexeme = Lexeme.objects.get(id=lexeme_id) try: first_citation = lexeme.lexemecitation_set.all()[0] return HttpResponseRedirect(redirect("lexeme-citation-detail", args=[first_citation.id])) except IndexError: msg = "Operation failed: this lexeme has no citations" messages.warning(request, msg) return HttpResponseRedirect(lexeme.get_absolute_url()) # -- /cognate/ ------------------------------------------------------------ @logExceptions def cognate_report(request, cognate_id=0, meaning=None, code=None): if cognate_id: cognate_class = CognateClass.objects.get(id=int(cognate_id)) # elif cognate_name: # cognate_class = CognateClass.objects.get(name=cognate_name) else: assert meaning and code cognate_classes = CognateClass.objects.filter( alias=code, cognatejudgement__lexeme__meaning__gloss=meaning).distinct() try: assert len(cognate_classes) == 1 cognate_class = cognate_classes[0] except AssertionError: msg = u"""error: meaning=‘%s’, cognate code=‘%s’ identifies %s cognate sets""" % (meaning, code, len(cognate_classes)) messages.info(request, oneline(msg)) return HttpResponseRedirect(reverse('meaning-report', args=[meaning])) # Handling of CognateJudgementSplitTable: if request.method == 'POST': if 'cognateJudgementSplitTable' in request.POST: form = CognateJudgementSplitTable(request.POST) try: form.validate() form.handle(request) except Exception as e: logging.exception('Problem when splitting CognateClasses ' 'in cognate_report.') messages.error(request, 'Sorry, the server had trouble ' 'understanding the request: %s' % e) elif 'deleteCognateClass' in request.POST: try: cognate_class.delete() messages.success(request, 'Deleted cognate class.') return HttpResponseRedirect('/cognateclasslist/') except Exception: logging.exception('Failed to delete CognateClass %s ' 'in cognate_report.', cognate_class.id) messages.error(request, 'Sorry, the server could not delete ' 'the requested cognate class %s.' % cognate_class.id) elif 'deleteCitation' in request.POST: try: citation = CognateClassCitation.objects.get( id=int(request.POST['citationId'])) citation.delete() messages.success(request, 'Deleted citation.') except Exception: logging.exception('Failed to delete citation ' 'in cognate_report.') messages.error(request, 'Sorry, the server could not delete ' 'the citation.') elif 'cognateClassEditForm' in request.POST: try: form = CognateClassEditForm(request.POST) form.validate() form.handle(request) except ValidationError as e: messages.error( request, 'Sorry, the server had trouble understanding ' 'the request: %s' % e) # recreate data to provide errorneous form data to the user language_list = LanguageList.objects.get( name=getDefaultLanguagelist(request)) splitTable = CognateJudgementSplitTable() ordLangs = language_list.languages.all().order_by("languagelistorder") for language in ordLangs: for cj in cognate_class.cognatejudgement_set.filter( lexeme__language=language).all(): cj.idField = cj.id splitTable.judgements.append_entry(cj) return render(request, 'cognate_report.html', {"cognate_class": cognate_class, "cognateClassForm": form, "splitTable": splitTable}) except Exception as e: logging.exception('Problem handling CognateClassEditForm.') messages.error( request, 'Sorry, the server had trouble understanding ' 'the request: %s' % e) return HttpResponseRedirect(reverse( 'cognate-set', args=[cognate_id])) language_list = LanguageList.objects.get( name=getDefaultLanguagelist(request)) splitTable = CognateJudgementSplitTable() # for language_id in language_list.language_id_list: ordLangs = language_list.languages.all().order_by( "level0", "level1" , "level2", "sortRankInClade","ascii_name") for language in ordLangs: for cj in cognate_class.cognatejudgement_set.filter( lexeme__language=language).all(): cj.idField = cj.id cj.cladeHexColor = Clade.objects.filter( languageclade__language_id=language.id, languageclade__cladesOrder=3).values_list('hexColor', flat=True).first() splitTable.judgements.append_entry(cj) # replace markups for note field (used in non-edit mode) s = Source.objects.all().filter(deprecated=False) notes = cognate_class.notes pattern = re.compile(r'(\{ref +([^\{]+?)(:[^\{]+?)? *\})') pattern2 = re.compile(r'(\{ref +[^\{]+?(:[^\{]+?)? *\})') for m in re.finditer(pattern, notes): foundSet = s.filter(shorthand=m.group(2)) if foundSet.count() == 1: notes = re.sub(pattern2, lambda match: '<a href="/sources/' + str(foundSet.first().id) + '" title="' + foundSet.first().citation_text.replace('"', '\"') + '">' + foundSet.first().shorthand + '</a>', notes, 1) # replace markups for justificationDiscussion field (used in non-edit mode) s = Source.objects.all().filter(deprecated=False) justificationDiscussion = cognate_class.justificationDiscussion pattern = re.compile(r'(\{ref +([^\{]+?)(:[^\{]+?)? *\})') pattern2 = re.compile(r'(\{ref +[^\{]+?(:[^\{]+?)? *\})') for m in re.finditer(pattern, justificationDiscussion): foundSet = s.filter(shorthand=m.group(2)) if foundSet.count() == 1: justificationDiscussion = re.sub(pattern2, lambda match: '<a href="/sources/' + str(foundSet.first().id) + '" title="' + foundSet.first().citation_text.replace('"', '\"') + '">' + foundSet.first().shorthand + '</a>', justificationDiscussion, 1) return render_template(request, "cognate_report.html", {"cognate_class": cognate_class, "notesExpandedMarkups": notes, "justificationDiscussionExpandedMarkups": justificationDiscussion, "cognateClassForm": CognateClassEditForm( obj=cognate_class), "splitTable": splitTable}) # -- /source/ ------------------------------------------------------------- @logExceptions def source_view(request, source_id): source = Source.objects.get(id=source_id) return render_template(request, 'source_edit.html', { "form": None, "source": source, "action": ""}) @login_required @logExceptions def source_edit(request, source_id=0, action="", cogjudge_id=0, lexeme_id=0): source_id = int(source_id) cogjudge_id = int(cogjudge_id) lexeme_id = int(lexeme_id) if source_id: source = Source.objects.get(id=source_id) else: source = None if request.method == 'POST': form = EditSourceForm(request.POST, instance=source) if "cancel" in form.data: return HttpResponseRedirect(reverse("view-sources")) if form.is_valid(): if action == "add": source = Source.objects.create(**form.cleaned_data) if cogjudge_id: # send back to origin judgement = CognateJudgement.objects.get(id=cogjudge_id) citation = CognateJudgementCitation.objects.create( cognate_judgement=judgement, source=source) return HttpResponseRedirect( reverse('lexeme-edit-cognate-citation', args=[judgement.lexeme.id, citation.id])) if lexeme_id: lexeme = Lexeme.objects.get(id=lexeme_id) citation = LexemeCitation.objects.create( lexeme=lexeme, source=source) return HttpResponseRedirect(reverse( 'lexeme-edit-citation', args=[lexeme.id, citation.id])) elif action == "edit": form.save() return HttpResponseRedirect(reverse('view-source', args=[source.id])) else: if action == "add": form = EditSourceForm() elif action == "edit": form = EditSourceForm(instance=source) elif action == "delete": source.delete() return HttpResponseRedirect(reverse("view-sources")) else: form = None return render_template(request, 'source_edit.html', { "form": form, "source": source, "action": action}) def source_perms_check(user): if user.has_perm('lexicon.change_source') or \ user.has_perm('lexicon.add_source') or \ user.has_perm('lexicon.delete_source'): return True return False @logExceptions def source_list(request): if request.POST.get("postType") == 'details': source_obj = Source.objects.get(pk=request.POST.get("id")) response = HttpResponse() response.write(SourceDetailsForm(instance=source_obj).as_table()) return response elif request.POST.get("postType") == 'add' and \ source_perms_check(request.user): response = HttpResponse() response.write(SourceEditForm().as_table()) return response elif request.POST.get("postType") == 'edit' and \ source_perms_check(request.user): source_obj = Source.objects.get(pk=request.POST.get("id")) response = HttpResponse() response.write(SourceEditForm(instance=source_obj).as_table()) return response elif request.POST.get("postType") == 'update' and \ source_perms_check(request.user): source_data = QueryDict(request.POST['source_data'].encode('ASCII')) if request.POST.get("action") == 'Delete': source_obj = Source.objects.get(pk=request.POST.get("id")) source_obj.delete() elif request.POST.get("action") == 'Update': source_obj = Source.objects.get(pk=request.POST.get("id")) form = SourceEditForm(source_data, instance=source_obj) if form.is_valid(): form.save() else: print(form.errors) elif request.POST.get("action") == 'Add': form = SourceEditForm(source_data) if form.is_valid(): form.save() else: print(form.errors) return HttpResponse() elif request.POST.get("postType") == 'deprecated-change' and \ source_perms_check(request.user): source_obj = Source.objects.get(pk=request.POST.get("id")) status = {u'true': True, 'false': False}[request.POST.get("status")] source_obj.deprecated = status source_obj.save() return HttpResponse() elif request.POST.get("postType") == 'TRS-change' and \ source_perms_check(request.user): source_obj = Source.objects.get(pk=request.POST.get("id")) status = {u'true': True, 'false': False}[request.POST.get("status")] source_obj.TRS = status source_obj.save() return HttpResponse() elif request.POST.get("postType") == 'filter': filter_dict = json.loads(request.POST.getlist("filter_dict[]")[0]) kwargs = {} for key in filter_dict.keys(): value = filter_dict[key] if value not in [u'', None]: if key == 'entrytype': key = 'ENTRYTYPE' kwargs['{0}__{1}'.format(key, 'icontains')] = value if kwargs != {}: queryset = Source.objects.filter(**kwargs) else: queryset = Source.objects.all() sources_table = get_sources_table(request, queryset) response = HttpResponse() RequestConfig( request, paginate={'per_page': 1000}).configure(sources_table) response.write(sources_table.as_html(request)) return response else: sources_table = get_sources_table(request) RequestConfig( request, paginate={'per_page': 1000}).configure(sources_table) return render_template(request, "source_list.html", {"sources": sources_table, "perms": source_perms_check(request.user), }) def get_language_list_obj(request): languageList = LanguageList.objects.get( id=getDefaultLanguagelistId(request)) return languageList def get_meaning_list_obj(request): meaningList = MeaningList.objects.get( id=getDefaultWordlistId(request)) return meaningList def get_default_lexemes(request): lexemes = Lexeme.objects.all().filter( language_id__in=get_language_list_obj(request).languages.all(), meaning_id__in=get_meaning_list_obj(request).meanings.all()) return lexemes def get_default_cognatejudgements(request): cognatejudgements = CognateJudgement.objects.all().filter( lexeme__in=get_default_lexemes(request)) return cognatejudgements def get_default_cognateclasses(request): ids_lst = get_default_cognatejudgements(request).values_list( 'cognate_class_id', flat=True) cognateclasses = CognateClass.objects.all().filter(id__in=ids_lst) return cognateclasses def get_sources_table(request, queryset=''): if queryset == '': queryset = Source.objects.all() lexeme_ids = list(get_default_lexemes(request).values_list('id', flat=True)) cognatejudgement_ids = list(get_default_cognatejudgements(request) .values_list('id', flat=True)) cognateclass_ids = list(get_default_cognateclasses(request) .values_list('id', flat=True)) queryset = queryset.extra({'cognacy_count': 'SELECT COUNT(*) ' 'FROM lexicon_cognatejudgementcitation ' 'WHERE ' 'lexicon_cognatejudgementcitation.source_id ' '= lexicon_source.id AND ' 'lexicon_cognatejudgementcitation.' 'cognate_judgement_id IN (%s)' % (', '.join(str(v) for v in cognatejudgement_ids)), 'cogset_count': 'SELECT COUNT(*) ' 'FROM lexicon_cognateclasscitation ' 'WHERE ' 'lexicon_cognateclasscitation.source_id ' '= lexicon_source.id AND ' 'lexicon_cognateclasscitation.' 'cognate_class_id IN (%s)' % (', '.join(str(v) for v in cognateclass_ids)), 'lexeme_count': 'SELECT COUNT(*) ' 'FROM lexicon_lexemecitation ' 'WHERE ' 'lexicon_lexemecitation.source_id ' '= lexicon_source.id AND ' 'lexicon_lexemecitation.' 'lexeme_id IN (%s)' % (', '.join(str(v) for v in lexeme_ids)) }) return SourcesTable(queryset) def export_bibtex(request): response = HttpResponse(content_type='text/plain; charset=utf-8') response['Content-Disposition'] = 'attachment; filename="export.bib"' db = BibDatabase() writer = BibTexWriter() for source_obj in Source.objects.all(): db.entries.append(source_obj.bibtex_dictionary) response.write(writer.write(db)) return response class source_import(FormView): form_class = UploadBiBTeXFileForm template_name = 'source_import.html' success_url = '/sources/' # Replace with your URL or reverse(). source_attr_lst = Source().bibtex_attr_lst @method_decorator(logExceptions) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(source_import, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) return render_template( request, self.template_name, {'form': form, 'update_sources_table': None}) def post(self, request, *args, **kwargs): if request.POST.get("postType") == 'import': for update_dict in request.POST.getlist('changes[]'): update_dict = json.loads(update_dict) if update_dict['id'] == u'new': s = Source() else: s = Source.objects.get(pk=update_dict['id']) for key in update_dict.keys(): if key not in ['id']: value = update_dict[key] if value == u'None': value = u'' setattr(s, key, value) s.save() return HttpResponseRedirect(reverse("view-sources")) else: form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file') if form.is_valid(): update_sources_dict_lst = [] new_sources_dict_lst = [] for f in files: result = self.get_bibtex_data(f) update_sources_dict_lst += result['update'] new_sources_dict_lst += result['new'] update_sources_table = new_sources_table = '' if update_sources_dict_lst: update_sources_table = SourcesUpdateTable( update_sources_dict_lst) RequestConfig( request, paginate={'per_page': 1000} ).configure(update_sources_table) if new_sources_dict_lst: new_sources_table = SourcesUpdateTable( new_sources_dict_lst) RequestConfig( request, paginate={'per_page': 1000} ).configure(new_sources_table) return render_template(request, self.template_name, { 'form': self.form_class(), 'update_sources_table': update_sources_table, 'new_sources_table': new_sources_table, }) else: return self.form_invalid(form) def get_bibtex_data(self, f): parser = BibTexParser() parser.ignore_nonstandard_types = False bib_database = bibtexparser.loads(f.read().decode('utf-8'), parser) update_sources_dict_lst = [] new_sources_dict_lst = [] for entry in bib_database.entries: result = self.get_comparison_dict(entry) if result['status'] == 'update': update_sources_dict_lst.append(result['dictionary']) else: new_sources_dict_lst.append(result['dictionary']) return {'update': update_sources_dict_lst, 'new': new_sources_dict_lst} def get_comparison_dict(self, entry): if entry['ID']: try: source_obj = Source.objects.get(pk=entry['ID']) return self.get_update_dict(entry, source_obj) except (ValueError, ObjectDoesNotExist): return self.get_new_dict(entry) return self.get_new_dict(entry) def get_update_dict(self, entry, source_obj): comparison_dict = {} comparison_dict['pk'] = entry['ID'] for key in [key for key in entry.keys() if key not in ['ID', 'date', 'type']]: if key in ['trs', 'deprecated']: entry[key] = json.loads(entry[key].lower()) if key in ['trs']: entry[key.upper()] = entry[key] key = key.upper() if getattr(source_obj, key) == entry[key]: comparison_dict[key] = [entry[key], 'same'] else: old_value = getattr(source_obj, key) if old_value in ['', u'—', None]: old_value = 'None' new_value = entry[key] if new_value in ['', u'—', None]: new_value = 'None' comparison_dict[key] = [ '<p class="oldValue">%s</p>' '<p class="newValue">%s</p>' % (old_value, new_value), 'changed'] for key in self.source_attr_lst: if key not in comparison_dict.keys(): if getattr(source_obj, key) not in ['', None]: comparison_dict[key] = [ '<p class="oldValue">%s</p>' '<p class="newValue">None</p>' % (getattr(source_obj, key)), 'changed'] return {'status': 'update', 'dictionary': comparison_dict} def get_new_dict(self, entry): comparison_dict = {} comparison_dict['pk'] = 'new' for key in entry.keys(): comparison_dict[key] = [entry[key], 'new'] return {'status': 'new', 'dictionary': comparison_dict} def source_related(request, formset, name, source_obj): return render_template(request, "source_related_inline.html", {"formset": formset, "name": name, "source": source_obj.shorthand }) def source_cognacy(request, source_id): source_obj = Source.objects.get(pk=source_id) formset = CognateJudgementFormSet( instance=source_obj, queryset=CognateJudgementCitation.objects.filter( cognate_judgement__in=get_default_cognatejudgements(request))) name = "Cognacy" return source_related(request, formset, name, source_obj) def source_cogset(request, source_id): source_obj = Source.objects.get(pk=source_id) formset = CognateClassFormSet( instance=source_obj, queryset=CognateClassCitation.objects.filter( cognate_class__in=get_default_cognateclasses(request))) name = "Cognate Sets" return source_related(request, formset, name, source_obj) def source_lexeme(request, source_id): source_obj = Source.objects.get(pk=source_id) formset = LexemeFormSet( instance=source_obj, queryset=LexemeCitation.objects.filter( lexeme__in=get_default_lexemes(request))) name = "Lexemes" return source_related(request, formset, name, source_obj) class SourceAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return Source.objects.none() qs = Source.objects.all() if self.q: qs = qs.filter(shorthand__icontains=self.q) return qs # -- /source end/ ------------------------------------------------------------- @logExceptions def lexeme_search(request): if request.method == 'POST': form = SearchLexemeForm(request.POST) if "cancel" in form.data: # has to be tested before data is cleaned return HttpResponseRedirect(reverse("view-frontpage")) if form.is_valid(): regex = form.cleaned_data["regex"] languages = form.cleaned_data["languages"] if not languages: languages = Language.objects.all() if form.cleaned_data["search_fields"] == "L": # Search language fields lexemes = Lexeme.objects.filter( Q(phon_form__regex=regex) | Q(romanised__regex=regex), language__in=languages)[:LIMIT_TO] else: # Search English fields assert form.cleaned_data["search_fields"] == "E" lexemes = Lexeme.objects.filter( Q(gloss__regex=regex) | Q(notes__regex=regex) | Q(meaning__gloss__regex=regex), language__in=languages)[:LIMIT_TO] language_names = [(l.utf8_name or l.ascii_name) for l in languages] return render_template(request, "lexeme_search_results.html", {"regex": regex, "language_names": language_names, "lexemes": lexemes, }) else: form = SearchLexemeForm() return render_template(request, "lexeme_search.html", {"form": form}) @logExceptions def viewDefaultLanguage(request): language = getDefaultLanguage(request) wordlist = getDefaultWordlist(request) return view_language_wordlist(request, language, wordlist) @logExceptions def viewDefaultMeaning(request): meaning = getDefaultMeaning(request) languagelist = getDefaultLanguagelist(request) return view_meaning(request, meaning, languagelist) @logExceptions def viewDefaultCognateClassList(request): meaning = getDefaultMeaning(request) return view_cognateclasses(request, meaning) @logExceptions def viewAbout(request, page): """ @param page :: str This function renders an about page. """ if page == 'statistics': return viewStatistics(request) pageTitleMap = { 'contact': 'Contact', 'furtherInfo': 'Further Info', 'home': 'Home' } baseUrl = 'https://raw.githubusercontent.com/wiki/lingdb/CoBL-public/' pageUrlMap = { 'contact': baseUrl + 'About-Page:-Contact.md', 'furtherInfo': baseUrl + 'About-Page:-Further-Info.md', 'home': baseUrl + 'About-Page:-Home.md' } return render_template(request, "about.html", {'title': pageTitleMap.get(page, 'Error'), 'content': fetchMarkdown(pageUrlMap[page])}) @logExceptions def viewStatistics(request): return render_template( request, "statistics.html", {"lexemes": Lexeme.objects.count(), "cognate_classes": CognateClass.objects.count(), "languages": Language.objects.count(), "meanings": Meaning.objects.count(), "coded_characters": CognateJudgement.objects.count(), "google_site_verification": META_TAGS}) @csrf_protect @logExceptions def viewAuthors(request): if request.method == 'POST': ''' We need to distinguish several cases here: * Creation of a new author * Modification of an existing author * Deletion of an author ''' if 'addAuthor' in request.POST: authorCreationForm = AuthorCreationForm(request.POST) try: authorCreationForm.validate() newAuthor = Author(**authorCreationForm.data) with transaction.atomic(): newAuthor.save(force_insert=True) except Exception as e: logging.exception('Problem creating author in viewAuthors.') messages.error(request, 'Sorry, the server could not ' 'create new author as requested: %s' % e) elif 'authors' in request.POST: authorData = AuthorTableForm(request.POST) try: authorData.validate() authorData.handle(request) except Exception as e: logging.exception('Problem updating authors in viewAuthors.') messages.error(request, 'Sorry, the server had problems ' 'updating at least one author: %s' % e) elif 'deleteAuthor' in request.POST: deleteAuthor = AuthorDeletionForm(request.POST) try: deleteAuthor.validate() deleteAuthor.handle(request) except Exception as e: logging.exception('Problem deleting author in viewAuthors.') messages.error(request, 'Sorry, the server had problems ' 'deleting the requested author: %s' % e) elif 'currentAuthorForm' in request.POST: currentAuthorForm = AuthorRowForm(request.POST) try: currentAuthorForm.validate() currentAuthorForm.handle(request) except Exception as e: logging.exception('Problem updating current author.') messages.error(request, 'Sorry, the server had problems ' 'updating the requested author: %s' % e) else: logging.error('Unexpected POST request in viewAuthors.') messages.error(request, 'Sorry, the server did not ' 'understand the request.') return HttpResponseRedirect( reverse("viewAuthors", args=[])) languageList = LanguageList.objects.get( name=getDefaultLanguagelist(request)) languageData = languageList.languages.values_list( 'utf8_name', 'author') authors = Author.objects.all() form = AuthorTableForm() for author in authors: author.idField = author.id form.elements.append_entry(author) authored = 0 namesOfLanguages = [] for aName, aString in languageData: if author.fullName in set(aString.split(' and ')): authored += 1 namesOfLanguages.append(aName) author.nol = str(authored) author.nolgs = ', '.join(namesOfLanguages) currentAuthorForm = None if request.user.is_authenticated: query = Author.objects.filter(user_id=request.user.id) if Author.objects.filter(user_id=request.user.id).exists(): currentAuthor = query.all()[0] currentAuthor.idField = currentAuthor.id currentAuthorForm = AuthorRowForm(obj=currentAuthor) return render_template( request, "authors.html", {'authors': form, 'currentAuthorForm': currentAuthorForm}) @csrf_protect @logExceptions def viewAuthor(request, initials): try: author = Author.objects.get(initials=initials) except Author.DoesNotExist: messages.error(request, "Unknown Author initials: %s." % initials) return HttpResponseRedirect(reverse("viewAuthors")) languageList = LanguageList.objects.get( name=getDefaultLanguagelist(request)) languageData = languageList.languages.values_list( 'ascii_name', 'utf8_name', 'author', 'reviewer') authored = [] reviewed = [] for aName, uName, aString, rString in languageData: if author.fullName in set(aString.split(' and ')): authored.append((aName, uName)) if author.fullName in set(rString.split(' and ')): reviewed.append((aName, uName)) return render_template( request, "author.html", { 'author': author, 'authored': authored, 'reviewed': reviewed, 'wordlist': getDefaultWordlist(request), 'content': fetchMarkdown( "Author-description:-%s.md" % author.initials)}) @logExceptions def changeDefaults(request): # Functions to get defaults: getDefaults = { 'language': getDefaultLanguage, 'meaning': getDefaultMeaning, 'wordlist': getDefaultWordlist, 'languagelist': getDefaultLanguagelist} # Current defaults: defaults = {k: v(request) for (k, v) in getDefaults.items()} # Defaults that can be changed: actions = { 'language': setDefaultLanguage, 'meaning': setDefaultMeaning, 'wordlist': setDefaultWordlist, 'languagelist': setDefaultLanguagelist} # Changing defaults for given parameters: for k, v in actions.items(): if k in request.GET: v(request, request.GET[k]) # Find changed defaults to substitute in url: substitutes = {} for k, v in getDefaults.items(): default = v(request) if defaults[k] != default: substitutes[defaults[k]] = default # Url to redirect clients to: url = request.GET['url'] if 'url' in request.GET else '/' # Substitute defaults in url: for k, v in substitutes.items(): url = url.replace(k, v) # Redirect to target url: return redirect(url) @logExceptions def view_frontpage(request): return viewAbout(request, 'home') @logExceptions @csrf_protect @login_required def view_nexus_export(request, exportId=None): if exportId is not None: if request.method == 'GET': try: export = NexusExport.objects.get(id=exportId) if not export.pending: return export.generateResponse( constraints='constraints' in request.GET, beauti='beauti' in request.GET, tabledata='datatable' in request.GET, matrix='matrix' in request.GET) # Message if pending: messages.info(request, "Sorry, the server is still " "computing export %s." % exportId) except NexusExport.DoesNotExist: messages.error(request, "Sorry, but export %s does not " "exist in the database." % exportId) elif request.method == 'POST' and 'delete' in request.POST: NexusExport.objects.filter(id=exportId).delete() messages.info(request, "Deleted export %s." % exportId) return HttpResponseRedirect(reverse("view_nexus_export_base")) exports = NexusExport.objects.order_by('-id').all() languageListNames = set([e.language_list_name for e in exports]) meaningListNames = set([e.meaning_list_name for e in exports]) def num(s): try: return int(s) except ValueError: return -1 # get the meaning and language counts at the moment of export via saved exportName # since the counts of meanings and languages can change over time for e in exports: try: c = re.search('_Lgs(\d+)', e.exportName).group(1) except AttributeError: c = -1 e.languageListCount = num(c) try: c = re.search('_Mgs(\d+)', e.exportName).group(1) except AttributeError: c = -1 e.meaningListCount = num(c) e.shortNameAuthor = re.sub('[^A-Z]', '', e.lastEditedBy) return render_template( request, "view_nexus_export.html", {'exports': exports}) @csrf_protect @logExceptions def view_two_languages_wordlist(request, targetLang=None, sourceLang=None, wordlist=None): ''' Implements two languages * all meanings view for #256 targetLang :: str | None sourceLang :: str | None wordlist :: str | None If targetLang is given it will be treated as the default language. ''' # Setting defaults if possible: if targetLang is not None: setDefaultLanguage(request, targetLang) if sourceLang is not None: setDefaultSourceLanguage(request, sourceLang) if wordlist is not None: setDefaultWordlist(request, wordlist) # Fetching targetLang to operate on: if targetLang is None: targetLang = getDefaultLanguage(request) try: targetLang = Language.objects.get(ascii_name=targetLang) except Language.DoesNotExist: raise Http404("Language '%s' does not exist" % targetLang) # Fetching sourceLang to operate on: if sourceLang is None: sourceLang = getDefaultSourceLanguage(request) if sourceLang is not None: try: sourceLang = Language.objects.get(ascii_name=sourceLang) except Language.DoesNotExist: sourceLang = None # Fetching wordlist to operate on: if wordlist is None: wordlist = getDefaultWordlist(request) try: wordlist = MeaningList.objects.get(name=wordlist) except MeaningList.DoesNotExist: raise Http404("MeaningList '%s' does not exist" % wordlist) if request.method == 'POST': # Handling cognate class assignments (#312): if 'assigncognates' in request.POST: form = AssignCognateClassesFromLexemeForm(request.POST) return form.handle() # Updating lexeme table data: elif 'lex_form' in request.POST: try: form = TwoLanguageWordlistTableForm(request.POST) form.validate() form.handle(request) except Exception as e: logging.exception('Problem updating lexemes ' 'in view_two_languages_wordlist.') messages.error(request, 'Sorry, the server had problems ' 'updating at least one lexeme: %s' % e) return HttpResponseRedirect( reverse("view-two-languages", args=[targetLang.ascii_name, sourceLang.ascii_name if sourceLang else None, wordlist.name])) def getLexemesForBothLanguages(targetLang, sourceLang): # Helper function to fetch lexemes # sourceLang will marked via column sourceLg by 1 for sorting and identifying return Lexeme.objects.filter( language__in=[targetLang, sourceLang], meaning__meaninglist=wordlist ).annotate(sourceLg=RawSQL("select (CASE WHEN language_id = %s THEN 1 ELSE 0 END)", (sourceLang,)) ).select_related("meaning", "language").prefetch_related( "cognatejudgement_set", "cognatejudgement_set__cognatejudgementcitation_set", "cognate_class", "lexemecitation_set").order_by("meaning__gloss", "sourceLg", "romanised") # collect data: mIdOrigLexDict = defaultdict(list) # Meaning.id -> [Lexeme] if sourceLang: mergedLexemes = getLexemesForBothLanguages(targetLang.id, sourceLang.id) for l in mergedLexemes.filter(language=sourceLang): mIdOrigLexDict[l.meaning_id].append(l) else: mergedLexemes = getLexemesForBothLanguages(targetLang, -1) # define colours for highlighting shared cognate sets # colours will be rotated ccColors = deque(['#FFCCCB','#FFCC00']) # init some stats counter helpers numOfSwadeshMeaningsSharedCC = set() numOfSwadeshMeaningsNotTargetSharedCC = set() numOfSwadeshMeanings = set() hasNotTargets = set() # - highlight same cognate classes per meaning # - calculating some stats matchedCC = False matchedSwadeshCC = False for l in mergedLexemes: # find shared cognate classes l.ccBackgroundColor = "#FFFFFF" # default background color for cognate set if l.meaning_id in mIdOrigLexDict: if l.not_swadesh_term: hasNotTargets.add(l.meaning_id) if l.sourceLg: # since targetLang will be detected first # check via matchedCC (set of lexeme ids) whether there's a possible match if matchedCC and matchedCC in l.allCognateClasses: l.ccBackgroundColor = ccColors[0] ccColors.rotate(1) else: m = mIdOrigLexDict[l.meaning.id] # store source info for merging l.originalIds = [{'id':s.id, 'romanised':s.romanised} for s in m] # iterate through all lexemes of both languages for given meaning for cc in l.allCognateClasses: for cc1 in m: if cc in cc1.allCognateClasses: l.ccBackgroundColor = ccColors[0] matchedCC = cc # counter for shared Swadesh only cognate classes if not cc1.not_swadesh_term and not l.not_swadesh_term: numOfSwadeshMeaningsSharedCC.add(l.meaning_id) else: numOfSwadeshMeaningsNotTargetSharedCC.add(l.meaning_id) # counter for Swadesh only meaning sets if not cc1.not_swadesh_term and not l.not_swadesh_term: numOfSwadeshMeanings.add(l.meaning_id) # add new boolean data for filtering shared cognate classes # column will be hidden in HTML for l in mergedLexemes: l.ccSwdKind = (l.meaning_id in numOfSwadeshMeaningsSharedCC) if l.meaning_id in numOfSwadeshMeaningsNotTargetSharedCC and l.meaning_id in numOfSwadeshMeanings and l.ccBackgroundColor != "#FFFFFF": l.notTargetCC = True l.ccBackgroundColor = "#FFFFFF" else: l.notTargetCC = False l.hasNotTargets = (l.meaning_id in hasNotTargets) lexemeTable = TwoLanguageWordlistTableForm(lexemes=mergedLexemes) otherMeaningLists = MeaningList.objects.exclude(id=wordlist.id).all() languageList = LanguageList.objects.prefetch_related('languages').get( name=getDefaultLanguagelist(request)) typeahead1 = json.dumps({ l.utf8_name: reverse( "view-two-languages", args=[l.ascii_name, sourceLang.ascii_name if sourceLang else None, wordlist.name]) for l in languageList.languages.all()}) typeahead2 = json.dumps({ l.utf8_name: reverse( "view-two-languages", args=[targetLang.ascii_name, l.ascii_name, wordlist.name]) for l in languageList.languages.all()}) if len(numOfSwadeshMeanings) != 0: numOfSharedCCPerSwadeshMeanings = "%.1f%%" % float( len(numOfSwadeshMeaningsSharedCC)/len(numOfSwadeshMeanings)*100) else: numOfSharedCCPerSwadeshMeanings = "" return render_template(request, "twoLanguages.html", {"targetLang": targetLang, "sourceLang": sourceLang, "wordlist": wordlist, "otherMeaningLists": otherMeaningLists, "lex_ed_form": lexemeTable, "numOfSwadeshMeaningsSharedCC": len(numOfSwadeshMeaningsSharedCC), "numOfSwadeshMeanings": len(numOfSwadeshMeanings), "numOfSharedCCPerSwadeshMeanings": numOfSharedCCPerSwadeshMeanings, "typeahead1": typeahead1, "typeahead2": typeahead2}) @csrf_protect @logExceptions def view_language_progress(request, language_list=None): current_list = get_canonical_language_list(language_list, request) setDefaultLanguagelist(request, current_list.name) if (request.method == 'POST') and ('progress_form' in request.POST): form = LanguageListProgressForm(request.POST) try: form.validate() except Exception as e: logging.exception( 'Exception in POST validation for view_language_list') messages.error(request, 'Sorry, the form data sent ' 'did not pass server side validation: %s' % e) return HttpResponseRedirect( reverse("view-language-progress", args=[current_list.name])) # Updating languages and gathering clades to update: updateClades = form.handle(request) # Updating clade relations for changes languages: if updateClades: updateLanguageCladeRelations(languages=updateClades) # Redirecting so that UA makes a GET. exportMethod = '' if 'onlyexport' in request.path.split('/'): exportMethod = 'onlyexport' elif 'onlynotexport' in request.path.split('/'): exportMethod = 'onlynotexport' return HttpResponseRedirect( reverse("view-language-progress", args=[current_list.name,exportMethod])) languages = current_list.languages.all().prefetch_related( "lexeme_set", "lexeme_set__meaning", "languageclade_set", "clades") meaningList = MeaningList.objects.get(name=getDefaultWordlist(request)) form = LanguageListProgressForm() exportMethod = '' if request.method == 'GET': if 'onlyexport' in request.path.split('/'): exportMethod = 'onlyexport' elif 'onlynotexport' in request.path.split('/'): exportMethod = 'onlynotexport' for lang in languages: lang.idField = lang.id lang.computeCounts(meaningList, exportMethod) form.langlist.append_entry(lang) otherLanguageLists = LanguageList.objects.exclude(name=current_list).all() noexportbutton = {} if request.method == 'GET': if 'onlyexport' in request.path.split('/'): noexportbutton = { "note": "based on only those meanings marked for 'export'", "url": "/".join(request.path.split('/')[0:-1]) + "/onlynotexport", "tooltip": "Show statistics based on all meanings which are marked only for 'not export'", "state": "btn-success", "icon": "glyphicon glyphicon-ok"} elif 'onlynotexport' in request.path.split('/'): noexportbutton = { "note": "based on only those meanings marked for 'not for export'", "url": "/".join(request.path.split('/')[0:-1]), "tooltip": "Show statistics based on all meanings including those which are marked for 'not export'", "state": "btn-danger", "icon": "glyphicon glyphicon-remove"} else: noexportbutton = { "note": "based on all meanings including those marked for 'not for export'", "url": request.path + "onlyexport", "tooltip": "Show statistics based on only those meanings which are marked for 'export'", "state": "btn-default", "icon": "glyphicon-question-sign"} return render_template(request, "language_progress.html", {"languages": languages, 'form': form, "current_list": current_list, "otherLanguageLists": otherLanguageLists, "noexportbutton": noexportbutton, "wordlist": getDefaultWordlist(request), "clades": Clade.objects.all()}) @csrf_protect @logExceptions def view_language_distributions(request, language_list=None): current_list = get_canonical_language_list(language_list, request) setDefaultLanguagelist(request, current_list.name) languages = current_list.languages.all().prefetch_related( "lexeme_set", "lexeme_set__meaning", "languageclade_set", "clades") if (request.method == 'POST') and ('langlist_form' in request.POST): form = LanguageDistributionTableForm(request.POST) try: form.validate() form.handle(request) except Exception as e: logging.exception( 'Exception in POST validation for view_language_distributions') messages.error(request, 'Sorry, the form data sent ' 'did not pass server side validation: %s' % e) return HttpResponseRedirect( reverse("view_language_distributions", args=[current_list.name])) # Redirecting so that UA makes a GET. return HttpResponseRedirect( reverse("view-language-distributions", args=[current_list.name])) meaningList = MeaningList.objects.get(name=getDefaultWordlist(request)) languages_editabletable_form = LanguageDistributionTableForm() exportMethod = '' if request.method == 'GET': if 'onlyexport' in request.path.split('/'): exportMethod = 'onlyexport' elif 'onlynotexport' in request.path.split('/'): exportMethod = 'onlynotexport' for lang in languages: lang.idField = lang.id lang.computeCounts(meaningList, exportMethod) languages_editabletable_form.langlist.append_entry(lang) otherLanguageLists = LanguageList.objects.exclude(name=current_list).all() return render_template(request, "language_distributions.html", {"languages": languages, 'lang_ed_form': languages_editabletable_form, "current_list": current_list, "otherLanguageLists": otherLanguageLists, "wordlist": getDefaultWordlist(request), "clades": Clade.objects.all()}) @logExceptions def json_cognateClass_placeholders(request): if request.method == 'GET' and 'lexemeid' in request.GET: # Acquiring languageList: try: languageList = LanguageList.objects.get( name=getDefaultLanguagelist(request)) except LanguageList.DoesNotExist: languageList = LanguageList.objects.get( name=LanguageList.ALL) meaningIds = Lexeme.objects.filter( id=int(request.GET['lexemeid'])).values_list( 'meaning_id', flat=True) # cognateClasses = CognateClass.objects.filter( # lexeme__meaning_id__in=meaningIds).distinct() # lexemes = [int(s) for s in request.GET['lexemes'].split(',')] # cognateClasses = CognateClass.objects.filter( # lexeme__in=lexemes).distinct() cognateClasses = CognateClass.objects.filter( cognatejudgement__lexeme__meaning_id__in=meaningIds ).prefetch_related('lexeme_set').order_by('alias').distinct() # Computing counts for ccs: for cc in cognateClasses: cc.computeCounts(languageList=languageList) def cmpKey(x): return [-x.cladeCount, -x.lexemeCount, len(x.alias)] cognateClasses = sorted(cognateClasses, key=cmpKey) dump = json.dumps([{'id': c.id, 'alias': c.alias, 'placeholder': c.combinedRootPlaceholder} for c in cognateClasses]), return HttpResponse(dump) return HttpResponse( "Please provide `lexemes` parameter detailing lexeme ids.") @logExceptions def view_cladecognatesearch(request): # Handle POST of AddCogClassTableForm: if request.method == 'POST': if 'AddCogClassTableForm' in request.POST: try: cogClassTableForm = AddCogClassTableForm(request.POST) cogClassTableForm.validate() cogClassTableForm.handle(request) except ValidationError as e: logging.exception( 'Validation did not work in view_cladecognatesearch.') messages.error(request, ' '.join(e.messages)) except Exception as e: logging.exception('Problem updating CognateClasses ' 'in view_cladecognatesearch.') messages.error(request, 'Sorry, the server had problems ' 'updating at least one entry: %s' % e) redirect_url = request.path if request.GET and 'clades' in request.GET: redirect_url += '?clades=%s' % request.GET['clades'] return HttpResponseRedirect(redirect_url) # Acquiring meaningList: try: meaningList = MeaningList.objects.get(name=getDefaultWordlist(request)) except meaningList.DoesNotExist: meaningList = MeaningList.objects.get(name=MeaningList.DEFAULT) # Acquiring languageList: try: languageList = LanguageList.objects.get( name=getDefaultLanguagelist(request)) except LanguageList.DoesNotExist: languageList = LanguageList.objects.get( name=LanguageList.ALL) allClades = Clade.objects.all() # Figuring out clades to search for: currentClades = [] includeMode = False if request.method == 'GET' and 'clades' in request.GET: cladeNames = [n.strip() for n in request.GET['clades'].split(',')] if 'nonunique' in cladeNames: includeMode = True currentClades = allClades.filter( taxonsetName__in=cladeNames).all() # Searching cognateClassIds by clades: cognateClassIds = set() allCognates = CognateClass.objects.filter( lexeme__language__in=languageList.languages.all(), lexeme__meaning__in=meaningList.meanings.all() ) for clade in currentClades: newIds = allCognates.filter( lexeme__language__languageclade__clade=clade, ).values_list('id', flat=True) if cognateClassIds: cognateClassIds &= set(newIds) else: cognateClassIds = set(newIds) # Removing unwanted entries from cognateClassIds: if currentClades and not includeMode: unwantedLanguages = languageList.languages.exclude( languageclade__clade__in=currentClades ).exclude(level0=0).values_list('id', flat=True) removeCognateClassIds = set(CognateClass.objects.filter( lexeme__language__in=unwantedLanguages, lexeme__meaning__in=meaningList.meanings.all() ).values_list('id', flat=True)) cognateClassIds -= removeCognateClassIds # Form for cognateClasses: cognateClasses = CognateClass.objects.filter( id__in=cognateClassIds, lexeme__language__in=languageList.languages.all(), lexeme__meaning__in=meaningList.meanings.all() ).order_by('lexeme__meaning').prefetch_related( 'lexeme_set', 'lexeme_set__language').distinct().all() lgsIds= set(languageList.languagelistorder_set.all().values_list( 'language_id', flat=True)) for c in cognateClasses: c.computeCounts(languageList, lgsIds, False) form = AddCogClassTableForm(cogclass=cognateClasses) # Computing cladeLinks: def mkCladeLink(clade, currentTaxonsetNames, includeMode): targetSet = currentTaxonsetNames ^ set([clade.taxonsetName]) if includeMode: targetSet.add('nonunique') return {'name': clade.shortName, 'active': clade.taxonsetName in currentTaxonsetNames, 'color': clade.hexColor, 'href': '?clades=%s' % ','.join(targetSet)} currentTaxonsetNames = set([c.taxonsetName for c in currentClades]) cladeLinks = [mkCladeLink(c, currentTaxonsetNames, includeMode) for c in allClades if c.shortName] if includeMode: cladeLinks.append({ 'name': 'Non-Unique Mode', 'active': True, 'color': '#999999', 'href': '?clades=%s' % (','.join(currentTaxonsetNames))}) else: cladeLinks.append({ 'name': 'Non-Unique Mode', 'active': False, 'color': '#999999', 'href': '?clades=%s%s' % (','.join(currentTaxonsetNames), ',nonunique')}) return render_template( request, "view_cladecognatesearch.html", {"cladeTitle": ", ".join([c.shortName for c in currentClades]), "cladeLinks": cladeLinks, "AddCogClassTableForm": form}) def query_to_dicts(query_string, *query_args): cursor = connection.cursor() cursor.execute(query_string, query_args) col_names = list(map(str.upper, [desc[0] for desc in cursor.description])) while True: row = cursor.fetchone() if row is None: break row_dict = OrderedDict(zip(col_names, row)) yield row_dict return @user_passes_test(lambda u: u.is_staff) @logExceptions def view_csvExport(request): def modelToFieldnames(model): def isWantedField(field): if field.startswith('_'): return False return isinstance(getattr(model, field), DeferredAttribute) return [f for f in dir(model) if isWantedField(f)] def modelToDicts(querySet, fieldnames): return [{field: getattr(entry, field) for field in fieldnames} for entry in querySet.all()] if 'full' in request.GET: models = {Author: Author.objects, Clade: Clade.objects, CognateClass: CognateClass.objects, CognateClassCitation: CognateClassCitation.objects, CognateJudgement: CognateJudgement.objects, CognateJudgementCitation: CognateJudgementCitation.objects, Language: Language.objects, LanguageClade: LanguageClade.objects, LanguageList: LanguageList.objects, LanguageListOrder: LanguageListOrder.objects, Lexeme: Lexeme.objects, LexemeCitation: LexemeCitation.objects, Meaning: Meaning.objects, MeaningList: MeaningList.objects, MeaningListOrder: MeaningListOrder.objects, SndComp: SndComp.objects, Source: Source.objects} elif 'cognate' in request.GET: meaningListId = getDefaultWordlistId(request) languageListId = getDefaultLanguagelistId(request) models_org = list(query_to_dicts(""" SELECT * FROM ( SELECT 0 as ID, cj.cognate_class_id as COGID, cc.root_form as ROOT_FORM, cj.lexeme_id as LEXEME_ID, m.gloss as CONCEPT, l.phon_form as IPA, l."phoneMic" as PHONEMIC, l.romanised as ROMANISED, lg.ascii_name as DOCULECT, l.not_swadesh_term as NOT_TARGET FROM lexicon_lexeme as l, lexicon_cognatejudgement as cj, lexicon_language as lg, lexicon_meaning as m, lexicon_cognateclass as cc WHERE l.id = cj.lexeme_id AND l.language_id = lg.id AND l.meaning_id = m.id AND cj.cognate_class_id = cc.id AND l.language_id in ( select language_id from lexicon_languagelistorder where language_list_id = %d) AND l.meaning_id in ( select meaning_id from lexicon_meaninglistorder where meaning_list_id = %d) UNION SELECT 0 as ID, 0 as COGID, '' as ROOT_FORM, l.id as LEXEME_ID, m.gloss as CONCEPT, l.phon_form as IPA, l."phoneMic" as PHONEMIC, l.romanised as ROMANISED, lg.ascii_name as DOCULECT, l.not_swadesh_term as NOT_TARGET FROM lexicon_lexeme as l, lexicon_language as lg, lexicon_meaning as m WHERE l.id not in ( SELECT cj.lexeme_id FROM lexicon_lexeme as l, lexicon_cognatejudgement as cj, lexicon_language as lg, lexicon_meaning as m, lexicon_cognateclass as cc WHERE l.id = cj.lexeme_id AND l.language_id = lg.id AND l.meaning_id = m.id AND cj.cognate_class_id = cc.id AND l.language_id in ( SELECT language_id from lexicon_languagelistorder where language_list_id = %d) AND l.meaning_id in ( SELECT meaning_id from lexicon_meaninglistorder where meaning_list_id = %d) ) AND l.language_id = lg.id AND l.meaning_id = m.id AND l.language_id in ( SELECT language_id from lexicon_languagelistorder where language_list_id = %d) AND l.meaning_id in ( SELECT meaning_id from lexicon_meaninglistorder where meaning_list_id = %d) ) t ORDER BY (doculect, concept) """ % ((languageListId,meaningListId) * 3))) zipBuffer = io.BytesIO() zipFile = zipfile.ZipFile(zipBuffer, 'w') if len(models_org) > 0: try: filename = 'CoBL_export_%s/%s.tsv' % (time.strftime("%Y-%m-%d"), 'cognates_all') models = [] cnt = 1 for i in range(len(models_org)): r = copy.deepcopy(models_org[i]) r["ID"] = cnt del r["NOT_TARGET"] models.append(r) cnt += 1 fieldnames = models[0].keys() modelBuffer = io.StringIO() writer = csv.DictWriter(modelBuffer, fieldnames=fieldnames, dialect="excel-tab") writer.writeheader() writer.writerows(models) zipFile.writestr(filename, modelBuffer.getvalue()) models = [] cnt = 1 for i in range(len(models_org)): r = copy.deepcopy(models_org[i]) if not r["NOT_TARGET"]: r["ID"] = cnt del r["NOT_TARGET"] models.append(r) cnt += 1 filename = 'CoBL_export_%s/%s.tsv' % (time.strftime("%Y-%m-%d"), 'cognates_only_target') modelBuffer = io.StringIO() writer = csv.DictWriter(modelBuffer, fieldnames=fieldnames, dialect="excel-tab") writer.writeheader() writer.writerows(models) zipFile.writestr(filename, modelBuffer.getvalue()) except BaseException as error: print("TSV cognate export error {}".format(error)) zipFile.close() resp = HttpResponse(zipBuffer.getvalue(), content_type='application/x-zip-compressed') cdHeader = "attachment; filename=%s.export.zip" % time.strftime("%Y-%m-%d") resp['Content-Disposition'] = cdHeader return resp else: meaningList = getDefaultWordlist(request) languageList = getDefaultLanguagelist(request) models = { Author: Author.objects, Language: Language.objects.filter( languagelist__name=languageList), LanguageList: LanguageList.objects.filter(name=languageList), LanguageListOrder: LanguageListOrder.objects.filter( language_list__name=languageList), Meaning: Meaning.objects.filter(meaninglist__name=meaningList), MeaningList: MeaningList.objects.filter(name=meaningList), MeaningListOrder: MeaningListOrder.objects.filter( meaning_list__name=meaningList), SndComp: SndComp.objects, Source: Source.objects} models[Lexeme] = Lexeme.objects.filter( language__in=models[Language], meaning__in=models[Meaning]) models[CognateJudgement] = CognateJudgement.objects.filter( lexeme__in=models[Lexeme]) models[CognateClass] = CognateClass.objects.filter( lexeme__in=models[Lexeme]) models[LexemeCitation] = LexemeCitation.objects.filter( lexeme__in=models[Lexeme]) models[CognateJudgementCitation] = \ CognateJudgementCitation.objects.filter( cognate_judgement__in=models[CognateJudgement]) models[CognateClassCitation] = \ CognateClassCitation.objects.filter( cognate_class__in=models[CognateClass]) models[LanguageClade] = LanguageClade.objects.filter( language__in=models[Language]) models[Clade] = Clade.objects.filter( languageclade__in=models[LanguageClade]) zipBuffer = io.BytesIO() zipFile = zipfile.ZipFile(zipBuffer, 'w') for model, querySet in models.items(): filename = 'CoBL_export_%s/%s.csv' % (time.strftime("%Y-%m-%d"), model.__name__) fieldnames = modelToFieldnames(model) modelBuffer = io.StringIO() writer = csv.DictWriter(modelBuffer, fieldnames=fieldnames) writer.writeheader() writer.writerows(modelToDicts(querySet, fieldnames)) zipFile.writestr(filename, modelBuffer.getvalue()) zipFile.close() resp = HttpResponse(zipBuffer.getvalue(), content_type='application/x-zip-compressed') cdHeader = "attachment; filename=%s.export.zip" % time.strftime("%Y-%m-%d") resp['Content-Disposition'] = cdHeader return resp @user_passes_test(lambda u: u.is_staff) @csrf_protect @logExceptions def viewProblematicRomanised(request): if request.method == 'POST': symbol = bytes(request.POST['symbol'], 'utf-8').decode('unicode_escape') if request.POST['action'] == 'add': rSymbol = RomanisedSymbol.objects.create(symbol=symbol) rSymbol.bump(request) elif request.POST['action'] == 'remove': RomanisedSymbol.objects.filter(symbol=symbol).delete() languageList = LanguageList.objects.get(name=getDefaultLanguagelist(request)) meaningList = MeaningList.objects.get(name=getDefaultWordlist(request)) lexemes = Lexeme.objects.filter( language__in=languageList.languages.all(), meaning__in=meaningList.meanings.all()).select_related('meaning') allowedSymbols = RomanisedSymbol.objects.all() okSet = set([allowed.symbol for allowed in allowedSymbols]) offendingLexemes = [] for lexeme in lexemes: offendingSymbols = set(lexeme.romanised) - okSet if offendingSymbols: lexeme.offendingSymbols = [ RomanisedSymbol(symbol=o) for o in offendingSymbols] offendingLexemes.append(lexeme) return render_template(request, "problematicRomanised.html", {"allowedSymbols": allowedSymbols, "offendingLexemes": offendingLexemes})
lingdb/CoBL-public
ielex/views.py
Python
bsd-2-clause
157,549
[ "VisIt" ]
5c6395ae051028d8c9bf15f50dbac5bda0be303680ca3316e07755143a52ed32
import os, sys, re, inspect, types, errno, pprint, subprocess, io, shutil, time, copy import path_tool path_tool.activate_module('FactorySystem') path_tool.activate_module('argparse') from ParseGetPot import ParseGetPot from socket import gethostname #from options import * from util import * from RunParallel import RunParallel from CSVDiffer import CSVDiffer from XMLDiffer import XMLDiffer from Tester import Tester from PetscJacobianTester import PetscJacobianTester from InputParameters import InputParameters from Factory import Factory from Parser import Parser from Warehouse import Warehouse import argparse from optparse import OptionParser, OptionGroup, Values from timeit import default_timer as clock class TestHarness: @staticmethod def buildAndRun(argv, app_name, moose_dir): if '--store-timing' in argv: harness = TestTimer(argv, app_name, moose_dir) else: harness = TestHarness(argv, app_name, moose_dir) harness.findAndRunTests() sys.exit(harness.error_code) def __init__(self, argv, app_name, moose_dir): self.factory = Factory() # Build a Warehouse to hold the MooseObjects self.warehouse = Warehouse() # Get dependant applications and load dynamic tester plugins # If applications have new testers, we expect to find them in <app_dir>/scripts/TestHarness/testers dirs = [os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))] sys.path.append(os.path.join(moose_dir, 'framework', 'scripts')) # For find_dep_apps.py # Use the find_dep_apps script to get the dependant applications for an app import find_dep_apps depend_app_dirs = find_dep_apps.findDepApps(app_name) dirs.extend([os.path.join(my_dir, 'scripts', 'TestHarness') for my_dir in depend_app_dirs.split('\n')]) # Finally load the plugins! self.factory.loadPlugins(dirs, 'testers', Tester) self.test_table = [] self.num_passed = 0 self.num_failed = 0 self.num_skipped = 0 self.num_pending = 0 self.host_name = gethostname() self.moose_dir = moose_dir self.base_dir = os.getcwd() self.run_tests_dir = os.path.abspath('.') self.code = '2d2d6769726c2d6d6f6465' self.error_code = 0x0 # Assume libmesh is a peer directory to MOOSE if not defined if os.environ.has_key("LIBMESH_DIR"): self.libmesh_dir = os.environ['LIBMESH_DIR'] else: self.libmesh_dir = os.path.join(self.moose_dir, 'libmesh', 'installed') self.file = None # Parse arguments self.parseCLArgs(argv) self.checks = {} self.checks['platform'] = getPlatforms() self.checks['submodules'] = getInitializedSubmodules(self.run_tests_dir) # The TestHarness doesn't strictly require the existence of libMesh in order to run. Here we allow the user # to select whether they want to probe for libMesh configuration options. if self.options.skip_config_checks: self.checks['compiler'] = set(['ALL']) self.checks['petsc_version'] = 'N/A' self.checks['library_mode'] = set(['ALL']) self.checks['mesh_mode'] = set(['ALL']) self.checks['dtk'] = set(['ALL']) self.checks['unique_ids'] = set(['ALL']) self.checks['vtk'] = set(['ALL']) self.checks['tecplot'] = set(['ALL']) self.checks['dof_id_bytes'] = set(['ALL']) self.checks['petsc_debug'] = set(['ALL']) self.checks['curl'] = set(['ALL']) self.checks['tbb'] = set(['ALL']) self.checks['superlu'] = set(['ALL']) self.checks['unique_id'] = set(['ALL']) self.checks['cxx11'] = set(['ALL']) self.checks['asio'] = set(['ALL']) else: self.checks['compiler'] = getCompilers(self.libmesh_dir) self.checks['petsc_version'] = getPetscVersion(self.libmesh_dir) self.checks['library_mode'] = getSharedOption(self.libmesh_dir) self.checks['mesh_mode'] = getLibMeshConfigOption(self.libmesh_dir, 'mesh_mode') self.checks['dtk'] = getLibMeshConfigOption(self.libmesh_dir, 'dtk') self.checks['unique_ids'] = getLibMeshConfigOption(self.libmesh_dir, 'unique_ids') self.checks['vtk'] = getLibMeshConfigOption(self.libmesh_dir, 'vtk') self.checks['tecplot'] = getLibMeshConfigOption(self.libmesh_dir, 'tecplot') self.checks['dof_id_bytes'] = getLibMeshConfigOption(self.libmesh_dir, 'dof_id_bytes') self.checks['petsc_debug'] = getLibMeshConfigOption(self.libmesh_dir, 'petsc_debug') self.checks['curl'] = getLibMeshConfigOption(self.libmesh_dir, 'curl') self.checks['tbb'] = getLibMeshConfigOption(self.libmesh_dir, 'tbb') self.checks['superlu'] = getLibMeshConfigOption(self.libmesh_dir, 'superlu') self.checks['unique_id'] = getLibMeshConfigOption(self.libmesh_dir, 'unique_id') self.checks['cxx11'] = getLibMeshConfigOption(self.libmesh_dir, 'cxx11') self.checks['asio'] = getIfAsioExists(self.moose_dir) # Override the MESH_MODE option if using the '--distributed-mesh' # or (deprecated) '--parallel-mesh' option. if (self.options.parallel_mesh == True or self.options.distributed_mesh == True) or \ (self.options.cli_args != None and \ (self.options.cli_args.find('--parallel-mesh') != -1 or self.options.cli_args.find('--distributed-mesh') != -1)): option_set = set(['ALL', 'PARALLEL']) self.checks['mesh_mode'] = option_set method = set(['ALL', self.options.method.upper()]) self.checks['method'] = method self.initialize(argv, app_name) """ Recursively walks the current tree looking for tests to run Error codes: 0x0 - Success 0x0* - Parser error 0x1* - TestHarness error """ def findAndRunTests(self, find_only=False): self.error_code = 0x0 self.preRun() self.start_time = clock() try: # PBS STUFF if self.options.pbs: # Check to see if we are using the PBS Emulator. # Its expensive, so it must remain outside of the os.walk for loop. self.options.PBSEmulator = self.checkPBSEmulator() if self.options.pbs and os.path.exists(self.options.pbs): self.options.processingPBS = True self.processPBSResults() else: self.options.processingPBS = False self.base_dir = os.getcwd() for dirpath, dirnames, filenames in os.walk(self.base_dir, followlinks=True): # Prune submdule paths when searching for tests if self.base_dir != dirpath and os.path.exists(os.path.join(dirpath, '.git')): dirnames[:] = [] # walk into directories that aren't contrib directories if "contrib" not in os.path.relpath(dirpath, os.getcwd()): for file in filenames: # set cluster_handle to be None initially (happens for each test) self.options.cluster_handle = None # See if there were other arguments (test names) passed on the command line if file == self.options.input_file_name: #and self.test_match.search(file): saved_cwd = os.getcwd() sys.path.append(os.path.abspath(dirpath)) os.chdir(dirpath) if self.prunePath(file): continue # Build a Parser to parse the objects parser = Parser(self.factory, self.warehouse) # Parse it self.error_code = self.error_code | parser.parse(file) # Retrieve the tests from the warehouse testers = self.warehouse.getActiveObjects() # Augment the Testers with additional information directly from the TestHarness for tester in testers: self.augmentParameters(file, tester) # Short circuit this loop if we've only been asked to parse Testers # Note: The warehouse will accumulate all testers in this mode if find_only: self.warehouse.markAllObjectsInactive() continue # Clear out the testers, we won't need them to stick around in the warehouse self.warehouse.clear() if self.options.enable_recover: testers = self.appendRecoverableTests(testers) # Handle PBS tests.cluster file if self.options.pbs: (tester, command) = self.createClusterLauncher(dirpath, testers) if command is not None: self.runner.run(tester, command) else: # Go through the Testers and run them for tester in testers: # Double the alloted time for tests when running with the valgrind option tester.setValgrindMode(self.options.valgrind_mode) # When running in valgrind mode, we end up with a ton of output for each failed # test. Therefore, we limit the number of fails... if self.options.valgrind_mode and self.num_failed > self.options.valgrind_max_fails: (should_run, reason) = (False, 'Max Fails Exceeded') elif self.num_failed > self.options.max_fails: (should_run, reason) = (False, 'Max Fails Exceeded') elif tester.parameters().isValid('error_code'): (should_run, reason) = (False, 'skipped (Parser Error)') else: (should_run, reason) = tester.checkRunnableBase(self.options, self.checks) if should_run: command = tester.getCommand(self.options) # This method spawns another process and allows this loop to continue looking for tests # RunParallel will call self.testOutputAndFinish when the test has completed running # This method will block when the maximum allowed parallel processes are running self.runner.run(tester, command) else: # This job is skipped - notify the runner if reason != '': if (self.options.report_skipped and reason.find('skipped') != -1) or reason.find('skipped') == -1: self.handleTestResult(tester.parameters(), '', reason) self.runner.jobSkipped(tester.parameters()['test_name']) os.chdir(saved_cwd) sys.path.pop() except KeyboardInterrupt: print '\nExiting due to keyboard interrupt...' sys.exit(0) self.runner.join() # Wait for all tests to finish if self.options.pbs and self.options.processingPBS == False: print '\n< checking batch status >\n' self.options.processingPBS = True self.processPBSResults() self.cleanup() if self.num_failed: self.error_code = self.error_code | 0x10 return def createClusterLauncher(self, dirpath, testers): self.options.test_serial_number = 0 command = None tester = None # Create the tests.cluster input file # Loop through each tester and create a job for tester in testers: (should_run, reason) = tester.checkRunnableBase(self.options, self.checks) if should_run: if self.options.cluster_handle == None: self.options.cluster_handle = open(dirpath + '/' + self.options.pbs + '.cluster', 'w') self.options.cluster_handle.write('[Jobs]\n') # This returns the command to run as well as builds the parameters of the test # The resulting command once this loop has completed is sufficient to launch # all previous jobs command = tester.getCommand(self.options) self.options.cluster_handle.write('[]\n') self.options.test_serial_number += 1 else: # This job is skipped - notify the runner if (reason != ''): self.handleTestResult(tester.parameters(), '', reason) self.runner.jobSkipped(tester.parameters()['test_name']) # Close the tests.cluster file if self.options.cluster_handle is not None: self.options.cluster_handle.close() self.options.cluster_handle = None # Return the final tester/command (sufficient to run all tests) return (tester, command) def prunePath(self, filename): test_dir = os.path.abspath(os.path.dirname(filename)) # Filter tests that we want to run # Under the new format, we will filter based on directory not filename since it is fixed prune = True if len(self.tests) == 0: prune = False # No filter else: for item in self.tests: if test_dir.find(item) > -1: prune = False # Return the inverse of will_run to indicate that this path should be pruned return prune def augmentParameters(self, filename, tester): params = tester.parameters() # We are going to do some formatting of the path that is printed # Case 1. If the test directory (normally matches the input_file_name) comes first, # we will simply remove it from the path # Case 2. If the test directory is somewhere in the middle then we should preserve # the leading part of the path test_dir = os.path.abspath(os.path.dirname(filename)) relative_path = test_dir.replace(self.run_tests_dir, '') relative_path = relative_path.replace('/' + self.options.input_file_name + '/', ':') relative_path = re.sub('^[/:]*', '', relative_path) # Trim slashes and colons formatted_name = relative_path + '.' + tester.name() params['test_name'] = formatted_name params['test_dir'] = test_dir params['relative_path'] = relative_path params['executable'] = self.executable params['hostname'] = self.host_name params['moose_dir'] = self.moose_dir params['base_dir'] = self.base_dir if params.isValid('prereq'): if type(params['prereq']) != list: print "Option 'prereq' needs to be of type list in " + params['test_name'] sys.exit(1) params['prereq'] = [relative_path.replace('/tests/', '') + '.' + item for item in params['prereq']] # This method splits a lists of tests into two pieces each, the first piece will run the test for # approx. half the number of timesteps and will write out a restart file. The second test will # then complete the run using the MOOSE recover option. def appendRecoverableTests(self, testers): new_tests = [] for part1 in testers: if part1.parameters()['recover'] == True: # Clone the test specs part2 = copy.deepcopy(part1) # Part 1: part1_params = part1.parameters() part1_params['test_name'] += '_part1' part1_params['cli_args'].append('--half-transient :Outputs/checkpoint=true') part1_params['skip_checks'] = True # Part 2: part2_params = part2.parameters() part2_params['prereq'].append(part1.parameters()['test_name']) part2_params['delete_output_before_running'] = False part2_params['cli_args'].append('--recover') part2_params.addParam('caveats', ['recover'], "") new_tests.append(part2) testers.extend(new_tests) return testers ## Finish the test by inspecting the raw output def testOutputAndFinish(self, tester, retcode, output, start=0, end=0): caveats = [] test = tester.specs # Need to refactor if test.isValid('caveats'): caveats = test['caveats'] if self.options.pbs and self.options.processingPBS == False: (reason, output) = self.buildPBSBatch(output, tester) elif self.options.dry_run: reason = 'DRY_RUN' output += '\n'.join(tester.processResultsCommand(self.moose_dir, self.options)) else: (reason, output) = tester.processResults(self.moose_dir, retcode, self.options, output) if self.options.scaling and test['scale_refine']: caveats.append('scaled') did_pass = True if reason == '': # It ran OK but is this test set to be skipped on any platform, compiler, so other reason? if self.options.extra_info: checks = ['platform', 'compiler', 'petsc_version', 'mesh_mode', 'method', 'library_mode', 'dtk', 'unique_ids'] for check in checks: if not 'ALL' in test[check]: caveats.append(', '.join(test[check])) if len(caveats): result = '[' + ', '.join(caveats).upper() + '] OK' elif self.options.pbs and self.options.processingPBS == False: result = 'LAUNCHED' else: result = 'OK' elif reason == 'DRY_RUN': result = 'DRY_RUN' else: result = 'FAILED (%s)' % reason did_pass = False if self.options.pbs and self.options.processingPBS == False and did_pass == True: # Handle the launch result, but do not add it to the results table (except if we learned that QSUB failed to launch for some reason) self.handleTestResult(tester.specs, output, result, start, end, False) return did_pass else: self.handleTestResult(tester.specs, output, result, start, end) return did_pass def getTiming(self, output): time = '' m = re.search(r"Active time=(\S+)", output) if m != None: return m.group(1) def getSolveTime(self, output): time = '' m = re.search(r"solve().*", output) if m != None: return m.group().split()[5] def checkExpectError(self, output, expect_error): if re.search(expect_error, output, re.MULTILINE | re.DOTALL) == None: #print "%" * 100, "\nExpect Error Pattern not found:\n", expect_error, "\n", "%" * 100, "\n" return False else: return True # PBS Defs def checkPBSEmulator(self): try: qstat_process = subprocess.Popen(['qstat', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) qstat_output = qstat_process.communicate() except OSError: # qstat binary is not available print 'qstat not available. Perhaps you need to load the PBS module?' sys.exit(1) if len(qstat_output[1]): # The PBS Emulator has no --version argument, and thus returns output to stderr return True else: return False def processPBSResults(self): # If batch file exists, check the contents for pending tests. if os.path.exists(self.options.pbs): # Build a list of launched jobs batch_file = open(self.options.pbs) batch_list = [y.split(':') for y in [x for x in batch_file.read().split('\n')]] batch_file.close() del batch_list[-1:] # Loop through launched jobs and match the TEST_NAME to determin correct stdout (Output_Path) for job in batch_list: file = '/'.join(job[2].split('/')[:-2]) + '/' + job[3] # Build a Warehouse to hold the MooseObjects warehouse = Warehouse() # Build a Parser to parse the objects parser = Parser(self.factory, warehouse) # Parse it parser.parse(file) # Retrieve the tests from the warehouse testers = warehouse.getAllObjects() for tester in testers: self.augmentParameters(file, tester) for tester in testers: # Build the requested Tester object if job[1] == tester.parameters()['test_name']: # Create Test Type # test = self.factory.create(tester.parameters()['type'], tester) # Get job status via qstat qstat = ['qstat', '-f', '-x', str(job[0])] qstat_command = subprocess.Popen(qstat, stdout=subprocess.PIPE, stderr=subprocess.PIPE) qstat_stdout = qstat_command.communicate()[0] if qstat_stdout != None: output_value = re.search(r'job_state = (\w+)', qstat_stdout).group(1) else: return ('QSTAT NOT FOUND', '') # Report the current status of JOB_ID if output_value == 'F': # F = Finished. Get the exit code reported by qstat exit_code = int(re.search(r'Exit_status = (-?\d+)', qstat_stdout).group(1)) # Read the stdout file if os.path.exists(job[2]): output_file = open(job[2], 'r') # Not sure I am doing this right: I have to change the TEST_DIR to match the temporary cluster_launcher TEST_DIR location, thus violating the tester.specs... tester.parameters()['test_dir'] = '/'.join(job[2].split('/')[:-1]) outfile = output_file.read() output_file.close() self.testOutputAndFinish(tester, exit_code, outfile) else: # I ran into this scenario when the cluster went down, but launched/completed my job :) self.handleTestResult(tester.specs, '', 'FAILED (NO STDOUT FILE)', 0, 0, True) elif output_value == 'R': # Job is currently running self.handleTestResult(tester.specs, '', 'RUNNING', 0, 0, True) elif output_value == 'E': # Job is exiting self.handleTestResult(tester.specs, '', 'EXITING', 0, 0, True) elif output_value == 'Q': # Job is currently queued self.handleTestResult(tester.specs, '', 'QUEUED', 0, 0, True) else: return ('BATCH FILE NOT FOUND', '') def buildPBSBatch(self, output, tester): # Create/Update the batch file if 'command not found' in output: return ('QSUB NOT FOUND', '') else: # Get the Job information from the ClusterLauncher results = re.findall(r'JOB_NAME: (\w+) JOB_ID:.* (\d+).*TEST_NAME: (\S+)', output) if len(results) != 0: file_name = self.options.pbs job_list = open(os.path.abspath(os.path.join(tester.specs['executable'], os.pardir)) + '/' + file_name, 'a') for result in results: (test_dir, job_id, test_name) = result qstat_command = subprocess.Popen(['qstat', '-f', '-x', str(job_id)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) qstat_stdout = qstat_command.communicate()[0] # Get the Output_Path from qstat stdout if qstat_stdout != None: output_value = re.search(r'Output_Path(.*?)(^ +)', qstat_stdout, re.S | re.M).group(1) output_value = output_value.split(':')[1].replace('\n', '').replace('\t', '').strip() else: job_list.close() return ('QSTAT NOT FOUND', '') # Write job_id, test['test_name'], and Ouput_Path to the batch file job_list.write(str(job_id) + ':' + test_name + ':' + output_value + ':' + self.options.input_file_name + '\n') # Return to TestHarness and inform we have launched the job job_list.close() return ('', 'LAUNCHED') else: return ('QSTAT INVALID RESULTS', output) def cleanPBSBatch(self): # Open the PBS batch file and assign it to a list if os.path.exists(self.options.pbs_cleanup): batch_file = open(self.options.pbs_cleanup, 'r') batch_list = [y.split(':') for y in [x for x in batch_file.read().split('\n')]] batch_file.close() del batch_list[-1:] else: print 'PBS batch file not found:', self.options.pbs_cleanup sys.exit(1) # Loop through launched jobs and delete whats found. for job in batch_list: if os.path.exists(job[2]): batch_dir = os.path.abspath(os.path.join(job[2], os.pardir)).split('/') if os.path.exists('/'.join(batch_dir)): shutil.rmtree('/'.join(batch_dir)) if os.path.exists('/'.join(batch_dir[:-1]) + '/' + self.options.pbs_cleanup + '.cluster'): os.remove('/'.join(batch_dir[:-1]) + '/' + self.options.pbs_cleanup + '.cluster') os.remove(self.options.pbs_cleanup) # END PBS Defs ## Update global variables and print output based on the test result # Containing OK means it passed, skipped means skipped, anything else means it failed def handleTestResult(self, specs, output, result, start=0, end=0, add_to_table=True): timing = '' if self.options.timing: timing = self.getTiming(output) elif self.options.store_time: timing = self.getSolveTime(output) # Only add to the test_table if told to. We now have enough cases where we wish to print to the screen, but not # in the 'Final Test Results' area. if add_to_table: self.test_table.append( (specs, output, result, timing, start, end) ) if result.find('OK') != -1 or result.find('DRY_RUN') != -1: self.num_passed += 1 elif result.find('skipped') != -1: self.num_skipped += 1 elif result.find('deleted') != -1: self.num_skipped += 1 elif result.find('LAUNCHED') != -1 or result.find('RUNNING') != -1 or result.find('QUEUED') != -1 or result.find('EXITING') != -1: self.num_pending += 1 else: self.num_failed += 1 self.postRun(specs, timing) if self.options.show_directory: print printResult(specs['relative_path'] + '/' + specs['test_name'].split('/')[-1], result, timing, start, end, self.options) else: print printResult(specs['test_name'], result, timing, start, end, self.options) if self.options.verbose or ('FAILED' in result and not self.options.quiet): output = output.replace('\r', '\n') # replace the carriage returns with newlines lines = output.split('\n'); color = '' if 'EXODIFF' in result or 'CSVDIFF' in result: color = 'YELLOW' elif 'FAILED' in result: color = 'RED' else: color = 'GREEN' test_name = colorText(specs['test_name'] + ": ", color, colored=self.options.colored, code=self.options.code) output = test_name + ("\n" + test_name).join(lines) print output # Print result line again at the bottom of the output for failed tests if self.options.show_directory: print printResult(specs['relative_path'] + '/' + specs['test_name'].split('/')[-1], result, timing, start, end, self.options), "(reprint)" else: print printResult(specs['test_name'], result, timing, start, end, self.options), "(reprint)" if not 'skipped' in result: if self.options.file: if self.options.show_directory: self.file.write(printResult( specs['relative_path'] + '/' + specs['test_name'].split('/')[-1], result, timing, start, end, self.options, color=False) + '\n') self.file.write(output) else: self.file.write(printResult( specs['test_name'], result, timing, start, end, self.options, color=False) + '\n') self.file.write(output) if self.options.sep_files or (self.options.fail_files and 'FAILED' in result) or (self.options.ok_files and result.find('OK') != -1): fname = os.path.join(specs['test_dir'], specs['test_name'].split('/')[-1] + '.' + result[:6] + '.txt') f = open(fname, 'w') f.write(printResult( specs['test_name'], result, timing, start, end, self.options, color=False) + '\n') f.write(output) f.close() # Write the app_name to a file, if the tests passed def writeState(self, app_name): # If we encounter bitten_status_moose environment, build a line itemized list of applications which passed their tests if os.environ.has_key("BITTEN_STATUS_MOOSE"): result_file = open(os.path.join(self.moose_dir, 'test_results.log'), 'a') result_file.write(os.path.split(app_name)[1].split('-')[0] + '\n') result_file.close() # Print final results, close open files, and exit with the correct error code def cleanup(self): # Print the results table again if a bunch of output was spewed to the screen between # tests as they were running if self.options.verbose or (self.num_failed != 0 and not self.options.quiet): print '\n\nFinal Test Results:\n' + ('-' * (TERM_COLS-1)) for (test, output, result, timing, start, end) in sorted(self.test_table, key=lambda x: x[2], reverse=True): if self.options.show_directory: print printResult(test['relative_path'] + '/' + specs['test_name'].split('/')[-1], result, timing, start, end, self.options) else: print printResult(test['test_name'], result, timing, start, end, self.options) time = clock() - self.start_time print '-' * (TERM_COLS-1) print 'Ran %d tests in %.1f seconds' % (self.num_passed+self.num_failed, time) if self.num_passed: summary = '<g>%d passed</g>' else: summary = '<b>%d passed</b>' summary += ', <b>%d skipped</b>' if self.num_pending: summary += ', <c>%d pending</c>' else: summary += ', <b>%d pending</b>' if self.num_failed: summary += ', <r>%d FAILED</r>' else: summary += ', <b>%d failed</b>' # Mask off TestHarness error codes to report parser errors if self.error_code & 0x0F: summary += ', <r>FATAL PARSER ERROR</r>' print colorText( summary % (self.num_passed, self.num_skipped, self.num_pending, self.num_failed), "", html = True, \ colored=self.options.colored, code=self.options.code ) if self.options.pbs: print '\nYour PBS batch file:', self.options.pbs if self.file: self.file.close() if self.num_failed == 0: self.writeState(self.executable) def initialize(self, argv, app_name): # Initialize the parallel runner with how many tests to run in parallel self.runner = RunParallel(self, self.options.jobs, self.options.load) ## Save executable-under-test name to self.executable self.executable = os.getcwd() + '/' + app_name + '-' + self.options.method # Save the output dir since the current working directory changes during tests self.output_dir = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), self.options.output_dir) # Create the output dir if they ask for it. It is easier to ask for forgiveness than permission if self.options.output_dir: try: os.makedirs(self.output_dir) except OSError, ex: if ex.errno == errno.EEXIST: pass else: raise # Open the file to redirect output to and set the quiet option for file output if self.options.file: self.file = open(os.path.join(self.output_dir, self.options.file), 'w') if self.options.file or self.options.fail_files or self.options.sep_files: self.options.quiet = True ## Parse command line options and assign them to self.options def parseCLArgs(self, argv): parser = argparse.ArgumentParser(description='A tool used to test MOOSE based applications') parser.add_argument('test_name', nargs=argparse.REMAINDER) parser.add_argument('--opt', action='store_const', dest='method', const='opt', help='test the app_name-opt binary') parser.add_argument('--dbg', action='store_const', dest='method', const='dbg', help='test the app_name-dbg binary') parser.add_argument('--devel', action='store_const', dest='method', const='devel', help='test the app_name-devel binary') parser.add_argument('--oprof', action='store_const', dest='method', const='oprof', help='test the app_name-oprof binary') parser.add_argument('--pro', action='store_const', dest='method', const='pro', help='test the app_name-pro binary') parser.add_argument('-j', '--jobs', nargs='?', metavar='int', action='store', type=int, dest='jobs', const=1, help='run test binaries in parallel') parser.add_argument('-e', action='store_true', dest='extra_info', help='Display "extra" information including all caveats and deleted tests') parser.add_argument('-c', '--no-color', action='store_false', dest='colored', help='Do not show colored output') parser.add_argument('--heavy', action='store_true', dest='heavy_tests', help='Run tests marked with HEAVY : True') parser.add_argument('--all-tests', action='store_true', dest='all_tests', help='Run normal tests and tests marked with HEAVY : True') parser.add_argument('-g', '--group', action='store', type=str, dest='group', default='ALL', help='Run only tests in the named group') parser.add_argument('--not_group', action='store', type=str, dest='not_group', help='Run only tests NOT in the named group') # parser.add_argument('--dofs', action='store', dest='dofs', help='This option is for automatic scaling which is not currently implemented in MOOSE 2.0') parser.add_argument('--dbfile', nargs='?', action='store', dest='dbFile', help='Location to timings data base file. If not set, assumes $HOME/timingDB/timing.sqlite') parser.add_argument('-l', '--load-average', action='store', type=float, dest='load', default=64.0, help='Do not run additional tests if the load average is at least LOAD') parser.add_argument('-t', '--timing', action='store_true', dest='timing', help='Report Timing information for passing tests') parser.add_argument('-s', '--scale', action='store_true', dest='scaling', help='Scale problems that have SCALE_REFINE set') parser.add_argument('-i', nargs=1, action='store', type=str, dest='input_file_name', default='tests', help='The default test specification file to look for (default="tests").') parser.add_argument('--libmesh_dir', nargs=1, action='store', type=str, dest='libmesh_dir', help='Currently only needed for bitten code coverage') parser.add_argument('--skip-config-checks', action='store_true', dest='skip_config_checks', help='Skip configuration checks (all tests will run regardless of restrictions)') parser.add_argument('--parallel', '-p', nargs='?', action='store', type=int, dest='parallel', const=1, help='Number of processors to use when running mpiexec') parser.add_argument('--n-threads', nargs=1, action='store', type=int, dest='nthreads', default=1, help='Number of threads to use when running mpiexec') parser.add_argument('-d', action='store_true', dest='debug_harness', help='Turn on Test Harness debugging') parser.add_argument('--recover', action='store_true', dest='enable_recover', help='Run a test in recover mode') parser.add_argument('--valgrind', action='store_const', dest='valgrind_mode', const='NORMAL', help='Run normal valgrind tests') parser.add_argument('--valgrind-heavy', action='store_const', dest='valgrind_mode', const='HEAVY', help='Run heavy valgrind tests') parser.add_argument('--valgrind-max-fails', nargs=1, type=int, dest='valgrind_max_fails', default=5, help='The number of valgrind tests allowed to fail before any additional valgrind tests will run') parser.add_argument('--max-fails', nargs=1, type=int, dest='max_fails', default=50, help='The number of tests allowed to fail before any additional tests will run') parser.add_argument('--pbs', nargs='?', metavar='batch_file', dest='pbs', const='generate', help='Enable launching tests via PBS. If no batch file is specified one will be created for you') parser.add_argument('--pbs-cleanup', nargs=1, metavar='batch_file', help='Clean up the directories/files created by PBS. You must supply the same batch_file used to launch PBS.') parser.add_argument('--pbs-project', nargs=1, default='moose', help='Identify PBS job submission to specified project') parser.add_argument('--re', action='store', type=str, dest='reg_exp', help='Run tests that match --re=regular_expression') # Options that pass straight through to the executable parser.add_argument('--parallel-mesh', action='store_true', dest='parallel_mesh', help='Deprecated, use --distributed-mesh instead') parser.add_argument('--distributed-mesh', action='store_true', dest='distributed_mesh', help='Pass "--distributed-mesh" to executable') parser.add_argument('--error', action='store_true', help='Run the tests with warnings as errors (Pass "--error" to executable)') parser.add_argument('--error-unused', action='store_true', help='Run the tests with errors on unused parameters (Pass "--error-unused" to executable)') # Option to use for passing unwrapped options to the executable parser.add_argument('--cli-args', nargs='?', type=str, dest='cli_args', help='Append the following list of arguments to the command line (Encapsulate the command in quotes)') parser.add_argument('--dry-run', action='store_true', dest='dry_run', help="Pass --dry-run to print commands to run, but don't actually run them") outputgroup = parser.add_argument_group('Output Options', 'These options control the output of the test harness. The sep-files options write output to files named test_name.TEST_RESULT.txt. All file output will overwrite old files') outputgroup.add_argument('-v', '--verbose', action='store_true', dest='verbose', help='show the output of every test') outputgroup.add_argument('-q', '--quiet', action='store_true', dest='quiet', help='only show the result of every test, don\'t show test output even if it fails') outputgroup.add_argument('--no-report', action='store_false', dest='report_skipped', help='do not report skipped tests') outputgroup.add_argument('--show-directory', action='store_true', dest='show_directory', help='Print test directory path in out messages') outputgroup.add_argument('-o', '--output-dir', nargs=1, metavar='directory', dest='output_dir', default='', help='Save all output files in the directory, and create it if necessary') outputgroup.add_argument('-f', '--file', nargs=1, action='store', dest='file', help='Write verbose output of each test to FILE and quiet output to terminal') outputgroup.add_argument('-x', '--sep-files', action='store_true', dest='sep_files', help='Write the output of each test to a separate file. Only quiet output to terminal. This is equivalant to \'--sep-files-fail --sep-files-ok\'') outputgroup.add_argument('--sep-files-ok', action='store_true', dest='ok_files', help='Write the output of each passed test to a separate file') outputgroup.add_argument('-a', '--sep-files-fail', action='store_true', dest='fail_files', help='Write the output of each FAILED test to a separate file. Only quiet output to terminal.') outputgroup.add_argument("--store-timing", action="store_true", dest="store_time", help="Store timing in the SQL database: $HOME/timingDB/timing.sqlite A parent directory (timingDB) must exist.") outputgroup.add_argument("--revision", nargs=1, action="store", type=str, dest="revision", help="The current revision being tested. Required when using --store-timing.") outputgroup.add_argument("--yaml", action="store_true", dest="yaml", help="Dump the parameters for the testers in Yaml Format") outputgroup.add_argument("--dump", action="store_true", dest="dump", help="Dump the parameters for the testers in GetPot Format") code = True if self.code.decode('hex') in argv: del argv[argv.index(self.code.decode('hex'))] code = False self.options = parser.parse_args(argv[1:]) self.tests = self.options.test_name self.options.code = code # Convert all list based options of length one to scalars for key, value in vars(self.options).items(): if type(value) == list and len(value) == 1: tmp_str = getattr(self.options, key) setattr(self.options, key, value[0]) self.checkAndUpdateCLArgs() ## Called after options are parsed from the command line # Exit if options don't make any sense, print warnings if they are merely weird def checkAndUpdateCLArgs(self): opts = self.options if opts.output_dir and not (opts.file or opts.sep_files or opts.fail_files or opts.ok_files): print 'WARNING: --output-dir is specified but no output files will be saved, use -f or a --sep-files option' if opts.group == opts.not_group: print 'ERROR: The group and not_group options cannot specify the same group' sys.exit(1) if opts.store_time and not (opts.revision): print 'ERROR: --store-timing is specified but no revision' sys.exit(1) if opts.store_time: # timing returns Active Time, while store_timing returns Solve Time. # Thus we need to turn off timing. opts.timing = False opts.scaling = True if opts.valgrind_mode and (opts.parallel > 1 or opts.nthreads > 1): print 'ERROR: --parallel and/or --threads can not be used with --valgrind' sys.exit(1) # Update any keys from the environment as necessary if not self.options.method: if os.environ.has_key('METHOD'): self.options.method = os.environ['METHOD'] else: self.options.method = 'opt' if not self.options.valgrind_mode: self.options.valgrind_mode = '' # Update libmesh_dir to reflect arguments if opts.libmesh_dir: self.libmesh_dir = opts.libmesh_dir # Generate a batch file if PBS argument supplied with out a file if opts.pbs == 'generate': largest_serial_num = 0 for name in os.listdir('.'): m = re.search('pbs_(\d{3})', name) if m != None and int(m.group(1)) > largest_serial_num: largest_serial_num = int(m.group(1)) opts.pbs = "pbs_" + str(largest_serial_num+1).zfill(3) # When running heavy tests, we'll make sure we use --no-report if opts.heavy_tests: self.options.report_skipped = False def postRun(self, specs, timing): return def preRun(self): if self.options.yaml: self.factory.printYaml("Tests") sys.exit(0) elif self.options.dump: self.factory.printDump("Tests") sys.exit(0) if self.options.pbs_cleanup: self.cleanPBSBatch() sys.exit(0) def getOptions(self): return self.options ################################################################################################################################# # The TestTimer TestHarness # This method finds and stores timing for individual tests. It is activated with --store-timing ################################################################################################################################# CREATE_TABLE = """create table timing ( app_name text, test_name text, revision text, date int, seconds real, scale int, load real );""" class TestTimer(TestHarness): def __init__(self, argv, app_name, moose_dir): TestHarness.__init__(self, argv, app_name, moose_dir) try: from sqlite3 import dbapi2 as sqlite except: print 'Error: --store-timing requires the sqlite3 python module.' sys.exit(1) self.app_name = app_name self.db_file = self.options.dbFile if not self.db_file: home = os.environ['HOME'] self.db_file = os.path.join(home, 'timingDB/timing.sqlite') if not os.path.exists(self.db_file): print 'Warning: creating new database at default location: ' + str(self.db_file) self.createDB(self.db_file) else: print 'Warning: Assuming database location ' + self.db_file def createDB(self, fname): from sqlite3 import dbapi2 as sqlite print 'Creating empty database at ' + fname con = sqlite.connect(fname) cr = con.cursor() cr.execute(CREATE_TABLE) con.commit() def preRun(self): from sqlite3 import dbapi2 as sqlite # Delete previous data if app_name and repo revision are found con = sqlite.connect(self.db_file) cr = con.cursor() cr.execute('delete from timing where app_name = ? and revision = ?', (self.app_name, self.options.revision)) con.commit() # After the run store the results in the database def postRun(self, test, timing): from sqlite3 import dbapi2 as sqlite con = sqlite.connect(self.db_file) cr = con.cursor() timestamp = int(time.time()) load = os.getloadavg()[0] # accumulate the test results data = [] sum_time = 0 num = 0 parse_failed = False # Were only interested in storing scaled data if timing != None and test['scale_refine'] != 0: sum_time += float(timing) num += 1 data.append( (self.app_name, test['test_name'].split('/').pop(), self.options.revision, timestamp, timing, test['scale_refine'], load) ) # Insert the data into the database cr.executemany('insert into timing values (?,?,?,?,?,?,?)', data) con.commit()
katyhuff/moose
python/TestHarness/TestHarness.py
Python
lgpl-2.1
44,147
[ "MOOSE", "VTK" ]
8099fc8e557db937f9c92b80dd0d4199a940178a1c934a5e7a92e9c369fa0419
# class generated by DeVIDE::createDeVIDEModuleFromVTKObject from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase import vtk class vtkImageGradientMagnitude(SimpleVTKClassModuleBase): def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkImageGradientMagnitude(), 'Processing.', ('vtkImageData',), ('vtkImageData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
chrisidefix/devide
modules/vtk_basic/vtkImageGradientMagnitude.py
Python
bsd-3-clause
507
[ "VTK" ]
7cc6699cf7d95b0d1e022211dfefe356c9a283e7f2649806145fa4613e0309f8
from __future__ import absolute_import from __future__ import print_function from __future__ import division import unittest import os import numpy as np from pymatgen.analysis.ferroelectricity.polarization import * from pymatgen.core.structure import Structure from pymatgen.io.vasp.outputs import Outcar from pymatgen.io.vasp.inputs import Potcar from pymatgen.util.testing import PymatgenTest test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", 'test_files/BTO_221_99_polarization') bto_folders = ['nonpolar_polarization'] bto_folders += ['interpolation_{}_polarization'.format(str(i)) for i in range(1,9)][::-1] bto_folders += ['polar_polarization'] structures = [Structure.from_file(test_dir+"/"+folder+"/POSCAR") for folder in bto_folders] ions = np.matrix([[-44.363484, -44.363484, -44.79259988], [-44.324764, -44.324764, -69.43452043], [-44.286055, -44.286055, -69.8792077 ], [-44.247335, -44.247335, -70.32475473], [-44.208626, -44.208626, -70.77139856], [-44.169906, -44.169906, -71.21889307], [-44.131197, -44.131197, -71.66746921], [-44.092477, -44.092477, -72.1168782 ], [-44.053768, -44.053768, -72.56736141], [-44.015048, -44.015048, -73.01874336]]) class UtilsTest(PymatgenTest): def setUp(self): self.potcar = Potcar.from_file(test_dir+"/POTCAR") self.zval_dict = {'Ba': 10.0, 'Ti': 10.0, 'O': 6.0} self.ions = ions self.structures = structures def test_zval_dict_from_potcar(self): zval_dict = zval_dict_from_potcar(self.potcar) self.assertDictEqual(self.zval_dict, zval_dict) def test_get_total_ionic_dipole(self): p_ion = get_total_ionic_dipole(self.structures[-1],self.zval_dict) self.assertArrayAlmostEqual(p_ion, self.ions[-1].A1.tolist()) class PolarizationTest(PymatgenTest): def setUp(self): self.p_ions = ions self.p_ions_outcar = np.matrix([[0.0, 0.0, 43.93437], [0.0, 0.0, 19.81697], [0.0, 0.0, 19.76076], [0.0, 0.0, 19.70306], [0.0, 0.0, 19.64372], [0.0, 0.0, -5.06619], [0.0, 0.0, -5.18997], [0.0, 0.0, -5.31457], [0.0, 0.0, -5.44026], [0.0, 0.0, -5.56684]]) self.p_elecs = np.matrix([[4.03304, -4.03304, -3.60393], [4.02958, 4.02958, -3.77177], [4.02611, 4.02611, -3.93397], [4.02264, 4.02263, -4.08851], [4.01916, 4.01914, 3.99662], [4.01567, 4.01565, 3.90327], [4.01217, 4.01214, 3.81998], [4.00867, 4.00863, 3.74561], [4.00517, 4.00512, 3.67949], [0.00024, 0.00019, 3.61674]]) self.same_branch = np.matrix([[ 9.76948106e-05, -9.76948108e-05, 4.59556390e-05], [ -1.36325612e-03, -1.36325612e-03, 5.99098550e+00], [ -2.54781559e-03, -2.54781559e-03, 1.18312234e+01], [ -3.74896442e-03, -3.50709575e-03, 1.74695147e+01], [ -4.67728039e-03, -4.19508654e-03, 2.28288548e+01], [ -5.38348125e-03, -4.90281328e-03, 2.79488973e+01], [ -5.82178137e-03, -5.10304293e-03, 3.28220345e+01], [ -6.28132190e-03, -5.32598777e-03, 3.74721262e+01], [ -6.71430111e-03, -5.52382219e-03, 4.19231297e+01], [ -5.69679257e-03, -4.50996078e-03, 4.62887982e+01]]) self.quanta = np.matrix([[ 98.50186747, 98.50186747, 98.50186747], [ 98.09416498, 98.09416498, 98.67403571], [ 97.69065056, 97.69065056, 98.84660662], [ 97.29131054, 97.29131054, 99.01967988], [ 96.89603543, 96.89603543, 99.19315873], [ 96.50481368, 96.50481368, 99.36714337], [ 96.11753848, 96.11753848, 99.54153654], [ 95.7342003 , 95.7342003 , 99.71643897], [ 95.35469487, 95.35469487, 99.89175289], [ 94.97901455, 94.97901455, 100.06757957]]) self.structures = structures self.polarization = Polarization(self.p_elecs, self.p_ions, self.structures) self.outcars = [Outcar(test_dir+"/"+folder+"/OUTCAR") for folder in bto_folders] self.change = np.matrix([[ -5.79448738e-03, -4.41226597e-03, 4.62887522e+01]]) self.change_norm = 46.288752795325244 self.max_jumps = [0.00021336004941047062, 0.00016254800426403291, 0.038269946959965086] self.smoothness = [0.00017013512377086267, 0.00013467465540412905, 0.034856268571937743] def test_from_outcars_and_structures(self): polarization = Polarization.from_outcars_and_structures(self.outcars, self.structures) p_elecs, p_ions = polarization.get_pelecs_and_pions(convert_to_muC_per_cm2=False) self.assertArrayAlmostEqual(p_elecs[0].A1.tolist(), self.p_elecs[0].A1.tolist()) self.assertArrayAlmostEqual(p_elecs[-1].A1.tolist(), self.p_elecs[-1].A1.tolist()) self.assertArrayAlmostEqual(p_ions[0].A1.tolist(), self.p_ions_outcar[0].A1.tolist()) self.assertArrayAlmostEqual(p_ions[-1].A1.tolist(), self.p_ions_outcar[-1].A1.tolist()) # Test for calc_ionic_from_zval=True polarization = Polarization.from_outcars_and_structures(self.outcars, self.structures, calc_ionic_from_zval=True) p_elecs, p_ions = polarization.get_pelecs_and_pions(convert_to_muC_per_cm2=False) self.assertArrayAlmostEqual(p_elecs[0].A1.tolist(), self.p_elecs[0].A1.tolist()) self.assertArrayAlmostEqual(p_elecs[-1].A1.tolist(), self.p_elecs[-1].A1.tolist()) self.assertArrayAlmostEqual(p_ions[0].A1.tolist(), self.p_ions[0].A1.tolist()) self.assertArrayAlmostEqual(p_ions[-1].A1.tolist(), self.p_ions[-1].A1.tolist()) def test_get_same_branch_polarization_data(self): same_branch = self.polarization.get_same_branch_polarization_data(convert_to_muC_per_cm2=True) self.assertArrayAlmostEqual(same_branch[0].A1.tolist(), self.same_branch[0].A1.tolist()) self.assertArrayAlmostEqual(same_branch[-1].A1.tolist(), self.same_branch[-1].A1.tolist()) def test_get_lattice_quanta(self): quanta = self.polarization.get_lattice_quanta(convert_to_muC_per_cm2=True) self.assertArrayAlmostEqual(quanta[0].A1.tolist(), self.quanta[0].A1.tolist()) self.assertArrayAlmostEqual(quanta[-1].A1.tolist(), self.quanta[-1].A1.tolist()) def test_get_polarization_change(self): change = self.polarization.get_polarization_change() self.assertArrayAlmostEqual(change, self.change) def test_get_polarization_change_norm(self): change_norm = self.polarization.get_polarization_change_norm() self.assertAlmostEqual(change_norm, self.change_norm) def test_max_spline_jumps(self): max_jumps = self.polarization.max_spline_jumps() self.assertArrayAlmostEqual(self.max_jumps, max_jumps) def test_smoothness(self): smoothness = self.polarization.smoothness() self.assertArrayAlmostEqual(self.smoothness, smoothness) class EnergyTrendTest(PymatgenTest): def setUp(self): self.energies = [-7.97738049, -7.988621176, -7.9793246479999995, -7.987973192, -7.984676138, -7.982700144000001, -7.986539788, -7.980859048000001, -7.978240114, -7.977637218] self.energy_trend = EnergyTrend(self.energies) self.smoothness = 0.0029874731764648306 self.max_jump = 0.0058893082867133018 def test_max_spline_jump(self): max_jump = self.energy_trend.max_spline_jump() self.assertAlmostEqual(max_jump, self.max_jump) def test_smoothness(self): smoothness = self.energy_trend.smoothness() self.assertAlmostEqual(smoothness, self.smoothness) def test_endpoints_minima(self): endpoints = self.energy_trend.endpoints_minima(slope_cutoff=1e-2) self.assertDictEqual({'polar': True, 'nonpolar': True}, endpoints) if __name__ == '__main__': unittest.main()
xhqu1981/pymatgen
pymatgen/analysis/ferroelectricity/tests/test_polarization.py
Python
mit
9,344
[ "VASP", "pymatgen" ]
d7b6342fe8acc016cbd45e9e1a56bab567f4b818847d0cfb90d70bdb87af160b
#! /usr/bin/env python3 from vasppy.poscar import Poscar import math import argparse def parse_command_line_arguments(): parser = argparse.ArgumentParser( description='Rotates the cell lattice in VASP POSCAR files' ) parser.add_argument( 'poscar', help="filename of the VASP POSCAR to be processed" ) parser.add_argument( '-a', '--axis', nargs=3, type=float, help="vector for rotation axis", required=True ) parser.add_argument( '-d', '--degrees', type=int, help="rotation angle in degrees", required=True ) args = parser.parse_args() return( args ) def main(): args = parse_command_line_arguments() poscar = Poscar() poscar.read_from( args.poscar ) theta = math.pi * args.degrees / 180.0 poscar.cell.rotate( args.axis, theta ) poscar.output() if __name__ == "__main__": main()
bjmorgan/vasppy
vasppy/scripts/rotate_poscar.py
Python
mit
834
[ "VASP" ]
f0ae190251174f22c82d65828f933e4803716e479a17f7ea8623e1df52d0aa20
../../../../share/pyshared/orca/orca_i18n.py
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/orca/orca_i18n.py
Python
gpl-3.0
44
[ "ORCA" ]
7f1ae9be8838eb41962cd444c8c5a8d89b56c4bcbbde8261d5a39db6f7eeba07
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals import math import numpy as np from monty.dev import deprecated from pymatgen.core.periodic_table import Element """ Utilities for generating nicer plots. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "Mar 13, 2012" def pretty_plot(width=8, height=None, plt=None, dpi=None, color_cycle=("qualitative", "Set1_9")): """ Provides a publication quality plot, with nice defaults for font sizes etc. Args: width (float): Width of plot in inches. Defaults to 8in. height (float): Height of plot in inches. Defaults to width * golden ratio. plt (matplotlib.pyplot): If plt is supplied, changes will be made to an existing plot. Otherwise, a new plot will be created. dpi (int): Sets dot per inch for figure. Defaults to 300. color_cycle (tuple): Set the color cycle for new plots to one of the color sets in palettable. Defaults to a qualitative Set1_9. Returns: Matplotlib plot object with properly sized fonts. """ ticksize = int(width * 2.5) golden_ratio = (math.sqrt(5) - 1) / 2 if not height: height = int(width * golden_ratio) if plt is None: import matplotlib.pyplot as plt import importlib mod = importlib.import_module("palettable.colorbrewer.%s" % color_cycle[0]) colors = getattr(mod, color_cycle[1]).mpl_colors from cycler import cycler plt.figure(figsize=(width, height), facecolor="w", dpi=dpi) ax = plt.gca() ax.set_prop_cycle(cycler('color', colors)) else: fig = plt.gcf() fig.set_size_inches(width, height) plt.xticks(fontsize=ticksize) plt.yticks(fontsize=ticksize) ax = plt.gca() ax.set_title(ax.get_title(), size=width * 4) labelsize = int(width * 3) ax.set_xlabel(ax.get_xlabel(), size=labelsize) ax.set_ylabel(ax.get_ylabel(), size=labelsize) return plt @deprecated(pretty_plot, "get_publication_quality_plot has been renamed " "pretty_plot. This stub will be removed in pmg 2018.01.01.") def get_publication_quality_plot(*args, **kwargs): return pretty_plot(*args, **kwargs) def pretty_plot_two_axis(x, y1, y2, xlabel=None, y1label=None, y2label=None, width=8, height=None, dpi=300): """ Variant of pretty_plot that does a dual axis plot. Adapted from matplotlib examples. Makes it easier to create plots with different axes. Args: x (np.ndarray/list): Data for x-axis. y1 (dict/np.ndarray/list): Data for y1 axis (left). If a dict, it will be interpreted as a {label: sequence}. y2 (dict/np.ndarray/list): Data for y2 axis (right). If a dict, it will be interpreted as a {label: sequence}. xlabel (str): If not None, this will be the label for the x-axis. y1label (str): If not None, this will be the label for the y1-axis. y2label (str): If not None, this will be the label for the y2-axis. width (float): Width of plot in inches. Defaults to 8in. height (float): Height of plot in inches. Defaults to width * golden ratio. dpi (int): Sets dot per inch for figure. Defaults to 300. Returns: matplotlib.pyplot """ import palettable.colorbrewer.diverging colors = palettable.colorbrewer.diverging.RdYlBu_4.mpl_colors c1 = colors[0] c2 = colors[-1] golden_ratio = (math.sqrt(5) - 1) / 2 if not height: height = int(width * golden_ratio) import matplotlib.pyplot as plt width = 12 labelsize = int(width * 3) ticksize = int(width * 2.5) styles = ["-", "--", "-.", "."] fig, ax1 = plt.subplots() fig.set_size_inches((width, height)) if dpi: fig.set_dpi(dpi) if isinstance(y1, dict): for i, (k, v) in enumerate(y1.items()): ax1.plot(x, v, c=c1, marker='s', ls=styles[i % len(styles)], label=k) ax1.legend(fontsize=labelsize) else: ax1.plot(x, y1, c=c1, marker='s', ls='-') if xlabel: ax1.set_xlabel(xlabel, fontsize=labelsize) if y1label: # Make the y-axis label, ticks and tick labels match the line color. ax1.set_ylabel(y1label, color=c1, fontsize=labelsize) ax1.tick_params('x', labelsize=ticksize) ax1.tick_params('y', colors=c1, labelsize=ticksize) ax2 = ax1.twinx() if isinstance(y2, dict): for i, (k, v) in enumerate(y2.items()): ax2.plot(x, v, c=c2, marker='o', ls=styles[i % len(styles)], label=k) ax2.legend(fontsize=labelsize) else: ax2.plot(x, y2, c=c2, marker='o', ls='-') if y2label: # Make the y-axis label, ticks and tick labels match the line color. ax2.set_ylabel(y2label, color=c2, fontsize=labelsize) ax2.tick_params('y', colors=c2, labelsize=ticksize) return plt def pretty_polyfit_plot(x, y, deg=1, xlabel=None, ylabel=None, **kwargs): """ Convenience method to plot data with trend lines based on polynomial fit. Args: x: Sequence of x data. y: Sequence of y data. deg (int): Degree of polynomial. Defaults to 1. xlabel (str): Label for x-axis. ylabel (str): Label for y-axis. \\*\\*kwargs: Keyword args passed to pretty_plot. Returns: matplotlib.pyplot object. """ plt = pretty_plot(**kwargs) pp = np.polyfit(x, y, deg) xp = np.linspace(min(x), max(x), 200) plt.plot(xp, np.polyval(pp, xp), 'k--', x, y, 'o') if xlabel: plt.xlabel(xlabel) if ylabel: plt.ylabel(ylabel) return plt def periodic_table_heatmap(elemental_data, cbar_label="", show_plot=False, cmap="YlOrRd", blank_color="grey", value_format=None, max_row=9): """ A static method that generates a heat map overlapped on a periodic table. Args: elemental_data (dict): A dictionary with the element as a key and a value assigned to it, e.g. surface energy and frequency, etc. Elements missing in the elemental_data will be grey by default in the final table elemental_data={"Fe": 4.2, "O": 5.0}. cbar_label (string): Label of the colorbar. Default is "". figure_name (string): Name of the plot (absolute path) being saved if not None. show_plot (bool): Whether to show the heatmap. Default is False. value_format (str): Formatting string to show values. If None, no value is shown. Example: "%.4f" shows float to four decimals. cmap (string): Color scheme of the heatmap. Default is 'coolwarm'. blank_color (string): Color assigned for the missing elements in elemental_data. Default is "grey". max_row (integer): Maximum number of rows of the periodic table to be shown. Default is 9, which means the periodic table heat map covers the first 9 rows of elements. """ # Convert elemental data in the form of numpy array for plotting. max_val = max(elemental_data.values()) min_val = min(elemental_data.values()) max_row = min(max_row, 9) if max_row <= 0: raise ValueError("The input argument 'max_row' must be positive!") value_table = np.empty((max_row, 18)) * np.nan blank_value = min_val - 0.01 for el in Element: if el.row > max_row: continue value = elemental_data.get(el.symbol, blank_value) value_table[el.row - 1, el.group - 1] = value # Initialize the plt object import matplotlib.pyplot as plt fig, ax = plt.subplots() plt.gcf().set_size_inches(12, 8) # We set nan type values to masked values (ie blank spaces) data_mask = np.ma.masked_invalid(value_table.tolist()) heatmap = ax.pcolor(data_mask, cmap=cmap, edgecolors='w', linewidths=1, vmin=min_val-0.001, vmax=max_val+0.001) cbar = fig.colorbar(heatmap) # Grey out missing elements in input data cbar.cmap.set_under(blank_color) cbar.set_label(cbar_label, rotation=270, labelpad=15) cbar.ax.tick_params(labelsize=14) # Refine and make the table look nice ax.axis('off') ax.invert_yaxis() # Label each block with corresponding element and value for i, row in enumerate(value_table): for j, el in enumerate(row): if not np.isnan(el): symbol = Element.from_row_and_group(i+1, j+1).symbol plt.text(j + 0.5, i + 0.25, symbol, horizontalalignment='center', verticalalignment='center', fontsize=14) if el != blank_value and value_format is not None: plt.text(j + 0.5, i + 0.5, value_format % el, horizontalalignment='center', verticalalignment='center', fontsize=10) plt.tight_layout() if show_plot: plt.show() return plt def get_ax_fig_plt(ax=None): """ Helper function used in plot functions supporting an optional Axes argument. If ax is None, we build the `matplotlib` figure and create the Axes else we return the current active figure. Returns: ax: :class:`Axes` object figure: matplotlib figure plt: matplotlib pyplot module. """ import matplotlib.pyplot as plt if ax is None: fig = plt.figure() ax = fig.add_subplot(1, 1, 1) else: fig = plt.gcf() return ax, fig, plt def get_ax3d_fig_plt(ax=None): """ Helper function used in plot functions supporting an optional Axes3D argument. If ax is None, we build the `matplotlib` figure and create the Axes3D else we return the current active figure. Returns: ax: :class:`Axes` object figure: matplotlib figure plt: matplotlib pyplot module. """ import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d if ax is None: fig = plt.figure() ax = axes3d.Axes3D(fig) else: fig = plt.gcf() return ax, fig, plt def get_axarray_fig_plt(ax_array, nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw): """ Helper function used in plot functions that accept an optional array of Axes as argument. If ax_array is None, we build the `matplotlib` figure and create the array of Axes by calling plt.subplots else we return the current active figure. Returns: ax: Array of :class:`Axes` objects figure: matplotlib figure plt: matplotlib pyplot module. """ import matplotlib.pyplot as plt if ax_array is None: fig, ax_array = plt.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey, squeeze=squeeze, subplot_kw=subplot_kw, gridspec_kw=gridspec_kw, **fig_kw) else: fig = plt.gcf() if squeeze: ax_array = np.array(ax_array).ravel() if len(ax_array) == 1: ax_array = ax_array[1] return ax_array, fig, plt def add_fig_kwargs(func): """ Decorator that adds keyword arguments for functions returning matplotlib figures. The function should return either a matplotlib figure or None to signal some sort of error/unexpected event. See doc string below for the list of supported options. """ from functools import wraps @wraps(func) def wrapper(*args, **kwargs): # pop the kwds used by the decorator. title = kwargs.pop("title", None) size_kwargs = kwargs.pop("size_kwargs", None) show = kwargs.pop("show", True) savefig = kwargs.pop("savefig", None) tight_layout = kwargs.pop("tight_layout", False) # Call func and return immediately if None is returned. fig = func(*args, **kwargs) if fig is None: return fig # Operate on matplotlib figure. if title is not None: fig.suptitle(title) if size_kwargs is not None: fig.set_size_inches(size_kwargs.pop("w"), size_kwargs.pop("h"), **size_kwargs) if savefig: fig.savefig(savefig) if tight_layout: fig.tight_layout() if show: import matplotlib.pyplot as plt plt.show() return fig # Add docstring to the decorated method. s = "\n" + """\ keyword arguments controlling the display of the figure: ================ ==================================================== kwargs Meaning ================ ==================================================== title Title of the plot (Default: None). show True to show the figure (default: True). savefig 'abc.png' or 'abc.eps' to save the figure to a file. size_kwargs Dictionary with options passed to fig.set_size_inches example: size_kwargs=dict(w=3, h=4) tight_layout True to call fig.tight_layout (default: False) ================ ====================================================""" if wrapper.__doc__ is not None: # Add s at the end of the docstring. wrapper.__doc__ += "\n" + s else: # Use s wrapper.__doc__ = s return wrapper
setten/pymatgen
pymatgen/util/plotting.py
Python
mit
13,979
[ "pymatgen" ]
07f9068d4f0ef08dc6abfe01fa47d5a3903cd8bbe3fb2d48c0354d1b72dcde97
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= Principal components analysis (PCA) ========================================================= These figures aid in illustrating how a point cloud can be very flat in one direction--which is where PCA comes in to choose a direction that is not flat. """ # Authors: Gael Varoquaux # Jaques Grobler # Kevin Hughes # License: BSD 3 clause from sklearn.decomposition import PCA from scipy import stats import vtk import os import argparse import timeit import pickle import random from imblearn.over_sampling import SMOTE import matplotlib.pyplot as plt import pprint import inputData from sklearn.decomposition import PCA import math import inputData import glob import numpy as np # ############################################################################# # Generate data parser = argparse.ArgumentParser(description='Shape Variation Analyzer', formatter_class=argparse.ArgumentDefaultsHelpFormatter) #parser.add_argument('--model', type=str, help='pickle file with the pca decomposition', required=True) #parser.add_argument('--shapeDir', type=str, help='Directory with vtk files .vtk', required=True) parser.add_argument('--dataPath', action='store', dest='dirwithSub', help='folder with subclasses', required=True) parser.add_argument('--template', help='Sphere template, computed using SPHARM-PDM', type=str, required=True) parser.add_argument('--train_size', help='train ratio', type=float, default=0.8) parser.add_argument('--validation_size', help='validation ratio from test data', default=0.5, type=float) parser.add_argument('--out', dest="pickle_file", help='Pickle file output', default="datasets.pickle", type=str) def writeData(data_for_training,outputdataPath): #write data in a vtk file vtkdirshapes = os.listdir(outputdataPath) for vtkfilename in vtkdirshapes: if vtkfilename.endswith((".vtk")): print("Writing", vtkfilename) writer = vtk.vtkPolyDataWriter() writer.SetInput(data_for_training) writer.SetFileName(os.path.join(outputdataPath),vtkfilename) writer.Write() def get_conversion_matrices(geometry): points_to_cells = np.zeros((geometry.GetNumberOfCells(), geometry.GetNumberOfPoints())) for cid in range(geometry.GetNumberOfCells()): pointidlist = vtk.vtkIdList() geometry.GetCellPoints(cid, pointidlist) for pid in range(pointidlist.GetNumberOfIds()): points_to_cells[cid][pointidlist.GetId(pid)] = 1 cells_to_points = np.zeros((geometry.GetNumberOfPoints(), geometry.GetNumberOfCells())) for pid in range(geometry.GetNumberOfPoints()): pointidlist = vtk.vtkIdList() geometry.GetPointCells(pid, pointidlist) for cid in range(pointidlist.GetNumberOfIds()): cells_to_points[pid][pointidlist.GetId(cid)] = 1 return points_to_cells, cells_to_points def get_normals(vtkclassdict): inputdata = inputData.inputData() labels = [] dataset_concatenated = [] # This looks really confusing but is really not for folderclass, vtklist in vtkclassdict.items(): try: with open(folderclass + ".pickle",'rb') as f: dataset=pickle.load(f) normal_features = [] for vtkfilename in vtklist: #We'll load the same files and get the normals features = inputdata.load_features(vtkfilename, feature_points=["Normals"]) normal_features.append(features) #This reshaping stuff is to get the list of points, i.e., all connected points #and the corresponding label which is the normal in this case #The data in the dataset contains lists with different sizes normal_features = np.array(normal_features) featshape = np.shape(normal_features) labels.extend(normal_features.reshape(featshape[0], featshape[1], -1)) dsshape = np.shape(dataset) dataset_concatenated.extend(dataset.reshape(dsshape[0], dsshape[2], dsshape[3], -1)) except Exception as e: print('Unable to process', pickle_file,':',e) raise # lens = np.array([len(dataset_concatenated[i]) for i in range(len(dataset_concatenated))]) # mask = np.arange(lens.max()) < lens[:,None] # padded = np.zeros(mask.shape + (3,)) # padded[mask] = np.vstack((dataset_concatenated[:])) # return np.array(padded), np.array(labels) return np.array(dataset_concatenated), np.array(labels) def get_labels(pickle_file): #get labels of a dataset and returns the labels array and the dataset with features #num_classes=len(pickle_file) #num_shapes = 268 #should be changed!! labels = [] shape =[] dataset_concatenated =[] for label, pickle_file in enumerate(pickle_file): try: with open(pickle_file,'rb') as f: dataset=pickle.load(f) shape_dataset = np.shape(dataset) num_shapes_per_group = shape_dataset[0] l=[label]*num_shapes_per_group labels.extend(l) dataset_concatenated.extend(dataset) except Exception as e: print('Unable to process', pickle_file,':',e) raise features=np.array(dataset_concatenated) shape_features=np.shape(features) return features.reshape(-1,shape_features[1]*shape_features[2]), np.array(labels) def generate_data(pca_model): #generate data thanks to pca decomposition (not used) print("Generating data ...") pca = pca_model["pca"] X_ = pca_model["X_"] X_pca_ = pca_model["X_pca_"] X_pca_var = pca_model["X_pca_var"] print('Variance',X_pca_var) print('Mean',X_pca_) #between -1 and 1 alpha = 2.0*(np.random.random_sample(np.size(X_pca_))) - 1.0 print('alpha', alpha) data_compressed = 1.5*X_pca_var * alpha + X_pca_ print('data compressed',data_compressed) data_generated = pca.inverse_transform(data_compressed) + X_ return data_generated def generate_with_SMOTE(dataset,labels): #generate data thanks to SMOTE algorithm, it balances different groups sm=SMOTE(kind='regular') print('shape dataset',dataset.shape) print('shape labels',labels.shape) dataset_res, labels_res = sm.fit_sample(dataset,labels) print('shape dataset resampled',np.shape(dataset_res),'shape lables resampled',np.shape(labels_res)) return dataset_res,labels_res def PCA_plot(dataset,labels,dataset_res,labels_res): #plot original dat and data resampled after a PCA decomposition pca = PCA(n_components=200) pca.fit(dataset) dataset_pca=pca.transform(dataset) print('original shape: ',dataset.shape) print('transformed shape:',dataset_pca.shape) #print('Ratio variance',pca.explained_variance_ratio_) #plt.scatter(dataset[:,0],dataset[:,1],alpha=0.2) #dataset_new = pca.inverse_transform(dataset_pca) plt.figure(2) plt.subplot(121) plt.scatter(dataset_pca[:,0],dataset_pca[:,1],edgecolor='none',alpha=0.5,c=labels,cmap=plt.cm.get_cmap('nipy_spectral',np.shape(np.unique(labels))[0])) plt.title('Original data with pca (' + str(dataset.shape[0]) + ' samples)') #pca.fit(dataset_res) dataset_res_pca=pca.transform(dataset_res) plt.subplot(122) plt.scatter(dataset_res_pca[:,0],dataset_res_pca[:,1],edgecolor='none',alpha=0.5,c=labels_res,cmap=plt.cm.get_cmap('nipy_spectral',np.shape(np.unique(labels_res))[0])) plt.title('Resampled data with pca (' + str(dataset_res_pca.shape[0]) + ' samples)') for i in range(1,3): plt.subplot(1,2,i) plt.xlabel('component 1') plt.ylabel('component 2') plt.colorbar() cumsum = np.cumsum(pca.explained_variance_ratio_) plt.figure(1) plt.plot(cumsum) plt.xlabel('nb of components') plt.ylabel('cumulative explained variance') plt.axhline(y=0.95, linestyle=':', label='.95 explained', color="#f23e3e") numcomponents = len(np.where(cumsum < 0.95)[0]) plt.axvline(x=numcomponents, linestyle=':', label=(str(numcomponents) + ' components'), color="#31f9ad") plt.legend(loc=0) histo = np.bincount(labels) histo_range = np.array(range(histo.shape[0])) plt.figure(3) plt.bar(histo_range, histo) plt.xlabel('Groups') plt.ylabel('Number of samples') for xy in zip(histo_range, histo): plt.annotate(xy[1], xy=xy, ha="center", color="#4286f4") plt.show() if __name__ == '__main__': np.set_printoptions(threshold='nan') args = parser.parse_args() dataPath=args.dirwithSub pickle_file = args.pickle_file template = args.template reader = vtk.vtkPolyDataReader() reader.SetFileName(template) reader.Update() points_to_cells, cells_to_points = get_conversion_matrices(reader.GetOutput()) # Get the data from the folders with vtk files inputdata = inputData.inputData() data_folders = inputdata.get_folder_classes_list(dataPath) pickled_datasets = inputdata.maybe_pickle(data_folders, 5, feature_polys=["Points"]) # Create the labels, i.e., enumerate the groups vtklistdict = inputdata.get_vtklist(data_folders) dataset,labels = get_normals(vtklistdict) # Comput the total number of shapes and train/test size total_number_shapes=dataset.shape[0] num_train = int(args.train_size*total_number_shapes) num_valid = int((total_number_shapes - num_train)*args.validation_size) # Randomize the original dataset shuffled_dataset, shuffled_labels = inputdata.randomize(dataset, labels) dataset_res = shuffled_dataset labels_res = shuffled_labels # SANITY CHECKS print('dataset',np.shape(dataset)) print('labels',np.shape(labels)) print('dataset_res',np.shape(dataset_res)) print('labels_res',np.shape(labels_res)) print('num_train', num_train) print('num_valid', num_valid) print('num_test', total_number_shapes - num_valid - num_train) print("points_to_cells", np.shape(points_to_cells)) print("cells_to_points", np.shape(cells_to_points)) # PCA_plot(dataset,labels,dataset_res,labels_res) try: f = open(pickle_file, 'wb') save = { 'train_dataset': dataset_res, 'train_labels': labels_res, 'valid_dataset': dataset[num_train: num_train + num_valid], 'valid_labels': labels[num_train: num_train + num_valid], 'test_dataset': dataset[num_train + num_valid:], 'test_labels': labels[num_train + num_valid:], 'points_to_cells': points_to_cells, 'cells_to_points': cells_to_points } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) #f.close() except Exception as e: print('Unable to save data to', pickle_file, ':', e) raise
pdedumast/ShapeVariationAnalyzer
src/py/generatelib/generate_polys.py
Python
apache-2.0
10,177
[ "VTK" ]
899c81511cfe1cea870bd9e34684c3c702caf02c4df2d87b8d9bf47a977779d0
from electrum.util import print_error import httplib, urllib import socket import threading import hashlib import json from urlparse import urlparse, parse_qs try: import PyQt4 except Exception: sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'") from PyQt4.QtGui import * from PyQt4.QtCore import * import PyQt4.QtCore as QtCore import PyQt4.QtGui as QtGui import aes import base64 import electrum from electrum.plugins import BasePlugin, hook from electrum.i18n import _ from electrum_gui.qt import HelpButton, EnterButton class Plugin(BasePlugin): target_host = 'labelectrum.herokuapp.com' encode_password = None def fullname(self): return _('Label Sync') def description(self): return '%s\n\n%s%s%s' % (_("This plugin can sync your labels across multiple Electrum installs by using a remote database to save your data. Labels, transactions ids and addresses are encrypted before they are sent to the remote server. This code might increase the load of your wallet with a few microseconds as it will sync labels on each startup."), _("To get started visit"), " http://labelectrum.herokuapp.com/ ", _(" to sign up for an account.")) def version(self): return "0.2.1" def encode(self, message): encrypted = electrum.bitcoin.aes_encrypt_with_iv(self.encode_password, self.iv, message.encode('utf8')) encoded_message = base64.b64encode(encrypted) return encoded_message def decode(self, message): decoded_message = electrum.bitcoin.aes_decrypt_with_iv(self.encode_password, self.iv, base64.b64decode(message)).decode('utf8') return decoded_message @hook def init_qt(self, gui): self.window = gui.main_window if not self.auth_token(): # First run, throw plugin settings in your face self.load_wallet(self.window.wallet) if self.settings_dialog(): self.set_enabled(True) return True else: self.set_enabled(False) return False @hook def load_wallet(self, wallet): self.wallet = wallet mpk = ''.join(sorted(self.wallet.get_master_public_keys().values())) self.encode_password = hashlib.sha1(mpk).digest().encode('hex')[:32] self.iv = hashlib.sha256(self.encode_password).digest()[:16] self.wallet_id = hashlib.sha256(mpk).digest().encode('hex') addresses = [] for account in self.wallet.accounts.values(): for address in account.get_addresses(0): addresses.append(address) self.addresses = addresses if self.auth_token(): # If there is an auth token we can try to actually start syncing threading.Thread(target=self.do_full_pull).start() def auth_token(self): return self.config.get("plugin_label_api_key") def is_available(self): return True def requires_settings(self): return True @hook def set_label(self, item,label, changed): if self.encode_password is None: return if not changed: return try: bundle = {"label": {"external_id": self.encode(item), "text": self.encode(label)}} params = json.dumps(bundle) connection = httplib.HTTPConnection(self.target_host) connection.request("POST", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'}) response = connection.getresponse() if response.reason == httplib.responses[httplib.NOT_FOUND]: return response = json.loads(response.read()) except socket.gaierror as e: print_error('Error connecting to service: %s ' % e) return False def settings_widget(self, window): return EnterButton(_('Settings'), self.settings_dialog) def settings_dialog(self): def check_for_api_key(api_key): if api_key and len(api_key) > 12: self.config.set_key("plugin_label_api_key", str(self.auth_token_edit.text())) self.upload.setEnabled(True) self.download.setEnabled(True) self.accept.setEnabled(True) else: self.upload.setEnabled(False) self.download.setEnabled(False) self.accept.setEnabled(False) d = QDialog() layout = QGridLayout(d) layout.addWidget(QLabel("API Key: "),0,0) self.auth_token_edit = QLineEdit(self.auth_token()) self.auth_token_edit.textChanged.connect(check_for_api_key) layout.addWidget(QLabel("Label sync options: "),2,0) layout.addWidget(self.auth_token_edit, 0,1,1,2) decrypt_key_text = QLineEdit(self.encode_password) decrypt_key_text.setReadOnly(True) layout.addWidget(decrypt_key_text, 1,1) layout.addWidget(QLabel("Decryption key: "),1,0) layout.addWidget(HelpButton("This key can be used on the LabElectrum website to decrypt your data in case you want to review it online."),1,2) self.upload = QPushButton("Force upload") self.upload.clicked.connect(self.full_push) layout.addWidget(self.upload, 2,1) self.download = QPushButton("Force download") self.download.clicked.connect(self.full_pull) layout.addWidget(self.download, 2,2) c = QPushButton(_("Cancel")) c.clicked.connect(d.reject) self.accept = QPushButton(_("Done")) self.accept.clicked.connect(d.accept) layout.addWidget(c,3,1) layout.addWidget(self.accept,3,2) check_for_api_key(self.auth_token()) self.window.labelsChanged.connect(self.done_processing) if d.exec_(): return True else: return False def done_processing(self): QMessageBox.information(None, _("Labels synchronised"), _("Your labels have been synchronised.")) def full_push(self): threading.Thread(target=self.do_full_push).start() def full_pull(self): threading.Thread(target=self.do_full_pull, args=([True])).start() def do_full_push(self): try: bundle = {"labels": {}} for key, value in self.wallet.labels.iteritems(): try: encoded_key = self.encode(key) except: print_error('cannot encode', repr(key)) continue try: encoded_value = self.encode(value) except: print_error('cannot encode', repr(value)) continue bundle["labels"][encoded_key] = encoded_value params = json.dumps(bundle) connection = httplib.HTTPConnection(self.target_host) connection.request("POST", ("/api/wallets/%s/labels/batch.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'}) response = connection.getresponse() if response.reason == httplib.responses[httplib.NOT_FOUND]: print_error('404 error' % e) return try: response = json.loads(response.read()) except ValueError as e: print_error('Error loading labelsync response: %s' % e) return False if "error" in response: print_error('Error loading labelsync response.') return False except socket.gaierror as e: print_error('Error connecting to service: %s ' % e) return False self.window.labelsChanged.emit() def do_full_pull(self, force = False): connection = httplib.HTTPConnection(self.target_host) connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())),"", {'Content-Type': 'application/json'}) response = connection.getresponse() if response.status != 200: print_error("Cannot retrieve labels:", response.status, response.reason) return response = json.loads(response.read()) if "error" in response: raise BaseException(_("Could not sync labels: %s" % response["error"])) result = {} for label in response: try: key = self.decode(label["external_id"]) except: continue try: value = self.decode(label["text"]) except: continue try: json.dumps(key) json.dumps(value) except: print_error('error: no json', key) continue result[key] = value wallet = self.wallet if not wallet: return for key, value in result.items(): if force or not wallet.labels.get(key): wallet.labels[key] = value wallet.storage.put('labels', wallet.labels) print_error("received %d labels"%len(response)) self.window.labelsChanged.emit()
spasmilo/electrum
plugins/labels.py
Python
gpl-3.0
9,305
[ "VisIt" ]
4e14891190813e5c1fb8a75d686b70f3c71c9b3aa16d431f021a38e1d574fcba
import data from galaxy import util from galaxy.datatypes.sniff import * from galaxy.web import url_for from tabular import Tabular from galaxy.datatypes import metadata from galaxy.datatypes.metadata import MetadataElement class ChromInfo( Tabular ): file_ext = "len" MetadataElement( name="chrom", default=1, desc="Chrom column", param=metadata.ColumnParameter ) MetadataElement( name="length", default=2, desc="Length column", param=metadata.ColumnParameter )
dbcls/dbcls-galaxy
lib/galaxy/datatypes/chrominfo.py
Python
mit
482
[ "Galaxy" ]
16241ebea06226af2112389dcddc79cbdc3fdb124ed664e3f0d079966cbb63eb
#!/usr/bin/env python # -*- coding: utf-8 -*- """Example script for calculations inside the nc2map module This script is part of the nc2map Python module, version 0.0b. It shall introduce you into the data management within the nc2map module and show you how per efficiently perform arithmetics and visualization at the same time. Within this script, we will calculate the absolute wind speed in two different ways. It produces a NetCDF file calculation-demo.nc and a plot calculation-demo.pdf. It requires the NetCDF file 'demo-t2m-u-v.nc' which you can find in the nc2map/demo directory""" import nc2map import os ncfile = 'demo-t2m-u-v.nc' output = 'calculation-demo.pdf' output_nc = 'calculation-demo.nc' # open nc2map.Maps instance mymaps = nc2map.Maps(ncfile, vlst=['u', 'v'], ax=(1,2), fmt={'clabel': '%(long_name)s [%(units)s]'}) # get the MapBase instance with zonal wind velocity mapo_u = mymaps.get_maps(var='u')[0] mapo_v = mymaps.get_maps(var='v')[0] # calculate the speed. The return is again a MapBase instance with the # formatoptions of mapo_u. It will plot into a new subplot. mapo_speed = (mapo_u*mapo_u + mapo_v*mapo_v)**0.5 # add it to the current Maps instance (to change the meta information, look # at the end of the script) mymaps.addmap(mapo_speed) # save the plots into a pdf pdf = mymaps.output(output, returnpdf=True) # However, the calculation with MapBase instances will always only consider the # specific level, time, etc. that are shown by the MapBase instance. Hence if # you now try # >>> mymaps.update(maps=mapo_speed, fmt={'time': 1}) # you will get an IndexError. This is behaviour is very efficient if you have # large datasets. However, if you want to consider all the data, we have to # go one level deeper, to the reader level reader = mapo_u.reader # a reader (an instance of the nc2map.readers.ArrayReaderBase) is the # representation of the NetCDF file in the nc2map module. It has essentially # the same structure as the netCDF4.Dataset class (in fact, it uses this # class). All the meta data is stored in this reader. # To calculate the wind speed for all times and levels, we can extract the # specific variable and calculate as we did above speed_reader = (reader.selname('u')**2 + reader.selname('v')**2)**0.5 # if you want to be more specific on the times and levels, use the # ArrayReaderBase.extract method in place of the selname method # The new variable contains all meta informations of the 'u' variable in the # old reader. We rename the variable name in the speed reader speed_reader.renameVariable('u', 'speed') # and change the global meta information speed_reader.set_meta(history='Calculated speed with nc2map module') # and the local long_name attribute of the 'speed' variable speed_reader.set_meta('speed', long_name='Absolute wind speed') # now we can add a new MapBase instance to our Maps mymaps.addmap(speed_reader, vlst='speed', fmt={ 'clabel': '%(long_name)s [%(units)s]', 'title': 'New mapo with full reader'}) # save the figure mymaps.output(pdf, var='speed') # and why not merge the new variable with the existing NetCDF file and save it speed_reader.merge(reader).dump_nc(output_nc, compression=4) # NOTE: In the first calculation when creating the mapo_speed MapBase # instance, we did not change any meta information, it contains everything # from the reader and the 'u' variable. # Here is how you can do it mapo_speed.reader.renameVariable('u', 'speed') mapo_speed.reader.set_meta('speed', long_name='Absolute wind speed') mapo_speed.var = 'speed' mapo_speed.update() #mymaps.close()
Chilipp/nc2map
demo/calculation_demo.py
Python
gpl-2.0
3,608
[ "NetCDF" ]
72c2fc056723c7ec7198ff159306c4795d8d4ca577ddfaeb5e0907e9325ac5f4
"""K-means clustering with weights""" __author__ = 'sylvain' import warnings import numpy as np import scipy.sparse as sp # from sklearn.base import BaseEstimator, ClusterMixin, TransformerMixin from sklearn.metrics.pairwise import euclidean_distances from sklearn.utils.extmath import row_norms, squared_norm # from sklearn.utils.sparsefuncs_fast import assign_rows_csr from sklearn.utils.sparsefuncs import mean_variance_axis # from sklearn.utils.fixes import astype from sklearn.utils import check_array from sklearn.utils import check_random_state from sklearn.utils import as_float_array # from sklearn.utils import gen_batches from sklearn.utils.validation import check_is_fitted from sklearn.utils.validation import FLOAT_DTYPES # from sklearn.utils.random import choice from joblib import Parallel from joblib import delayed from six import string_types import sys if sys.version_info >= (3, 5): from sklearn.cluster import _k_means_fast as _k_means else: from sklearn.cluster import _k_means ############################################################################### # Initialization heuristic def _k_init_with_weights(X, weights, n_clusters, x_squared_norms, random_state, n_local_trials=None): """Init n_clusters seeds according to k-means++, using weights Parameters ----------- X: array or sparse matrix, shape (n_samples, n_features) The data to pick seeds for. To avoid memory copy, the input data should be double precision (dtype=np.float64). n_clusters: integer The number of seeds to choose weights: array of weights x_squared_norms: array, shape (n_samples,) Squared Euclidean norm of each data point. random_state: numpy.RandomState The generator used to initialize the centers. n_local_trials: integer, optional The number of seeding trials for each center (except the first), of which the one reducing inertia the most is greedily chosen. Set to None to make the number of trials depend logarithmically on the number of seeds (2+log(k)); this is the default. Notes ----- Selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. see: Arthur, D. and Vassilvitskii, S. "k-means++: the advantages of careful seeding". ACM-SIAM symposium on Discrete algorithms. 2007 Version modified to include weights. """ n_samples, n_features = X.shape centers = np.empty((n_clusters, n_features)) assert x_squared_norms is not None, 'x_squared_norms None in _k_init_with_weights' # Set the number of local seeding trials if none is given if n_local_trials is None: # This is what Arthur/Vassilvitskii tried, but did not report # specific results for other than mentioning in the conclusion # that it helped. n_local_trials = 2 + int(np.log(n_clusters)) # Pick first center randomly #####should use the weights here too center_id = np.random.randint(n_samples) if sp.issparse(X): centers[0] = X[center_id].toarray() else: centers[0] = X[center_id] # Initialize list of closest distances and calculate current potential closest_dist_sq = euclidean_distances( centers[0, np.newaxis], X, Y_norm_squared=x_squared_norms, squared=True) closest_dist_sq_weighted = closest_dist_sq * weights ##check if dimensions agree current_pot_weighted = closest_dist_sq_weighted.sum() # Pick the remaining n_clusters-1 points for c in range(1, n_clusters): # Choose center candidates by sampling with probability proportional # to the squared distance to the closest existing center rand_vals = np.random.random_sample(n_local_trials) * current_pot_weighted candidate_ids = np.searchsorted(closest_dist_sq_weighted.cumsum(), rand_vals) # Compute distances to center candidates distance_to_candidates = euclidean_distances( X[candidate_ids], X, Y_norm_squared=x_squared_norms, squared=True) # here we use the true distances distance_to_candidates_weighted = distance_to_candidates * weights ##check syntax # Decide which candidate is the best best_candidate = None best_pot_weighted = None best_dist_sq = None for trial in range(n_local_trials): # Compute potential when including center candidate new_dist_sq = np.minimum(closest_dist_sq, distance_to_candidates[trial]) ###check here too # new_pot = new_dist_sq.sum() new_pot_weighted = (new_dist_sq * weights).sum() # Store result if it is the best local trial so far if (best_candidate is None) or (new_pot_weighted < best_pot_weighted): best_candidate = candidate_ids[trial] best_pot_weighted = new_pot_weighted best_dist_sq = new_dist_sq # Permanently add best center candidate found in local tries if sp.issparse(X): centers[c] = X[best_candidate].toarray() else: centers[c] = X[best_candidate] current_pot_weighted = best_pot_weighted closest_dist_sq = best_dist_sq ##include here also the updating of the weights return centers ############################################################################### # K-means batch estimation by EM (expectation maximization) def _validate_center_shape(X, n_centers, centers): """Check if centers is compatible with X and n_centers""" if len(centers) != n_centers: raise ValueError('The shape of the initial centers (%s) ' 'does not match the number of clusters %i' % (centers.shape, n_centers)) if centers.shape[1] != X.shape[1]: raise ValueError( "The number of features of the initial centers %s " "does not match the number of features of the data %s." % (centers.shape[1], X.shape[1])) def _tolerance(X, tol): """Return a tolerance which is independent of the dataset""" if sp.issparse(X): variances = mean_variance_axis(X, axis=0)[1] else: variances = np.var(X, axis=0) return np.mean(variances) * tol def _labels_inertia_precompute_dense(X, x_squared_norms, centers, distances): """Compute labels and inertia using a full distance matrix. This will overwrite the 'distances' array in-place. Parameters ---------- X : numpy array, shape (n_sample, n_features) Input data. x_squared_norms : numpy array, shape (n_samples,) Precomputed squared norms of X. centers : numpy array, shape (n_clusters, n_features) Cluster centers which data is assigned to. distances : numpy array, shape (n_samples,) Pre-allocated array in which distances are stored. Returns ------- labels : numpy array, dtype=np.int, shape (n_samples,) Indices of clusters that samples are assigned to. inertia : float Sum of distances of samples to their closest cluster center. """ n_samples = X.shape[0] k = centers.shape[0] all_distances = euclidean_distances(centers, X, x_squared_norms, squared=True) labels = np.empty(n_samples, dtype=np.int32) labels.fill(-1) mindist = np.empty(n_samples) mindist.fill(np.infty) for center_id in range(k): dist = all_distances[center_id] labels[dist < mindist] = center_id mindist = np.minimum(dist, mindist) if n_samples == distances.shape[0]: # distances will be changed in-place distances[:] = mindist inertia = mindist.sum() return labels, inertia def _labels_inertia(X, x_squared_norms, centers, precompute_distances=True, distances=None): """E step of the K-means EM algorithm. Compute the labels and the inertia of the given samples and centers. This will compute the distances in-place. Parameters ---------- X: float64 array-like or CSR sparse matrix, shape (n_samples, n_features) The input samples to assign to the labels. x_squared_norms: array, shape (n_samples,) Precomputed squared euclidean norm of each data point, to speed up computations. centers: float64 array, shape (k, n_features) The cluster centers. precompute_distances : boolean, default: True Precompute distances (faster but takes more memory). distances: float64 array, shape (n_samples,) Pre-allocated array to be filled in with each sample's distance to the closest center. Returns ------- labels: int array of shape(n) The resulting assignment inertia : float Sum of distances of samples to their closest cluster center. """ n_samples = X.shape[0] # set the default value of centers to -1 to be able to detect any anomaly # easily labels = -np.ones(n_samples, np.int32) if distances is None: distances = np.zeros(shape=(0,), dtype=np.float64) # distances will be changed in-place if sp.issparse(X): inertia = _k_means._assign_labels_csr( X, x_squared_norms, centers, labels, distances=distances) else: if precompute_distances: return _labels_inertia_precompute_dense(X, x_squared_norms, centers, distances) inertia = _k_means._assign_labels_array( X, x_squared_norms, centers, labels, distances=distances) return labels, inertia def _init_centroids_with_weights(X, weights, k, init, random_state=None, x_squared_norms=None, init_size=None): """Compute the initial centroids Parameters ---------- X: array, shape (n_samples, n_features) weights: array, shape (n_samples) k: int number of centroids init: {'k-means++_with_weights', 'random' or ndarray or callable} optional Method for initialization random_state: integer or numpy.RandomState, optional The generator used to initialize the centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. x_squared_norms: array, shape (n_samples,), optional Squared euclidean norm of each data point. Pass it if you have it at hands already to avoid it being recomputed here. Default: None init_size : int, optional Number of samples to randomly sample for speeding up the initialization (sometimes at the expense of accuracy): the only algorithm is initialized by running a batch KMeans on a random subset of the data. This needs to be larger than k. Returns ------- centers: array, shape(k, n_features) """ random_state = check_random_state(random_state) # will use np.random everywhere n_samples = X.shape[0] if x_squared_norms is None: x_squared_norms = row_norms(X, squared=True) if init_size is not None and init_size < n_samples: if init_size < k: warnings.warn( "init_size=%d should be larger than k=%d. " "Setting it to 3*k" % (init_size, k), RuntimeWarning, stacklevel=2) init_size = 3 * k init_indices = np.random.random_integers( 0, n_samples - 1, init_size) X = X[init_indices] x_squared_norms = x_squared_norms[init_indices] n_samples = X.shape[0] elif n_samples < k: raise ValueError( "n_samples=%d should be larger than k=%d" % (n_samples, k)) if isinstance(init, string_types) and init == 'kmeans++_with_weights': centers = _k_init_with_weights(X, weights, k, random_state=random_state, x_squared_norms=x_squared_norms) elif isinstance(init, string_types) and init == 'random': seeds = np.random.permutation(n_samples)[:k] centers = X[seeds] elif hasattr(init, '__array__'): centers = init elif callable(init): centers = init(X, k, random_state=random_state) else: raise ValueError("the init parameter for the k-means should " "be 'kmeans++_with_weights' or 'random' or an ndarray, " "'%s' (type '%s') was passed." % (init, type(init))) if sp.issparse(centers): centers = centers.toarray() _validate_center_shape(X, k, centers) return centers def _kmeans_single_with_weights(X, weights, n_clusters, x_squared_norms, max_iter=300, init='kmeans++_with_weights', verbose=False, random_state=None, tol=1e-4, precompute_distances=True): """A single run of k-means with weights, assumes preparation completed prior. Parameters ---------- X: array-like of floats, shape (n_samples, n_features) The observations to cluster. n_clusters: int The number of clusters to form as well as the number of centroids to generate. weights: array, shape (n_samples) max_iter: int, optional, default 300 Maximum number of iterations of the k-means algorithm to run. init: {'kmeans++_with_weights', 'random', or ndarray, or a callable}, optional Method for initialization, default to 'k-means++': 'kmeans++_with_weights' : selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init_with_weights for more details. 'random': generate k centroids from a Gaussian with mean and variance estimated from the data. If an ndarray is passed, it should be of shape (k, p) and gives the initial centers. If a callable is passed, it should take arguments X, k and and a random state and return an initialization. tol: float, optional The relative increment in the results before declaring convergence. verbose: boolean, optional Verbosity mode x_squared_norms: array Precomputed x_squared_norms. precompute_distances : boolean, default: True Precompute distances (faster but takes more memory). random_state: integer or numpy.RandomState, optional The generator used to initialize the centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. Returns ------- centroid: float ndarray with shape (k, n_features) Centroids found at the last iteration of k-means. label: integer ndarray with shape (n_samples,) label[i] is the code or index of the centroid the i'th observation is closest to. weighted inertia: float The final value of the inertia criterion (weighted sum of squared distances to the closest centroid for all observations in the training set). n_iter : int Number of iterations run. """ # random_state = check_random_state(random_state) ####remove this best_labels, best_inertia, best_centers = None, None, None # init centers = _init_centroids_with_weights(X, weights, n_clusters, init, random_state=random_state, x_squared_norms=x_squared_norms) if verbose: print("Initialization complete") # Allocate memory to store the distances for each sample to its # closer center for reallocation in case of ties distances = np.zeros(shape=(X.shape[0],), dtype=np.float64) # iterations for i in range(max_iter): centers_old = centers.copy() # labels assignment is also called the E-step of EM labels, _ = \ _labels_inertia(X, x_squared_norms, centers, precompute_distances=precompute_distances, distances=distances) # computation of the means is also called the M-step of EM # if sp.issparse(X): # centers = _k_means._centers_sparse(X, labels, n_clusters, # distances) # else: # centers = _k_means._centers_dense(X, labels, n_clusters, distances) # computation of the weighted means is also called the M-step of EM ##Check this!!# weights_clusters = np.zeros(n_clusters) for i in range(len(X)): weights_clusters[labels[i]] += weights[i] n_samples_in_cluster = np.bincount(labels, minlength=n_clusters) if sp.issparse(X): centers = _k_means._centers_sparse(np.multiply(X, weights.reshape(len(weights), 1)), labels, n_clusters, distances) else: centers = _k_means._centers_dense(np.multiply(X, weights.reshape(len(weights), 1)), labels, n_clusters, distances) weights_clusters = np.zeros(n_clusters) for i in range(len(X)): weights_clusters[labels[i]] += weights[i] weights_clusters[weights_clusters == 0] = 1 n_samples_in_cluster = np.bincount(labels, minlength=n_clusters) centers /= weights_clusters[:, np.newaxis] centers *= n_samples_in_cluster[:, np.newaxis] # weighted inertia is computed here centers_labelled = centers[labels] row_norms_diff = row_norms(X - centers_labelled, squared=True)[np.newaxis, :] inertia = np.sum(weights * row_norms_diff) if verbose: print(("Iteration %2d, inertia %.3f" % (i, inertia))) if best_inertia is None or inertia < best_inertia: best_labels = labels.copy() best_centers = centers.copy() best_inertia = inertia shift = squared_norm(centers_old - centers) if shift <= tol: if verbose: print(("Converged at iteration %d" % i)) break if shift > 0: # rerun E-step in case of non-convergence so that predicted labels # match cluster centers best_labels, _ = \ _labels_inertia(X, x_squared_norms, best_centers, precompute_distances=precompute_distances, distances=distances) # weighted best_inertia is computed here best_centers_labelled = best_centers[best_labels] best_row_norms_diff = row_norms(X - best_centers_labelled, squared=True)[np.newaxis, :] best_inertia = np.sum(weights * best_row_norms_diff) return best_labels, best_inertia, best_centers, i + 1 ############without weights, just to compare, with some print statements within ###### def _k_init(X, n_clusters, x_squared_norms, random_state, n_local_trials=None): """Init n_clusters seeds according to k-means++ Parameters ----------- X: array or sparse matrix, shape (n_samples, n_features) The data to pick seeds for. To avoid memory copy, the input data should be double precision (dtype=np.float64). n_clusters: integer The number of seeds to choose x_squared_norms: array, shape (n_samples,) Squared Euclidean norm of each data point. random_state: numpy.RandomState The generator used to initialize the centers. n_local_trials: integer, optional The number of seeding trials for each center (except the first), of which the one reducing inertia the most is greedily chosen. Set to None to make the number of trials depend logarithmically on the number of seeds (2+log(k)); this is the default. Notes ----- Selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. see: Arthur, D. and Vassilvitskii, S. "k-means++: the advantages of careful seeding". ACM-SIAM symposium on Discrete algorithms. 2007 Version ported from http://www.stanford.edu/~darthur/kMeansppTest.zip, which is the implementation used in the aforementioned paper. """ n_samples, n_features = X.shape centers = np.empty((n_clusters, n_features)) assert x_squared_norms is not None, 'x_squared_norms None in _k_init' # Set the number of local seeding trials if none is given if n_local_trials is None: # This is what Arthur/Vassilvitskii tried, but did not report # specific results for other than mentioning in the conclusion # that it helped. n_local_trials = 2 + int(np.log(n_clusters)) # Pick first center randomly center_id = np.random.randint(n_samples) if sp.issparse(X): centers[0] = X[center_id].toarray() else: centers[0] = X[center_id] # print 'initial center id= ', center_id # Initialize list of closest distances and calculate current potential closest_dist_sq = euclidean_distances( centers[0, np.newaxis], X, Y_norm_squared=x_squared_norms, squared=True) # print 'closest_dist_sq = ' current_pot = closest_dist_sq.sum() # print 'current_pot=' # Pick the remaining n_clusters-1 points for c in range(1, n_clusters): # Choose center candidates by sampling with probability proportional # to the squared distance to the closest existing center rand_vals = np.random.random_sample(n_local_trials) * current_pot # print 'rand_vals', rand_vals candidate_ids = np.searchsorted(closest_dist_sq.cumsum(), rand_vals) # print 'candidate ids=', candidate_ids # Compute distances to center candidates distance_to_candidates = euclidean_distances( X[candidate_ids], X, Y_norm_squared=x_squared_norms, squared=True) # print 'distance to candidates', distance_to_candidates # Decide which candidate is the best best_candidate = None best_pot = None best_dist_sq = None for trial in range(n_local_trials): # Compute potential when including center candidate new_dist_sq = np.minimum(closest_dist_sq, distance_to_candidates[trial]) new_pot = new_dist_sq.sum() # Store result if it is the best local trial so far if (best_candidate is None) or (new_pot < best_pot): best_candidate = candidate_ids[trial] best_pot = new_pot best_dist_sq = new_dist_sq # Permanently add best center candidate found in local tries if sp.issparse(X): centers[c] = X[best_candidate].toarray() else: centers[c] = X[best_candidate] current_pot = best_pot closest_dist_sq = best_dist_sq return centers #########kmeans with weights########### def k_means_with_weights(X, weights, n_clusters, init='kmeans++_with_weights', precompute_distances='auto', n_init=10, max_iter=300, verbose=False, tol=1e-4, random_state=None, copy_x=True, n_jobs=1, return_n_iter=False): """K-means clustering algorithm with weights. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The observations to cluster. n_clusters : int The number of clusters to form as well as the number of centroids to generate. weights : array of weights, shape (n_samples) max_iter : int, optional, default 300 Maximum number of iterations of the k-means algorithm to run. n_init : int, optional, default: 10 Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia. init : {'kmeans++_with_weights', 'random', or ndarray, or a callable}, optional Method for initialization, default to 'k-means++_with_weights': 'k-means++_with_weights' : selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. 'random': generate k centroids from a Gaussian with mean and variance estimated from the data. If an ndarray is passed, it should be of shape (n_clusters, n_features) and gives the initial centers. If a callable is passed, it should take arguments X, k and and a random state and return an initialization. precompute_distances : {'auto', True, False} Precompute distances (faster but takes more memory). 'auto' : do not precompute distances if n_samples * n_clusters > 12 million. This corresponds to about 100MB overhead per job using double precision. True : always precompute distances False : never precompute distances tol : float, optional The relative increment in the results before declaring convergence. verbose : boolean, optional Verbosity mode. random_state : integer or numpy.RandomState, optional The generator used to initialize the centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. copy_x : boolean, optional When pre-computing distances it is more numerically accurate to center the data first. If copy_x is True, then the original data is not modified. If False, the original data is modified, and put back before the function returns, but small numerical differences may be introduced by subtracting and then adding the data mean. n_jobs : int The number of jobs to use for the computation. This works by computing each of the n_init runs in parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. return_n_iter : bool, optional Whether or not to return the number of iterations. Returns ------- centroid : float ndarray with shape (k, n_features) Centroids found at the last iteration of k-means_with_weights. label : integer ndarray with shape (n_samples,) label[i] is the code or index of the centroid the i'th observation is closest to. inertia : float The final value of the inertia criterion (weighted sum of squared distances to the closest centroid for all observations in the training set). best_n_iter: int Number of iterations corresponding to the best results. Returned only if `return_n_iter` is set to True. """ if n_init <= 0: raise ValueError("Invalid number of initializations." " n_init=%d must be bigger than zero." % n_init) # random_state = check_random_state(random_state) if max_iter <= 0: raise ValueError('Number of iterations should be a positive number,' ' got %d instead' % max_iter) best_inertia = np.infty X = as_float_array(X, copy=copy_x) tol = _tolerance(X, tol) # If the distances are precomputed every job will create a matrix of shape # (n_clusters, n_samples). To stop KMeans from eating up memory we only # activate this if the created matrix is guaranteed to be under 100MB. 12 # million entries consume a little under 100MB if they are of type double. if precompute_distances == 'auto': n_samples = X.shape[0] precompute_distances = (n_clusters * n_samples) < 12e6 elif isinstance(precompute_distances, bool): pass else: raise ValueError("precompute_distances should be 'auto' or True/False" ", but a value of %r was passed" % precompute_distances) # subtract of mean of x for more accurate distance computations if not sp.issparse(X) or hasattr(init, '__array__'): X_mean = X.mean(axis=0) # what about weighted means here? if not sp.issparse(X): # The copy was already done above X -= X_mean if hasattr(init, '__array__'): init = check_array(init, dtype=np.float64, copy=True) _validate_center_shape(X, n_clusters, init) init -= X_mean if n_init != 1: warnings.warn( 'Explicit initial center position passed: ' 'performing only one init in k-means instead of n_init=%d' % n_init, RuntimeWarning, stacklevel=2) n_init = 1 # precompute squared norms of data points x_squared_norms = row_norms(X, squared=True) best_labels, best_inertia, best_centers = None, None, None if n_jobs == 1: # For a single thread, less memory is needed if we just store one set # of the best results (as opposed to one set per run per thread). for it in range(n_init): # run a k-means once labels, inertia, centers, n_iter_ = _kmeans_single_with_weights( X, weights, n_clusters, max_iter=max_iter, init=init, verbose=verbose, precompute_distances=precompute_distances, tol=tol, x_squared_norms=x_squared_norms, random_state=random_state) # determine if these results are the best so far if best_inertia is None or inertia < best_inertia: best_labels = labels.copy() best_centers = centers.copy() best_inertia = inertia best_n_iter = n_iter_ else: # default n_jobs==1 should be used here # parallelisation of k-means runs seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init) results = Parallel(n_jobs=n_jobs, verbose=0)( delayed(_kmeans_single_with_weights)(X, weights, n_clusters, max_iter=max_iter, init=init, verbose=verbose, tol=tol, precompute_distances=precompute_distances, x_squared_norms=x_squared_norms, # Change seed to ensure variety random_state=seed) for seed in seeds) # Get results with the lowest inertia labels, inertia, centers, n_iters = list(zip(*results)) best = np.argmin(inertia) best_labels = labels[best] best_inertia = inertia[best] best_centers = centers[best] best_n_iter = n_iters[best] if not sp.issparse(X): if not copy_x: X += X_mean best_centers += X_mean if return_n_iter: return best_centers, best_labels, best_inertia, best_n_iter else: return best_centers, best_labels, best_inertia class KMeansWeighted(object): """K-Means clustering with weights Read more in the :ref:`User Guide <k_means>`. Parameters ---------- n_clusters : int, optional, default: 8 The number of clusters to form as well as the number of centroids to generate. max_iter : int, default: 300 Maximum number of iterations of the k-means algorithm for a single run. n_init : int, default: 10 Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia. init : {'k-means++', 'random' or an ndarray} Method for initialization, defaults to 'k-means++': 'k-means++' : selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details. 'random': choose k observations (rows) at random from data for the initial centroids. If an ndarray is passed, it should be of shape (n_clusters, n_features) and gives the initial centers. precompute_distances : {'auto', True, False} Precompute distances (faster but takes more memory). 'auto' : do not precompute distances if n_samples * n_clusters > 12 million. This corresponds to about 100MB overhead per job using double precision. True : always precompute distances False : never precompute distances tol : float, default: 1e-4 Relative tolerance with regards to inertia to declare convergence n_jobs : int The number of jobs to use for the computation. This works by computing each of the n_init runs in parallel. If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. random_state : integer or numpy.RandomState, optional The generator used to initialize the centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator. verbose : int, default 0 Verbosity mode. copy_x : boolean, default True When pre-computing distances it is more numerically accurate to center the data first. If copy_x is True, then the original data is not modified. If False, the original data is modified, and put back before the function returns, but small numerical differences may be introduced by subtracting and then adding the data mean. Attributes ---------- cluster_centers_ : array, [n_clusters, n_features] Coordinates of cluster centers labels_ : Labels of each point inertia_ : float Sum of distances of samples to their closest cluster center. Notes ------ The k-means problem is solved using Lloyd's algorithm. """ def __init__(self, n_clusters=8, init='kmeans++_with_weights', n_init=10, max_iter=300, tol=1e-4, precompute_distances='auto', verbose=0, random_state=None, copy_x=True, n_jobs=1): self.n_clusters = n_clusters self.init = init self.max_iter = max_iter self.tol = tol self.precompute_distances = precompute_distances self.n_init = n_init self.verbose = verbose self.random_state = None self.copy_x = copy_x self.n_jobs = n_jobs def _check_fit_data(self, X): """Verify that the number of samples given is larger than k""" X = check_array(X, accept_sparse='csr', dtype=np.float64) if X.shape[0] < self.n_clusters: raise ValueError("n_samples=%d should be >= n_clusters=%d" % ( X.shape[0], self.n_clusters)) return X def _check_test_data(self, X): X = check_array(X, accept_sparse='csr', dtype=FLOAT_DTYPES, warn_on_dtype=True) n_samples, n_features = X.shape expected_n_features = self.cluster_centers_.shape[1] if not n_features == expected_n_features: raise ValueError("Incorrect number of features. " "Got %d features, expected %d" % ( n_features, expected_n_features)) return X def fit(self, X, weights, y=None, debug=False): """Compute k-means clustering. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) weights : array, shape (n_samples) """ random_state = np.random # random_state is always np.random if debug: print((type(X))) print(X) print((X.shape)) X = self._check_fit_data(X) self.cluster_centers_, self.labels_, self.inertia_, self.n_iter_ = \ k_means_with_weights( X, weights, n_clusters=self.n_clusters, init=self.init, n_init=self.n_init, max_iter=self.max_iter, verbose=self.verbose, return_n_iter=True, precompute_distances=self.precompute_distances, tol=self.tol, random_state=self.random_state, copy_x=self.copy_x, n_jobs=self.n_jobs) return self def fit_predict(self, X, weights, y=None): """Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). """ return self.fit(X, weights).labels_ def fit_transform(self, X, weights, y=None): """Compute clustering and transform X to cluster-distance space. Equivalent to fit(X).transform(X), but more efficiently implemented. """ # Currently, this just skips a copy of the data if it is not in # np.array or CSR format already. # XXX This skips _check_test_data, which may change the dtype; # we should refactor the input validation. X = self._check_fit_data(X) return self.fit(X, weights)._transform(X) def transform(self, X, y=None): """Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by `transform` will typically be dense. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] New data to transform. Returns ------- X_new : array, shape [n_samples, k] X transformed in the new space. """ check_is_fitted(self, 'cluster_centers_') X = self._check_test_data(X) return self._transform(X) def _transform(self, X): """guts of transform method; no input validation""" return euclidean_distances(X, self.cluster_centers_) def predict(self, X): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] New data to predict. Returns ------- labels : array, shape [n_samples,] Index of the cluster each sample belongs to. """ check_is_fitted(self, 'cluster_centers_') X = self._check_test_data(X) x_squared_norms = row_norms(X, squared=True) return _labels_inertia(X, x_squared_norms, self.cluster_centers_)[0] def score(self, X, y=None): """Opposite of the value of X on the K-means objective. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] New data. Returns ------- score : float Opposite of the value of X on the K-means objective. """ check_is_fitted(self, 'cluster_centers_') X = self._check_test_data(X) x_squared_norms = row_norms(X, squared=True) return -_labels_inertia(X, x_squared_norms, self.cluster_centers_)[1] def main(): pass if __name__ == '__main__': main()
thorwhalen/ut
ml/cluster/w_kmeans.py
Python
mit
39,462
[ "Gaussian" ]
db9dc579e850dbf0005ddabaf63fcadc87dbdcb2965c905ce4cca6cb43f1f7dd
# # Copyright 2001 - 2006 Ludek Smid [http://www.ospace.net/] # # This file is part of IGE - Outer Space. # # IGE - Outer Space is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # IGE - Outer Space is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with IGE - Outer Space; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # import gdata, client import glob, math import pygame, pygame.image from osci import gdata from ige.ospace.Const import * from ige.ospace import Rules from ige import log whiteShift = 80000 redShift = 90000 smallStarImgs = None techImgs = None bigStarImgs = None planetImgs = None planetImgCnt = None buttonImgs = None cmdInProgressImg = None loginLogoImg = None structProblemImg = None structOffImg = None icons = {} def initialize(): # needed for progress dlg global loginLogoImg loginLogoImg = pygame.image.load('res/logo-login.png').convert_alpha() def loadResources(): import dialog dlg = dialog.ProgressDlg(gdata.app) curr = 0 max = len(glob.glob('res/galaxy/*.png')) + len(glob.glob('res/techs/*.png')) + \ len(glob.glob('res/system/*.png')) + len(glob.glob('res/icons/*.png')) + len(glob.glob('res/buttons/*.png')) dlg.display(_('Loading resources'), 0, max) # load star imgs global smallStarImgs smallStarImgs = {} for filename in glob.glob('res/galaxy/star_*.png'): curr += 1 if curr % 10 == 0: dlg.setProgress(_('Loading resources...'), curr) name = filename[16:-4] smallStarImgs[name] = pygame.image.load(filename).convert_alpha() # load tech imgs global techImgs techImgs = {} white = pygame.Surface((37,37)) white.fill((255, 255, 255)) white.set_alpha(64) red = pygame.Surface((37,37)) red.fill((255, 0, 0)) red.set_alpha(64) for filename in glob.glob('res/techs/????.png'): curr += 1 if curr % 10 == 0: dlg.setProgress(_('Loading resources...'), curr) name = filename[10:14] imgID = int(name) techImgs[imgID] = pygame.image.load(filename).convert_alpha() copyImg = techImgs[imgID].convert_alpha() copyImg.blit(white, (0,0)) techImgs[imgID + whiteShift] = copyImg copyImg = techImgs[imgID].convert_alpha() copyImg.blit(red, (0,0)) techImgs[imgID + redShift] = copyImg # load big star imgs global bigStarImgs bigStarImgs = {} for filename in glob.glob('res/system/star_*.png'): curr += 1 if curr % 10 == 0: dlg.setProgress(_('Loading resources...'), curr) name = filename[16:-4] bigStarImgs[name] = pygame.image.load(filename).convert_alpha() # load planet images global planetImgs global planetImgCnt planetImgs = {} planetImgCnt = {} for filename in glob.glob('res/system/planet_*.png'): curr += 1 if curr % 10 == 0: dlg.setProgress(_('Loading resources...'), curr) name = filename[18:-4] pltype = name[:1] if pltype in planetImgCnt: planetImgCnt[pltype] += 1 else: planetImgCnt[pltype] = 1 planetImgs[name] = pygame.image.load(filename).convert_alpha() # load ship imgs global shipImgs shipImgs = {} for filename in glob.glob('res/ships/??.png'): curr += 1 if curr % 10 == 0: dlg.setProgress(_('Loading resources...'), curr) name = filename[10:-4] shipImgs[int(name)] = pygame.image.load(filename).convert_alpha() # load star imgs global icons icons = {} for filename in glob.glob('res/icons/*.png'): curr += 1 if curr % 10 == 0: dlg.setProgress(_('Loading resources...'), curr) name = filename[10:-4] icons[name] = pygame.image.load(filename).convert_alpha() # load buttons global buttonImgs buttonImgs = {} for filename in glob.glob('res/buttons/*.png'): curr += 1 if curr % 10 == 0: dlg.setProgress(_('Loading resources...'), curr) name = filename[12:-4] buttonImgs[name] = pygame.image.load(filename).convert_alpha() # other icons global cmdInProgressImg cmdInProgressImg = pygame.image.load('res/cmdInProgress.png').convert_alpha() global structProblemImg structProblemImg = pygame.image.load('res/struct_problem.png').convert_alpha() global structOffImg structOffImg = pygame.image.load('res/struct_off.png').convert_alpha() dlg.hide() def getTechImg(techID): return techImgs.get(techID, techImgs[0]) def getShipImg(combatClass, isMilitary): return shipImgs.get(int(combatClass) * 10 + int(isMilitary), shipImgs[99]) def getSmallStarImg(name): return smallStarImgs[name] def getBigStarImg(name): return bigStarImgs[name] def getPlanetImg(pltype,plid): global planetImgCnt name = '%s%d' % (pltype,plid % planetImgCnt[pltype]) return planetImgs[name] def getButton(name,state): if state: name = "%s_%s" % (name,'active') else: name = "%s_%s" % (name,'inactive') return buttonImgs[name] def getUnknownName(): return _('[Unknown]') def getNA(): return _('N/A') def getSystemOverviewProblemColor(owner,problem): if problem: return gdata.sevColors[gdata.CRI] else: return getPlayerColor(owner) def OLDgetFFColorCode(relationship): if relationship < 0: return (0xff, 0x00, 0xff) elif relationship < 500 and relationship >= 0: rel = relationship / 500.0 r = 0xff g = int(0xff * rel) b = 0x00 return (r, g, b) elif relationship >= 500 and relationship <= 1000: rel = (relationship - 500) / 500.0 #r = int(0xff * (1 - rel)) #g = 0xff #b = int(0xff * rel) r = 0xff g = 0xff b = int(0xff * rel) return (r, g, b) elif relationship == 1250: return (0x00, 0xff, 0x00) else: return (0xc0, 0xc0, 0xc0) def getFFColorCode(relationship): if relationship < 0: return (0xff, 0x00, 0xff) elif relationship < REL_UNFRIENDLY_LO: return (0xff, 0x80, 0x80) elif relationship < REL_NEUTRAL_LO: return (0xff, 0x90, 0x01) elif relationship < REL_FRIENDLY_LO: return (0xff, 0xff, 0x00) elif relationship < REL_ALLY_LO: return (0xb0, 0xb0, 0xff) elif relationship <= REL_ALLY_HI: return (0x80, 0xff, 0xff) elif relationship == 1250: return (0x00, 0xff, 0x00) else: return (0xc0, 0xc0, 0xc0) def getHabitabilityColorCode(bio): if bio < 0: return (0xff, 0x00, 0xff) if bio < 26: return((255),(5*bio),0x00) # end 255, 125, 0 if bio < 76: return((255-2*(bio-25)),(125+2*(bio-25)),0x00) # end 155, 225, 0 if bio < 126: return((155-3*(bio-75)),(225),0x00) #end 5, 225, 0 if bio < 201: return(0x00,0xFF,(2*(bio-125))) #end 0, 225, 250 if bio > 200: return (0x00, 0xff, 0xff) return (0xc0, 0xc0, 0xc0) def getPirateColonyColorCode(pirate): if not pirate: return (0xc0, 0xc0, 0xc0) if pirate <= 0: return (0xff, 0x00, 0xff) if pirate < 26: return((255),(5*pirate),0x00) # end 255, 125, 0 if pirate < 76: return((255-2*(pirate-25)),(125+2*(pirate-25)),0x00) # end 155, 225, 0 if pirate < 126: return((155-3*(pirate-75)),(225),0x00) #end 5, 225, 0 if pirate < 201: return(0x00,0xFF,(2*(pirate-125))) #end 0, 225, 250 if pirate > 200: return (0x00, 0xff, 0xff) return (0xc0, 0xc0, 0xc0) def getFameColorCode(fame): if fame > 0 and fame < 200: #log.debug(fame,(0xff,255 - int(255*(fame/200)),0x00)) return (0xff,255 - int(255*(fame/200.0)),0x00) if fame == 200: return (0xff,0x00,0xff) #pirate colony return (0xc0, 0xc0, 0xc0) def getMineralColorCode(minerals): if minerals >= 0: return (0xff,max(0,min(255,255 - int(255*(minerals/200.0)))),0x0) #use min, since it we occasionally get 201+ mineral levels, but it is so rare that we can ignore it for colors. return (0xc0, 0xc0, 0xc0) def getSlotColorCode(slots): if slots > 20: return (0x0,0xFF,min(255,(slots-20)*10)) #in case sometime in the future we have larger worlds available if slots > 0: return (int(255*(slots/20.0)),255 - int(255*(slots/20.0)),0x0) return (0xc0, 0xc0, 0xc0) def getSlotSystemColorCode(slots,planets): if planets > 0: slots = int(float(slots)/planets) if slots > 20: return (0x0,0xFF,min(255,(slots-20)*10)) #in case sometime in the future we have larger worlds available if slots > 0: return (int(255*(slots/20.0)),255 - int(255*(slots/20.0)),0x0) return (0xc0, 0xc0, 0xc0) else: return (0xc0, 0xc0, 0xc0) def getStargateColorCode(accel): accel = accel * 100 - 100 if accel < 1: return (0xc0, 0xc0, 0xc0) if accel < 50: return (0xff, 0xff, 0x00) if accel < 150: return (0xff, 0xc0, 0x00) if accel < 250: return (0xff, 0x60, 0x00) if accel < 350: return (0xff, 0x00, 0x00) if accel < 450: return (0xff, 0x00, 0x80) if accel > 449: return (0xff, 0x00, 0xff) return (0xc0, 0xc0, 0xc0) def getDockColorCode(refuel,upgrades): #refuel is based on best dock; upgrades are based on sum of all docks #refuel range: 0...6 #upgrade range: 0...100 (cap 100) if (refuel > 1 and upgrades > 0) or (refuel > 2): #refuel > 2 for other player docks since they always read upgrades of 0; this probably should be corrected for allies refuelScale = max(0,min(1,(refuel-1)/5.0)) upgradeScale = max(0,min(1,upgrades/50)) return (0xFF,int(refuelScale*(1-upgradeScale)*255),int(refuelScale*(upgradeScale)*255)) if refuel > 0: refuelScale = max(0,min(1,refuel/2.0)) return (0x00,100+100*int(refuelScale),100+100*int(refuelScale)) # cyan return (0xc0, 0xc0, 0xc0) def getMoraleColors(morale): if morale >= 0: return (255-int(255*(morale/100.0)),int(255*(morale/100.0)),0x0) return (0xc0, 0xc0, 0xc0) def getPlayerColor(owner, onlyDiplo = False): if owner == OID_NONE: return getFFColorCode(REL_UNDEF) if not onlyDiplo: if gdata.config.defaults.highlights == 'yes': if gdata.playersHighlightColors.has_key(owner): return gdata.playersHighlightColors[owner] rel = min(REL_UNDEF,client.getRelationTo(owner)) return getFFColorCode(rel) def getControlColor(owner, onlyDiplo = False): if owner == OID_NONE: return False if not onlyDiplo: if gdata.config.defaults.highlights == 'yes': if gdata.playersHighlightColors.has_key(owner): return fadeDarkColor(gdata.playersHighlightColors[owner]) rel = min(REL_UNDEF,client.getRelationTo(owner)) return fadeDarkColor(getFFColorCode(rel)) def getGateLineWidth(owner): if owner == OID_NONE: return 1 rel = min(REL_UNDEF,client.getRelationTo(owner)) if rel == 1250: return 2 return 1 def getStarmapWidgetPlanetColor(ownerid,bio,mineral,slot,stargate,dockfuel,dockupgrade,fame,stratres,morale,pirate=False): colors = {} for datatype in gdata.OVERLAY_TYPES: colors[datatype] = getStarmapWidgetPlanetColorPerDatatype(datatype,ownerid,bio,mineral,slot,stargate,dockfuel,dockupgrade,fame,stratres,morale,pirate) return colors def getStarmapWidgetSystemColor(ownerid,bio,mineral,slot,num_planets,stargate,dockfuel,dockupgrade,fame,stratres,morale,pirate=False): colors = {} for datatype in gdata.OVERLAY_TYPES: colors[datatype] = getStarmapWidgetSystemColorPerDatatype(datatype,ownerid,bio,mineral,slot,num_planets,stargate,dockfuel,dockupgrade,fame,stratres,morale,pirate) return colors def getStarmapWidgetPlanetColorPerDatatype(datatype,ownerid,bio,mineral,slot,stargate,dockfuel,dockupgrade,fame,stratres,morale,pirate=False): if (datatype == gdata.OVERLAY_OWNER): return getPlayerColor(ownerid) if (datatype == gdata.OVERLAY_DIPLO): return getPlayerColor(ownerid,True) if (datatype == gdata.OVERLAY_BIO): return getHabitabilityColorCode(bio) if (datatype == gdata.OVERLAY_MIN): return getMineralColorCode(mineral) if (datatype == gdata.OVERLAY_SLOT): return getSlotColorCode(slot) if (datatype == gdata.OVERLAY_STARGATE): return getStargateColorCode(stargate) if (datatype == gdata.OVERLAY_DOCK): return getDockColorCode(dockfuel,dockupgrade) if (datatype == gdata.OVERLAY_FAME): return getFameColorCode(fame) if (datatype == gdata.OVERLAY_PIRATECOLONYCOST): return getPirateColonyColorCode(pirate) # if (datatype == "stratres"): # return getMoraleColors(stratres) if (datatype == gdata.OVERLAY_MORALE): return getMoraleColors(morale) return getPlayerColor(ownerid) #default def getStarmapWidgetSystemColorPerDatatype(datatype,ownerid,bio,mineral,slot,num_planets,stargate,dockfuel,dockupgrade,fame,stratres,morale,pirate=False): if (datatype == gdata.OVERLAY_OWNER): return getPlayerColor(ownerid) if (datatype == gdata.OVERLAY_DIPLO): return getPlayerColor(ownerid,True) if (datatype == gdata.OVERLAY_BIO): return getHabitabilityColorCode(bio) if (datatype == gdata.OVERLAY_MIN): return getMineralColorCode(mineral) if (datatype == gdata.OVERLAY_SLOT): return getSlotSystemColorCode(slot,num_planets) if (datatype == gdata.OVERLAY_STARGATE): return getStargateColorCode(stargate) if (datatype == gdata.OVERLAY_DOCK): return getDockColorCode(dockfuel,dockupgrade) if (datatype == gdata.OVERLAY_FAME): return getFameColorCode(fame) if (datatype == gdata.OVERLAY_PIRATECOLONYCOST): return getPirateColonyColorCode(pirate) # if (datatype == "stratres"): # return getMoraleColors(stratres) if (datatype == gdata.OVERLAY_MORALE): return getMoraleColors(morale) return getPlayerColor(ownerid) #default def fadeColor(triplet): return ((triplet[0]+0xc0)/2,(triplet[1]+0xc0)/2,(triplet[2]+0xc0)/2) def fadeDarkColor(triplet): return ((triplet[0]+0x00*2)/3,(triplet[1]+0x00*2)/3,(triplet[2]+0x00*2)/3) def formatTime(time,separator=':'): time = int(math.ceil(time)) sign = '' if time < 0: time = - time sign = '-' days = time / 24 hours = time % 24 return '%s%d%s%02d' % (sign, days, separator, hours) def formatBE(b, e): return '%d / %d' % (b, e) def globalQueueName(index): return ['Default', 'Red', 'Blue', 'Yellow', 'Violet'][index]
Lukc/ospace-lukc
client-pygame/lib/osci/res.py
Python
gpl-2.0
13,877
[ "Galaxy" ]
a7d74278198c92909e99cd7963ad8baad63a713c3c4749ca2bf18740c152ee69
'''This file is part of AeoLiS. AeoLiS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AeoLiS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with AeoLiS. If not, see <http://www.gnu.org/licenses/>. AeoLiS Copyright (C) 2015 Bas Hoonhout bas.hoonhout@deltares.nl b.m.hoonhout@tudelft.nl Deltares Delft University of Technology Unit of Hydraulic Engineering Faculty of Civil Engineering and Geosciences Boussinesqweg 1 Stevinweg 1 2629 HVDelft 2628CN Delft The Netherlands The Netherlands ''' from __future__ import absolute_import import logging class Logger(logging.getLoggerClass()): '''Custom logger class that supports multiline logging and raising exceptions that are logged with the full traceback''' def _log(self, lvl, msgs, *args, **kwargs): if not isinstance(msgs, list): msgs = [msgs] for msg in msgs: super(Logger, self)._log(lvl, msg, *args, **kwargs) def log_and_raise(self, msg, exc=Exception, *args, **kwargs): try: raise exc(msg) except: super(Logger, self).exception(msg, stack_info=True) raise logging.setLoggerClass(Logger) import aeolis.inout import aeolis.model import aeolis.wind import aeolis.bed import aeolis.hydro import aeolis.threshold import aeolis.transport import aeolis.netcdf
openearth/aeolis-python
aeolis/__init__.py
Python
gpl-3.0
1,881
[ "NetCDF" ]
781b2904b2cdcd2509d2bd877e4926ac20f5f5da16c0f06272d0ddebe61a526e
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import threading from DIRAC import gLogger, S_ERROR from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler class TransportPool(object): def __init__(self, logger=False): if logger: self.log = logger else: self.log = gLogger self.__modLock = threading.Lock() self.__transports = {} self.__listenPersistConn = False self.__msgCounter = 0 result = gThreadScheduler.addPeriodicTask(5, self.__sendKeepAlives) if not result["OK"]: self.log.fatal("Cannot add task to thread scheduler", result["Message"]) self.__keepAlivesTask = result["Value"] # # Send keep alives # def __sendKeepAlives(self, retries=5): if retries == 0: return tridList = [] try: tridList = [trid for trid in self.__transports] except RuntimeError: self.__sendKeepAlives(retries - 1) for trid in tridList: try: tr = self.__transports[trid][0] except KeyError: continue if not tr.getKeepAliveLapse(): continue try: tr.sendKeepAlive(now=time.time()) except KeyError: continue except Exception: gLogger.exception("Cannot send keep alive") # exists def exists(self, trid): return trid in self.__transports # Add def add(self, transport): remoteAddr = transport.getRemoteAddress() localAddr = transport.getLocalAddress() self.log.debug("New connection -> %s:%s" % (remoteAddr[0], remoteAddr[1])) trid = "%s:%s->%s:%s" % (localAddr[0], localAddr[1], remoteAddr[0], remoteAddr[1]) return self.__add(trid, transport) def __add(self, trid, transport): self.__modLock.acquire() try: if not self.exists(trid): self.__transports[trid] = (transport, {}) finally: self.__modLock.release() return trid # Data association def associateData(self, trid, kw, value): self.__modLock.acquire() try: if trid in self.__transports: self.__transports[trid][1][kw] = value finally: self.__modLock.release() def getAssociatedData(self, trid, kw): try: return self.__transports[trid][1][kw] except KeyError: return None # Get transport def get(self, trid): try: return self.__transports[trid][0] except KeyError: return None # Receive def receive(self, trid, maxBufferSize=0, blockAfterKeepAlive=True, idleReceive=False): try: received = self.__transports[trid][0].receiveData(maxBufferSize, blockAfterKeepAlive, idleReceive) return received except KeyError: return S_ERROR("No transport with id %s defined" % trid) # Send def send(self, trid, msg): try: transport = self.__transports[trid][0] except KeyError: return S_ERROR("No transport with id %s defined" % trid) return transport.sendData(msg) # Send And Close def sendErrorAndClose(self, trid, msg): try: result = self.__transports[trid][0].sendData(S_ERROR(msg)) if not result["OK"]: return result except KeyError: return S_ERROR("No transport with id %s defined" % trid) finally: self.close(trid) def sendAndClose(self, trid, msg): try: result = self.__transports[trid][0].sendData(msg) if not result["OK"]: return result except KeyError: return S_ERROR("No transport with id %s defined" % trid) finally: self.close(trid) def sendKeepAlive(self, trid, responseId=None): try: return self.__transports[trid][0].sendKeepAlive(responseId) except KeyError: return S_ERROR("No transport with id %s defined" % trid) # Close def close(self, trid): try: self.__transports[trid][0].close() except KeyError: return S_ERROR("No transport with id %s defined" % trid) self.remove(trid) def remove(self, trid): self.__modLock.acquire() try: if trid in self.__transports: del self.__transports[trid] finally: self.__modLock.release() gTransportPool = None def getGlobalTransportPool(): global gTransportPool if not gTransportPool: gTransportPool = TransportPool() return gTransportPool
ic-hep/DIRAC
src/DIRAC/Core/DISET/private/TransportPool.py
Python
gpl-3.0
4,891
[ "DIRAC" ]
a55f81a46b81d047828713767540115e9d762c9961b35447436c1d998d769110
import numpy as np from scipy.stats import multivariate_normal from menpofit.math.fft_utils import pad, crop def centered_meshgrid(shape): r""" Method that generates a centered meshgrid. Parameters ---------- shape : (`int`, `int`) The desired meshgrid shape. Returns ------- grid : ``shape + (2,)`` `ndarray` The centered meshgrid. """ # Compute rounded half of provided shape shape = np.asarray(shape) half_shape = np.floor(shape / 2) half_shape = np.require(half_shape, dtype=int) # Find start and end values for meshgrid start = -half_shape end = half_shape + shape % 2 # Create grid sampling_grid = np.mgrid[start[0]:end[0], start[1]:end[1]] return np.rollaxis(sampling_grid, 0, 3) def gaussian_response(shape, cov=2): r""" Method that returns a 2D gaussian response centered in the middle with the specified shape. Parameters ---------- shape : (`int`, `int`) The desired shape. cov : `int`, optional The covariance of the normal distribution. Returns ------- response : ``(1,) + shape`` `ndarray` The Gaussian response. """ grid = centered_meshgrid(shape) return multivariate_normal(mean=np.zeros(2), cov=cov).pdf(grid)[None, ...] def conv2d(image, f, mode='same', boundary='symmetric'): r""" Performs fast 2D convolution in the frequency domain. Note that if the input is multi-channel, then the convolution is performed per channel. Parameters ---------- image : ``(C, Y, X)`` `ndarray` The input image. f : ``(C, Y, X)`` `ndarray` The filter to convolve with defined on the spatial domain. mode : {``full``, ``same``, ``valid``}, optional Determines the shape of the resulting convolution. boundary: str {``constant``, ``symmetric``}, optional Determines the padding applied on the image. Returns ------- response : ``(C, Y, X)`` `ndarray` Result of convolving each image channel with its corresponding filter channel. """ # Compute the extended shape image_shape = np.asarray(image.shape[-2:]) filter_shape = np.asarray(f.shape[-2:]) ext_shape = image_shape + filter_shape - 1 # Pad image and f ext_image = pad(image, ext_shape, boundary=boundary) ext_filter = pad(f, ext_shape) # Compute ffts of extended image and extended f fft_ext_image = np.fft.fft2(ext_image) fft_ext_filter = np.fft.fft2(ext_filter) # Compute extended convolution in Fourier domain fft_ext_c = fft_ext_filter * fft_ext_image # Compute ifft of extended convolution ext_c = np.real(np.fft.ifftshift(np.fft.ifft2(fft_ext_c), axes=(-2, -1))) # Fix response shape. if mode is 'full': return ext_c elif mode is 'same': return crop(ext_c, image_shape) elif mode is 'valid': return crop(ext_c, image_shape - filter_shape + 1) else: raise ValueError("mode must be 'full', 'same' or 'valid'")
nontas/trafficsignrecognition
trafficsignrecognition/correlationfilter/utils.py
Python
bsd-3-clause
3,062
[ "Gaussian" ]
f3ad673bf5e2825bf622e147a600a6f68a3b83d579ce6b6337d5a8ab4d054925
# coding: utf-8 import unittest import os from pymatgen import Molecule from pymatgen.io.fiesta import FiestaInput, FiestaOutput test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files') class FiestaInputTest(unittest.TestCase): def setUp(self): coords = [[0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 1.089000], [1.026719, 0.000000, -0.363000], [-0.513360, -0.889165, -0.363000], [-0.513360, 0.889165, -0.363000]] self.coords = coords mol = Molecule(["C", "H", "H", "H", "H"], coords) self.cellin = FiestaInput(mol, correlation_grid={'dE_grid': u'0.500', 'n_grid': u'14'}, Exc_DFT_option={'rdVxcpsi': u'1'}, COHSEX_options={'eigMethod': u'C', 'mix_cohsex': u'0.500', 'nc_cohsex': u'0', 'nit_cohsex': u'0', 'nv_cohsex': u'0', 'resMethod': u'V', 'scf_cohsex_wf': u'0'}, GW_options={'nc_corr': u'10', 'nit_gw': u'3', 'nv_corr': u'10'}, BSE_TDDFT_options={'do_bse': u'1', 'do_tddft': u'0', 'nc_bse': u'382', 'nit_bse': u'50', 'npsi_bse': u'1', 'nv_bse': u'21'}) def test_init(self): mol = Molecule(["C", "H", "H", "H", "H"], self.coords) cellin = FiestaInput(mol) self.assertEqual(cellin.molecule.spin_multiplicity, 1) def test_str_and_from_string(self): ans = '# number of atoms and species\n 5 2\n# number of valence bands\n 5\n' \ '# number of points and spacing in eV for correlation grid\n 14 0.500\n' \ '# relire=1 ou recalculer=0 Exc DFT\n 1\n' \ '# number of COHSEX corrected occp and unoccp bands: C=COHSEX H=HF\n 0 0 C\n' \ '# number of COHSEX iter, scf on wfns, mixing coeff; V=RI-V I=RI-D\n 0 V 0 0.500\n' \ '# number of GW corrected occp and unoccp bands\n 10 10\n# number of GW iterations\n 3\n' \ '# dumping for BSE and TDDFT\n 1 0\n' \ '# number of occp. and virtual bands fo BSE: nocore and up to 40 eVs\n 21 382\n' \ '# number of excitations needed and number of iterations\n 1 50\n' \ '# list of symbols in order\nC\nH\n' \ '# scaling factor\n 1.000\n# atoms x,y,z cartesian .. will be multiplied by scale\n 0.0 0.0 0.0 1\n' \ ' 0.0 0.0 1.089 2\n 1.026719 0.0 -0.363 2\n -0.51336 -0.889165 -0.363 2\n -0.51336 0.889165 -0.363 2' \ '\n ' self.assertEqual(str(self.cellin), ans) cellin = FiestaInput.from_string(ans) self.assertEqual(cellin.GW_options['nc_corr'], '10') self.assertEqual(cellin.COHSEX_options['eigMethod'], 'C') class FiestaOutputTest(unittest.TestCase): def setUp(self): self.logfiesta = FiestaOutput(os.path.join(test_dir, "log_fiesta")) def test_props(self): out = self.logfiesta self.assertEqual(out.data[0]["Gaps"]["Egap_QP_Linear"], u'10.4135') self.assertEqual(out.data[0]["HOMO"], {'band': u'HOMO', 'eKS': u'-7.3029', 'eQP_Linear': u'-9.5142', 'eQP_SCF': u'-8.9264', 'eQP_old': u'-7.7188', 'eXX': u'-15.9483', 'sigma_c_Linear': u'-0.4587', 'sigma_c_SCF': u'0.3900', 'z': u'0.87'}) if __name__ == "__main__": unittest.main()
gVallverdu/pymatgen
pymatgen/io/tests/test_fiesta.py
Python
mit
3,999
[ "pymatgen" ]
31d4601068bc4f736cc9b889fca5c2b0d279377b367485098be0882a23e78202
"""Support for Konnected devices.""" import copy import hmac import json import logging from aiohttp.hdrs import AUTHORIZATION from aiohttp.web import Request, Response import voluptuous as vol from homeassistant import config_entries from homeassistant.components.binary_sensor import DEVICE_CLASSES_SCHEMA from homeassistant.components.http import HomeAssistantView from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ENTITY_ID, CONF_ACCESS_TOKEN, CONF_BINARY_SENSORS, CONF_DEVICES, CONF_DISCOVERY, CONF_HOST, CONF_ID, CONF_NAME, CONF_PIN, CONF_PORT, CONF_REPEAT, CONF_SENSORS, CONF_SWITCHES, CONF_TYPE, CONF_ZONE, HTTP_BAD_REQUEST, HTTP_NOT_FOUND, HTTP_UNAUTHORIZED, STATE_OFF, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv from homeassistant.helpers.typing import ConfigType from .config_flow import ( # Loading the config flow file will register the flow CONF_DEFAULT_OPTIONS, CONF_IO, CONF_IO_BIN, CONF_IO_DIG, CONF_IO_SWI, OPTIONS_SCHEMA, ) from .const import ( CONF_ACTIVATION, CONF_API_HOST, CONF_BLINK, CONF_INVERSE, CONF_MOMENTARY, CONF_PAUSE, CONF_POLL_INTERVAL, DOMAIN, PIN_TO_ZONE, STATE_HIGH, STATE_LOW, UNDO_UPDATE_LISTENER, UPDATE_ENDPOINT, ZONE_TO_PIN, ZONES, ) from .handlers import HANDLERS from .panel import AlarmPanel _LOGGER = logging.getLogger(__name__) def ensure_pin(value): """Check if valid pin and coerce to string.""" if value is None: raise vol.Invalid("pin value is None") if PIN_TO_ZONE.get(str(value)) is None: raise vol.Invalid("pin not valid") return str(value) def ensure_zone(value): """Check if valid zone and coerce to string.""" if value is None: raise vol.Invalid("zone value is None") if str(value) not in ZONES is None: raise vol.Invalid("zone not valid") return str(value) def import_device_validator(config): """Validate zones and reformat for import.""" config = copy.deepcopy(config) io_cfgs = {} # Replace pins with zones for conf_platform, conf_io in ( (CONF_BINARY_SENSORS, CONF_IO_BIN), (CONF_SENSORS, CONF_IO_DIG), (CONF_SWITCHES, CONF_IO_SWI), ): for zone in config.get(conf_platform, []): if zone.get(CONF_PIN): zone[CONF_ZONE] = PIN_TO_ZONE[zone[CONF_PIN]] del zone[CONF_PIN] io_cfgs[zone[CONF_ZONE]] = conf_io # Migrate config_entry data into default_options structure config[CONF_IO] = io_cfgs config[CONF_DEFAULT_OPTIONS] = OPTIONS_SCHEMA(config) # clean up fields migrated to options config.pop(CONF_BINARY_SENSORS, None) config.pop(CONF_SENSORS, None) config.pop(CONF_SWITCHES, None) config.pop(CONF_BLINK, None) config.pop(CONF_DISCOVERY, None) config.pop(CONF_API_HOST, None) config.pop(CONF_IO, None) return config def import_validator(config): """Reformat for import.""" config = copy.deepcopy(config) # push api_host into device configs for device in config.get(CONF_DEVICES, []): device[CONF_API_HOST] = config.get(CONF_API_HOST, "") return config # configuration.yaml schemas (legacy) BINARY_SENSOR_SCHEMA_YAML = vol.All( vol.Schema( { vol.Exclusive(CONF_ZONE, "s_io"): ensure_zone, vol.Exclusive(CONF_PIN, "s_io"): ensure_pin, vol.Required(CONF_TYPE): DEVICE_CLASSES_SCHEMA, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_INVERSE, default=False): cv.boolean, } ), cv.has_at_least_one_key(CONF_PIN, CONF_ZONE), ) SENSOR_SCHEMA_YAML = vol.All( vol.Schema( { vol.Exclusive(CONF_ZONE, "s_io"): ensure_zone, vol.Exclusive(CONF_PIN, "s_io"): ensure_pin, vol.Required(CONF_TYPE): vol.All(vol.Lower, vol.In(["dht", "ds18b20"])), vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_POLL_INTERVAL, default=3): vol.All( vol.Coerce(int), vol.Range(min=1) ), } ), cv.has_at_least_one_key(CONF_PIN, CONF_ZONE), ) SWITCH_SCHEMA_YAML = vol.All( vol.Schema( { vol.Exclusive(CONF_ZONE, "s_io"): ensure_zone, vol.Exclusive(CONF_PIN, "s_io"): ensure_pin, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_ACTIVATION, default=STATE_HIGH): vol.All( vol.Lower, vol.Any(STATE_HIGH, STATE_LOW) ), vol.Optional(CONF_MOMENTARY): vol.All(vol.Coerce(int), vol.Range(min=10)), vol.Optional(CONF_PAUSE): vol.All(vol.Coerce(int), vol.Range(min=10)), vol.Optional(CONF_REPEAT): vol.All(vol.Coerce(int), vol.Range(min=-1)), } ), cv.has_at_least_one_key(CONF_PIN, CONF_ZONE), ) DEVICE_SCHEMA_YAML = vol.All( vol.Schema( { vol.Required(CONF_ID): cv.matches_regex("[0-9a-f]{12}"), vol.Optional(CONF_BINARY_SENSORS): vol.All( cv.ensure_list, [BINARY_SENSOR_SCHEMA_YAML] ), vol.Optional(CONF_SENSORS): vol.All(cv.ensure_list, [SENSOR_SCHEMA_YAML]), vol.Optional(CONF_SWITCHES): vol.All(cv.ensure_list, [SWITCH_SCHEMA_YAML]), vol.Inclusive(CONF_HOST, "host_info"): cv.string, vol.Inclusive(CONF_PORT, "host_info"): cv.port, vol.Optional(CONF_BLINK, default=True): cv.boolean, vol.Optional(CONF_API_HOST, default=""): vol.Any("", cv.url), vol.Optional(CONF_DISCOVERY, default=True): cv.boolean, } ), import_device_validator, ) # pylint: disable=no-value-for-parameter CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.All( import_validator, vol.Schema( { vol.Required(CONF_ACCESS_TOKEN): cv.string, vol.Optional(CONF_API_HOST): vol.Url(), vol.Optional(CONF_DEVICES): vol.All( cv.ensure_list, [DEVICE_SCHEMA_YAML] ), } ), ) }, extra=vol.ALLOW_EXTRA, ) YAML_CONFIGS = "yaml_configs" PLATFORMS = ["binary_sensor", "sensor", "switch"] async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Konnected platform.""" cfg = config.get(DOMAIN) if cfg is None: cfg = {} if DOMAIN not in hass.data: hass.data[DOMAIN] = { CONF_ACCESS_TOKEN: cfg.get(CONF_ACCESS_TOKEN), CONF_API_HOST: cfg.get(CONF_API_HOST), CONF_DEVICES: {}, } hass.http.register_view(KonnectedView) # Check if they have yaml configured devices if CONF_DEVICES not in cfg: return True for device in cfg.get(CONF_DEVICES, []): # Attempt to importing the cfg. Use # hass.async_add_job to avoid a deadlock. hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=device ) ) return True async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up panel from a config entry.""" client = AlarmPanel(hass, entry) # creates a panel data store in hass.data[DOMAIN][CONF_DEVICES] await client.async_save_data() # if the cfg entry was created we know we could connect to the panel at some point # async_connect will handle retries until it establishes a connection await client.async_connect() hass.config_entries.async_setup_platforms(entry, PLATFORMS) # config entry specific data to enable unload hass.data[DOMAIN][entry.entry_id] = { UNDO_UPDATE_LISTENER: entry.add_update_listener(async_entry_updated) } return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) hass.data[DOMAIN][entry.entry_id][UNDO_UPDATE_LISTENER]() if unload_ok: hass.data[DOMAIN][CONF_DEVICES].pop(entry.data[CONF_ID]) hass.data[DOMAIN].pop(entry.entry_id) return unload_ok async def async_entry_updated(hass: HomeAssistant, entry: ConfigEntry): """Reload the config entry when options change.""" await hass.config_entries.async_reload(entry.entry_id) class KonnectedView(HomeAssistantView): """View creates an endpoint to receive push updates from the device.""" url = UPDATE_ENDPOINT name = "api:konnected" requires_auth = False # Uses access token from configuration def __init__(self): """Initialize the view.""" @staticmethod def binary_value(state, activation): """Return binary value for GPIO based on state and activation.""" if activation == STATE_HIGH: return 1 if state == STATE_ON else 0 return 0 if state == STATE_ON else 1 async def update_sensor(self, request: Request, device_id) -> Response: """Process a put or post.""" hass = request.app["hass"] data = hass.data[DOMAIN] auth = request.headers.get(AUTHORIZATION) tokens = [] if hass.data[DOMAIN].get(CONF_ACCESS_TOKEN): tokens.extend([hass.data[DOMAIN][CONF_ACCESS_TOKEN]]) tokens.extend( [ entry.data[CONF_ACCESS_TOKEN] for entry in hass.config_entries.async_entries(DOMAIN) if entry.data.get(CONF_ACCESS_TOKEN) ] ) if auth is None or not next( (True for token in tokens if hmac.compare_digest(f"Bearer {token}", auth)), False, ): return self.json_message("unauthorized", status_code=HTTP_UNAUTHORIZED) try: # Konnected 2.2.0 and above supports JSON payloads payload = await request.json() except json.decoder.JSONDecodeError: _LOGGER.error( "Your Konnected device software may be out of " "date. Visit https://help.konnected.io for " "updating instructions" ) device = data[CONF_DEVICES].get(device_id) if device is None: return self.json_message( "unregistered device", status_code=HTTP_BAD_REQUEST ) panel = device.get("panel") if panel is not None: # connect if we haven't already hass.async_create_task(panel.async_connect()) try: zone_num = str(payload.get(CONF_ZONE) or PIN_TO_ZONE[payload[CONF_PIN]]) payload[CONF_ZONE] = zone_num zone_data = ( device[CONF_BINARY_SENSORS].get(zone_num) or next( (s for s in device[CONF_SWITCHES] if s[CONF_ZONE] == zone_num), None ) or next( (s for s in device[CONF_SENSORS] if s[CONF_ZONE] == zone_num), None ) ) except KeyError: zone_data = None if zone_data is None: return self.json_message( "unregistered sensor/actuator", status_code=HTTP_BAD_REQUEST ) zone_data["device_id"] = device_id for attr in ("state", "temp", "humi", "addr"): value = payload.get(attr) handler = HANDLERS.get(attr) if value is not None and handler: hass.async_create_task(handler(hass, zone_data, payload)) return self.json_message("ok") async def get(self, request: Request, device_id) -> Response: """Return the current binary state of a switch.""" hass = request.app["hass"] data = hass.data[DOMAIN] device = data[CONF_DEVICES].get(device_id) if not device: return self.json_message( f"Device {device_id} not configured", status_code=HTTP_NOT_FOUND ) panel = device.get("panel") if panel is not None: # connect if we haven't already hass.async_create_task(panel.async_connect()) # Our data model is based on zone ids but we convert from/to pin ids # based on whether they are specified in the request try: zone_num = str( request.query.get(CONF_ZONE) or PIN_TO_ZONE[request.query[CONF_PIN]] ) zone = next( switch for switch in device[CONF_SWITCHES] if switch[CONF_ZONE] == zone_num ) except StopIteration: zone = None except KeyError: zone = None zone_num = None if not zone: target = request.query.get( CONF_ZONE, request.query.get(CONF_PIN, "unknown") ) return self.json_message( f"Switch on zone or pin {target} not configured", status_code=HTTP_NOT_FOUND, ) resp = {} if request.query.get(CONF_ZONE): resp[CONF_ZONE] = zone_num else: resp[CONF_PIN] = ZONE_TO_PIN[zone_num] # Make sure entity is setup zone_entity_id = zone.get(ATTR_ENTITY_ID) if zone_entity_id: resp["state"] = self.binary_value( hass.states.get(zone_entity_id).state, zone[CONF_ACTIVATION] ) return self.json(resp) _LOGGER.warning("Konnected entity not yet setup, returning default") resp["state"] = self.binary_value(STATE_OFF, zone[CONF_ACTIVATION]) return self.json(resp) async def put(self, request: Request, device_id) -> Response: """Receive a sensor update via PUT request and async set state.""" return await self.update_sensor(request, device_id) async def post(self, request: Request, device_id) -> Response: """Receive a sensor update via POST request and async set state.""" return await self.update_sensor(request, device_id)
Danielhiversen/home-assistant
homeassistant/components/konnected/__init__.py
Python
apache-2.0
14,300
[ "VisIt" ]
474e28b23e88b0b8a37f7441943105bf4755333d1343dec6365f2c5063dc332c
# -*- coding: utf-8 -*- """ sphinx.pycode ~~~~~~~~~~~~~ Utilities parsing and analyzing Python code. :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ from os import path from sphinx import package_dir from sphinx.errors import PycodeError from sphinx.pycode import nodes from sphinx.pycode.pgen2 import driver, token, tokenize, parse, literals from sphinx.util import get_module_source, detect_encoding from sphinx.util.pycompat import next, StringIO, BytesIO, TextIOWrapper from sphinx.util.docstrings import prepare_docstring, prepare_commentdoc # load the Python grammar _grammarfile = path.join(package_dir, 'pycode', 'Grammar.txt') pygrammar = driver.load_grammar(_grammarfile) pydriver = driver.Driver(pygrammar, convert=nodes.convert) # an object with attributes corresponding to token and symbol names class sym: pass for k, v in pygrammar.symbol2number.items(): setattr(sym, k, v) for k, v in token.tok_name.items(): setattr(sym, v, k) # a dict mapping terminal and nonterminal numbers to their names number2name = pygrammar.number2symbol.copy() number2name.update(token.tok_name) _eq = nodes.Leaf(token.EQUAL, '=') class AttrDocVisitor(nodes.NodeVisitor): """ Visitor that collects docstrings for attribute assignments on toplevel and in classes (class attributes and attributes set in __init__). The docstrings can either be in special '#:' comments before the assignment or in a docstring after it. """ def init(self, scope, encoding): self.scope = scope self.in_init = 0 self.encoding = encoding self.namespace = [] self.collected = {} self.tagnumber = 0 self.tagorder = {} def add_tag(self, name): name = '.'.join(self.namespace + [name]) self.tagorder[name] = self.tagnumber self.tagnumber += 1 def visit_classdef(self, node): """Visit a class.""" self.add_tag(node[1].value) self.namespace.append(node[1].value) self.generic_visit(node) self.namespace.pop() def visit_funcdef(self, node): """Visit a function (or method).""" # usually, don't descend into functions -- nothing interesting there self.add_tag(node[1].value) if node[1].value == '__init__': # however, collect attributes set in __init__ methods self.in_init += 1 self.generic_visit(node) self.in_init -= 1 def visit_expr_stmt(self, node): """Visit an assignment which may have a special comment before (or after) it. """ if _eq not in node.children: # not an assignment (we don't care for augmented assignments) return # look *after* the node; there may be a comment prefixing the NEWLINE # of the simple_stmt parent = node.parent idx = parent.children.index(node) + 1 while idx < len(parent): if parent[idx].type == sym.SEMI: idx += 1 continue # skip over semicolon if parent[idx].type == sym.NEWLINE: prefix = parent[idx].get_prefix() if not isinstance(prefix, str): prefix = prefix.decode(self.encoding) docstring = prepare_commentdoc(prefix) if docstring: self.add_docstring(node, docstring) return # don't allow docstrings both before and after break # now look *before* the node pnode = node[0] prefix = pnode.get_prefix() # if the assignment is the first statement on a new indentation # level, its preceding whitespace and comments are not assigned # to that token, but the first INDENT or DEDENT token while not prefix: pnode = pnode.get_prev_leaf() if not pnode or pnode.type not in (token.INDENT, token.DEDENT): break prefix = pnode.get_prefix() if not isinstance(prefix, str): prefix = prefix.decode(self.encoding) docstring = prepare_commentdoc(prefix) self.add_docstring(node, docstring) def visit_simple_stmt(self, node): """Visit a docstring statement which may have an assignment before.""" if node[0].type != token.STRING: # not a docstring; but still need to visit children return self.generic_visit(node) prev = node.get_prev_sibling() if not prev: return if prev.type == sym.simple_stmt and \ prev[0].type == sym.expr_stmt and _eq in prev[0].children: # need to "eval" the string because it's returned in its # original form docstring = literals.evalString(node[0].value, self.encoding) docstring = prepare_docstring(docstring) self.add_docstring(prev[0], docstring) def add_docstring(self, node, docstring): # add an item for each assignment target for i in range(0, len(node) - 1, 2): target = node[i] if self.in_init and self.number2name[target.type] == 'power': # maybe an attribute assignment -- check necessary conditions if (# node must have two children len(target) != 2 or # first child must be "self" target[0].type != token.NAME or target[0].value != 'self' or # second child must be a "trailer" with two children self.number2name[target[1].type] != 'trailer' or len(target[1]) != 2 or # first child must be a dot, second child a name target[1][0].type != token.DOT or target[1][1].type != token.NAME): continue name = target[1][1].value elif target.type != token.NAME: # don't care about other complex targets continue else: name = target.value self.add_tag(name) if docstring: namespace = '.'.join(self.namespace) if namespace.startswith(self.scope): self.collected[namespace, name] = docstring class ModuleAnalyzer(object): # cache for analyzer objects -- caches both by module and file name cache = {} @classmethod def for_string(cls, string, modname, srcname='<string>'): if isinstance(string, bytes): return cls(BytesIO(string), modname, srcname) return cls(StringIO(string), modname, srcname, decoded=True) @classmethod def for_file(cls, filename, modname): if ('file', filename) in cls.cache: return cls.cache['file', filename] try: fileobj = open(filename, 'rb') except Exception as err: raise PycodeError('error opening %r' % filename, err) obj = cls(fileobj, modname, filename) cls.cache['file', filename] = obj return obj @classmethod def for_module(cls, modname): if ('module', modname) in cls.cache: entry = cls.cache['module', modname] if isinstance(entry, PycodeError): raise entry return entry try: type, source = get_module_source(modname) if type == 'string': obj = cls.for_string(source, modname) else: obj = cls.for_file(source, modname) except PycodeError as err: cls.cache['module', modname] = err raise cls.cache['module', modname] = obj return obj def __init__(self, source, modname, srcname, decoded=False): # name of the module self.modname = modname # name of the source file self.srcname = srcname # file-like object yielding source lines self.source = source # cache the source code as well pos = self.source.tell() if not decoded: self.encoding = detect_encoding(self.source.readline) self.source.seek(pos) self.code = self.source.read().decode(self.encoding) self.source.seek(pos) self.source = TextIOWrapper(self.source, self.encoding) else: self.encoding = None self.code = self.source.read() self.source.seek(pos) # will be filled by tokenize() self.tokens = None # will be filled by parse() self.parsetree = None # will be filled by find_attr_docs() self.attr_docs = None self.tagorder = None # will be filled by find_tags() self.tags = None def tokenize(self): """Generate tokens from the source.""" if self.tokens is not None: return self.tokens = list(tokenize.generate_tokens(self.source.readline)) self.source.close() def parse(self): """Parse the generated source tokens.""" if self.parsetree is not None: return self.tokenize() try: self.parsetree = pydriver.parse_tokens(self.tokens) except parse.ParseError as err: raise PycodeError('parsing failed', err) def find_attr_docs(self, scope=''): """Find class and module-level attributes and their documentation.""" if self.attr_docs is not None: return self.attr_docs self.parse() attr_visitor = AttrDocVisitor(number2name, scope, self.encoding) attr_visitor.visit(self.parsetree) self.attr_docs = attr_visitor.collected self.tagorder = attr_visitor.tagorder # now that we found everything we could in the tree, throw it away # (it takes quite a bit of memory for large modules) self.parsetree = None return attr_visitor.collected def find_tags(self): """Find class, function and method definitions and their location.""" if self.tags is not None: return self.tags self.tokenize() result = {} namespace = [] stack = [] indent = 0 defline = False expect_indent = False def tokeniter(ignore = (token.COMMENT, token.NL)): for tokentup in self.tokens: if tokentup[0] not in ignore: yield tokentup tokeniter = tokeniter() for type, tok, spos, epos, line in tokeniter: if expect_indent: if type != token.INDENT: # no suite -- one-line definition assert stack dtype, fullname, startline, _ = stack.pop() endline = epos[0] namespace.pop() result[fullname] = (dtype, startline, endline) expect_indent = False if tok in ('def', 'class'): name = next(tokeniter)[1] namespace.append(name) fullname = '.'.join(namespace) stack.append((tok, fullname, spos[0], indent)) defline = True elif type == token.INDENT: expect_indent = False indent += 1 elif type == token.DEDENT: indent -= 1 # if the stacklevel is the same as it was before the last # def/class block, this dedent closes that block if stack and indent == stack[-1][3]: dtype, fullname, startline, _ = stack.pop() endline = spos[0] namespace.pop() result[fullname] = (dtype, startline, endline) elif type == token.NEWLINE: # if this line contained a definition, expect an INDENT # to start the suite; if there is no such INDENT # it's a one-line definition if defline: defline = False expect_indent = True self.tags = result return result if __name__ == '__main__': import time, pprint x0 = time.time() #ma = ModuleAnalyzer.for_file(__file__.rstrip('c'), 'sphinx.builders.html') ma = ModuleAnalyzer.for_file('sphinx/environment.py', 'sphinx.environment') ma.tokenize() x1 = time.time() ma.parse() x2 = time.time() #for (ns, name), doc in ma.find_attr_docs().iteritems(): # print '>>', ns, name # print '\n'.join(doc) pprint.pprint(ma.find_tags()) x3 = time.time() #print nodes.nice_repr(ma.parsetree, number2name) print("tokenizing %.4f, parsing %.4f, finding %.4f" % (x1-x0, x2-x1, x3-x2))
superdesk/Live-Blog
documentor/libraries/Sphinx-1.1.3-py3.2/sphinx/pycode/__init__.py
Python
agpl-3.0
12,891
[ "VisIt" ]
63b5a848195a1afe46c4dbe47003dd2d5e8f8da0be6b7a228856664dac7657e0
# Copyright 2011 Rackspace # Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2013 IBM Corp. # All Rights Reserved. # # 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 fixtures import mock import mox import netaddr from oslo.config import cfg from oslo import messaging from nova import context from nova import db from nova.db.sqlalchemy import models from nova import exception from nova import ipv6 from nova.network import floating_ips from nova.network import linux_net from nova.network import manager as network_manager from nova.network import model as net_model from nova.objects import fixed_ip as fixed_ip_obj from nova.objects import floating_ip as floating_ip_obj from nova.objects import instance as instance_obj from nova.objects import network as network_obj from nova.objects import quotas as quotas_obj from nova.openstack.common.db import exception as db_exc from nova.openstack.common import importutils from nova.openstack.common import log as logging from nova.openstack.common import processutils from nova import test from nova.tests import fake_instance from nova.tests import fake_ldap from nova.tests import fake_network from nova.tests import matchers from nova.tests.objects import test_fixed_ip from nova.tests.objects import test_floating_ip from nova.tests.objects import test_network from nova.tests.objects import test_service from nova import utils CONF = cfg.CONF LOG = logging.getLogger(__name__) HOST = "testhost" FAKEUUID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" fake_inst = fake_instance.fake_db_instance networks = [{'id': 0, 'uuid': FAKEUUID, 'label': 'test0', 'injected': False, 'multi_host': False, 'cidr': '192.168.0.0/24', 'cidr_v6': '2001:db8::/64', 'gateway_v6': '2001:db8::1', 'netmask_v6': '64', 'netmask': '255.255.255.0', 'bridge': 'fa0', 'bridge_interface': 'fake_fa0', 'gateway': '192.168.0.1', 'broadcast': '192.168.0.255', 'dns1': '192.168.0.1', 'dns2': '192.168.0.2', 'vlan': None, 'host': HOST, 'project_id': 'fake_project', 'vpn_public_address': '192.168.0.2', 'vpn_public_port': '22', 'vpn_private_address': '10.0.0.2'}, {'id': 1, 'uuid': 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'label': 'test1', 'injected': False, 'multi_host': False, 'cidr': '192.168.1.0/24', 'cidr_v6': '2001:db9::/64', 'gateway_v6': '2001:db9::1', 'netmask_v6': '64', 'netmask': '255.255.255.0', 'bridge': 'fa1', 'bridge_interface': 'fake_fa1', 'gateway': '192.168.1.1', 'broadcast': '192.168.1.255', 'dns1': '192.168.0.1', 'dns2': '192.168.0.2', 'vlan': None, 'host': HOST, 'project_id': 'fake_project', 'vpn_public_address': '192.168.1.2', 'vpn_public_port': '22', 'vpn_private_address': '10.0.0.2'}] fixed_ips = [{'id': 0, 'network_id': 0, 'address': '192.168.0.100', 'instance_uuid': 0, 'allocated': False, 'virtual_interface_id': 0, 'floating_ips': []}, {'id': 0, 'network_id': 1, 'address': '192.168.1.100', 'instance_uuid': 0, 'allocated': False, 'virtual_interface_id': 0, 'floating_ips': []}, {'id': 0, 'network_id': 1, 'address': '2001:db9:0:1::10', 'instance_uuid': 0, 'allocated': False, 'virtual_interface_id': 0, 'floating_ips': []}] flavor = {'id': 0, 'rxtx_cap': 3} floating_ip_fields = {'id': 0, 'address': '192.168.10.100', 'pool': 'nova', 'interface': 'eth0', 'fixed_ip_id': 0, 'project_id': None, 'auto_assigned': False} vifs = [{'id': 0, 'created_at': None, 'updated_at': None, 'deleted_at': None, 'deleted': 0, 'address': 'DE:AD:BE:EF:00:00', 'uuid': '00000000-0000-0000-0000-0000000000000000', 'network_id': 0, 'instance_uuid': 0}, {'id': 1, 'created_at': None, 'updated_at': None, 'deleted_at': None, 'deleted': 0, 'address': 'DE:AD:BE:EF:00:01', 'uuid': '00000000-0000-0000-0000-0000000000000001', 'network_id': 1, 'instance_uuid': 0}, {'id': 2, 'created_at': None, 'updated_at': None, 'deleted_at': None, 'deleted': 0, 'address': 'DE:AD:BE:EF:00:02', 'uuid': '00000000-0000-0000-0000-0000000000000002', 'network_id': 2, 'instance_uuid': 0}] class FlatNetworkTestCase(test.TestCase): def setUp(self): super(FlatNetworkTestCase, self).setUp() self.tempdir = self.useFixture(fixtures.TempDir()).path self.flags(log_dir=self.tempdir) self.flags(use_local=True, group='conductor') self.network = network_manager.FlatManager(host=HOST) self.network.instance_dns_domain = '' self.network.db = db self.context = context.RequestContext('testuser', 'testproject', is_admin=False) def test_get_instance_nw_info(self): fake_get_instance_nw_info = fake_network.fake_get_instance_nw_info nw_info = fake_get_instance_nw_info(self.stubs, 0, 2) self.assertFalse(nw_info) nw_info = fake_get_instance_nw_info(self.stubs, 1, 2) for i, vif in enumerate(nw_info): nid = i + 1 check = {'bridge': 'fake_br%d' % nid, 'cidr': '192.168.%s.0/24' % nid, 'cidr_v6': '2001:db8:0:%x::/64' % nid, 'id': '00000000-0000-0000-0000-00000000000000%02d' % nid, 'multi_host': False, 'injected': False, 'bridge_interface': None, 'vlan': None, 'broadcast': '192.168.%d.255' % nid, 'dhcp_server': '192.168.1.1', 'dns': ['192.168.%d.3' % nid, '192.168.%d.4' % nid], 'gateway': '192.168.%d.1' % nid, 'gateway_v6': '2001:db8:0:1::1', 'label': 'test%d' % nid, 'mac': 'DE:AD:BE:EF:00:%02x' % nid, 'rxtx_cap': 30, 'vif_type': net_model.VIF_TYPE_BRIDGE, 'vif_devname': None, 'vif_uuid': '00000000-0000-0000-0000-00000000000000%02d' % nid, 'ovs_interfaceid': None, 'qbh_params': None, 'qbg_params': None, 'should_create_vlan': False, 'should_create_bridge': False, 'ip': '192.168.%d.%03d' % (nid, nid + 99), 'ip_v6': '2001:db8:0:1::%x' % nid, 'netmask': '255.255.255.0', 'netmask_v6': 64, 'physical_network': None, } network = vif['network'] net_v4 = vif['network']['subnets'][0] net_v6 = vif['network']['subnets'][1] vif_dict = dict(bridge=network['bridge'], cidr=net_v4['cidr'], cidr_v6=net_v6['cidr'], id=vif['id'], multi_host=network.get_meta('multi_host', False), injected=network.get_meta('injected', False), bridge_interface= network.get_meta('bridge_interface'), vlan=network.get_meta('vlan'), broadcast=str(net_v4.as_netaddr().broadcast), dhcp_server=network.get_meta('dhcp_server', net_v4['gateway']['address']), dns=[ip['address'] for ip in net_v4['dns']], gateway=net_v4['gateway']['address'], gateway_v6=net_v6['gateway']['address'], label=network['label'], mac=vif['address'], rxtx_cap=vif.get_meta('rxtx_cap'), vif_type=vif['type'], vif_devname=vif.get('devname'), vif_uuid=vif['id'], ovs_interfaceid=vif.get('ovs_interfaceid'), qbh_params=vif.get('qbh_params'), qbg_params=vif.get('qbg_params'), should_create_vlan= network.get_meta('should_create_vlan', False), should_create_bridge= network.get_meta('should_create_bridge', False), ip=net_v4['ips'][i]['address'], ip_v6=net_v6['ips'][i]['address'], netmask=str(net_v4.as_netaddr().netmask), netmask_v6=net_v6.as_netaddr()._prefixlen, physical_network= network.get_meta('physical_network', None)) self.assertThat(vif_dict, matchers.DictMatches(check)) def test_validate_networks(self): self.mox.StubOutWithMock(db, 'network_get_all_by_uuids') self.mox.StubOutWithMock(db, 'fixed_ip_get_by_address') requested_networks = [('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '192.168.1.100'), ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '192.168.0.100')] db.network_get_all_by_uuids(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( [dict(test_network.fake_network, **net) for net in networks]) ip = dict(test_fixed_ip.fake_fixed_ip, **fixed_ips[1]) ip['network'] = dict(test_network.fake_network, **networks[1]) ip['instance_uuid'] = None db.fixed_ip_get_by_address(mox.IgnoreArg(), mox.IgnoreArg(), columns_to_join=mox.IgnoreArg() ).AndReturn(ip) ip = dict(test_fixed_ip.fake_fixed_ip, **fixed_ips[0]) ip['network'] = dict(test_network.fake_network, **networks[0]) ip['instance_uuid'] = None db.fixed_ip_get_by_address(mox.IgnoreArg(), mox.IgnoreArg(), columns_to_join=mox.IgnoreArg() ).AndReturn(ip) self.mox.ReplayAll() self.network.validate_networks(self.context, requested_networks) def test_validate_networks_valid_fixed_ipv6(self): self.mox.StubOutWithMock(db, 'network_get_all_by_uuids') self.mox.StubOutWithMock(db, 'fixed_ip_get_by_address') requested_networks = [('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '2001:db9:0:1::10')] db.network_get_all_by_uuids(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( [dict(test_network.fake_network, **networks[1])]) ip = dict(test_fixed_ip.fake_fixed_ip, **fixed_ips[2]) ip['network'] = dict(test_network.fake_network, **networks[1]) ip['instance_uuid'] = None db.fixed_ip_get_by_address(mox.IgnoreArg(), mox.IgnoreArg(), columns_to_join=mox.IgnoreArg() ).AndReturn(ip) self.mox.ReplayAll() self.network.validate_networks(self.context, requested_networks) def test_validate_reserved(self): context_admin = context.RequestContext('testuser', 'testproject', is_admin=True) nets = self.network.create_networks(context_admin, 'fake', '192.168.0.0/24', False, 1, 256, None, None, None, None, None) self.assertEqual(1, len(nets)) network = nets[0] self.assertEqual(3, db.network_count_reserved_ips(context_admin, network['id'])) def test_validate_networks_none_requested_networks(self): self.network.validate_networks(self.context, None) def test_validate_networks_empty_requested_networks(self): requested_networks = [] self.mox.ReplayAll() self.network.validate_networks(self.context, requested_networks) def test_validate_networks_invalid_fixed_ip(self): self.mox.StubOutWithMock(db, 'network_get_all_by_uuids') requested_networks = [('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '192.168.1.100.1'), ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '192.168.0.100.1')] db.network_get_all_by_uuids(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( [dict(test_network.fake_network, **net) for net in networks]) self.mox.ReplayAll() self.assertRaises(exception.FixedIpInvalid, self.network.validate_networks, self.context, requested_networks) def test_validate_networks_empty_fixed_ip(self): self.mox.StubOutWithMock(db, 'network_get_all_by_uuids') requested_networks = [('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', ''), ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '')] db.network_get_all_by_uuids(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( [dict(test_network.fake_network, **net) for net in networks]) self.mox.ReplayAll() self.assertRaises(exception.FixedIpInvalid, self.network.validate_networks, self.context, requested_networks) def test_validate_networks_none_fixed_ip(self): self.mox.StubOutWithMock(db, 'network_get_all_by_uuids') requested_networks = [('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', None), ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', None)] db.network_get_all_by_uuids(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( [dict(test_network.fake_network, **net) for net in networks]) self.mox.ReplayAll() self.network.validate_networks(self.context, requested_networks) @mock.patch('nova.objects.quotas.Quotas.reserve') def test_add_fixed_ip_instance_using_id_without_vpn(self, reserve): self.stubs.Set(self.network, '_do_trigger_security_group_members_refresh_for_instance', lambda *a, **kw: None) self.mox.StubOutWithMock(db, 'network_get') self.mox.StubOutWithMock(db, 'network_update') self.mox.StubOutWithMock(db, 'fixed_ip_associate_pool') self.mox.StubOutWithMock(db, 'virtual_interface_get_by_instance_and_network') self.mox.StubOutWithMock(db, 'fixed_ip_update') self.mox.StubOutWithMock(db, 'instance_get_by_uuid') self.mox.StubOutWithMock(self.network, 'get_instance_nw_info') fixed = dict(test_fixed_ip.fake_fixed_ip, address='192.168.0.101') db.fixed_ip_associate_pool(mox.IgnoreArg(), mox.IgnoreArg(), instance_uuid=mox.IgnoreArg(), host=None).AndReturn(fixed) db.virtual_interface_get_by_instance_and_network(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(vifs[0]) db.fixed_ip_update(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) inst = fake_inst(display_name=HOST, uuid=FAKEUUID) db.instance_get_by_uuid(self.context, mox.IgnoreArg(), use_slave=False, columns_to_join=['info_cache', 'security_groups'] ).AndReturn(inst) db.network_get(mox.IgnoreArg(), mox.IgnoreArg(), project_only=mox.IgnoreArg() ).AndReturn(dict(test_network.fake_network, **networks[0])) db.network_update(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.network.get_instance_nw_info(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.mox.ReplayAll() self.network.add_fixed_ip_to_instance(self.context, FAKEUUID, HOST, networks[0]['id']) exp_project, exp_user = quotas_obj.ids_from_instance(self.context, inst) reserve.assert_called_once_with(self.context, fixed_ips=1, project_id=exp_project, user_id=exp_user) @mock.patch('nova.objects.quotas.Quotas.reserve') def test_add_fixed_ip_instance_using_uuid_without_vpn(self, reserve): self.stubs.Set(self.network, '_do_trigger_security_group_members_refresh_for_instance', lambda *a, **kw: None) self.mox.StubOutWithMock(db, 'network_get_by_uuid') self.mox.StubOutWithMock(db, 'network_update') self.mox.StubOutWithMock(db, 'fixed_ip_associate_pool') self.mox.StubOutWithMock(db, 'virtual_interface_get_by_instance_and_network') self.mox.StubOutWithMock(db, 'fixed_ip_update') self.mox.StubOutWithMock(db, 'instance_get_by_uuid') self.mox.StubOutWithMock(self.network, 'get_instance_nw_info') fixed = dict(test_fixed_ip.fake_fixed_ip, address='192.168.0.101') db.fixed_ip_associate_pool(mox.IgnoreArg(), mox.IgnoreArg(), instance_uuid=mox.IgnoreArg(), host=None).AndReturn(fixed) db.virtual_interface_get_by_instance_and_network(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(vifs[0]) db.fixed_ip_update(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) inst = fake_inst(display_name=HOST, uuid=FAKEUUID) db.instance_get_by_uuid(self.context, mox.IgnoreArg(), use_slave=False, columns_to_join=['info_cache', 'security_groups'] ).AndReturn(inst) db.network_get_by_uuid(mox.IgnoreArg(), mox.IgnoreArg() ).AndReturn(dict(test_network.fake_network, **networks[0])) db.network_update(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.network.get_instance_nw_info(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.mox.ReplayAll() self.network.add_fixed_ip_to_instance(self.context, FAKEUUID, HOST, networks[0]['uuid']) exp_project, exp_user = quotas_obj.ids_from_instance(self.context, inst) reserve.assert_called_once_with(self.context, fixed_ips=1, project_id=exp_project, user_id=exp_user) def test_mini_dns_driver(self): zone1 = "example.org" zone2 = "example.com" driver = self.network.instance_dns_manager driver.create_entry("hostone", "10.0.0.1", "A", zone1) driver.create_entry("hosttwo", "10.0.0.2", "A", zone1) driver.create_entry("hostthree", "10.0.0.3", "A", zone1) driver.create_entry("hostfour", "10.0.0.4", "A", zone1) driver.create_entry("hostfive", "10.0.0.5", "A", zone2) driver.delete_entry("hostone", zone1) driver.modify_address("hostfour", "10.0.0.1", zone1) driver.modify_address("hostthree", "10.0.0.1", zone1) names = driver.get_entries_by_address("10.0.0.1", zone1) self.assertEqual(len(names), 2) self.assertIn('hostthree', names) self.assertIn('hostfour', names) names = driver.get_entries_by_address("10.0.0.5", zone2) self.assertEqual(len(names), 1) self.assertIn('hostfive', names) addresses = driver.get_entries_by_name("hosttwo", zone1) self.assertEqual(len(addresses), 1) self.assertIn('10.0.0.2', addresses) self.assertRaises(exception.InvalidInput, driver.create_entry, "hostname", "10.10.10.10", "invalidtype", zone1) def test_mini_dns_driver_with_mixed_case(self): zone1 = "example.org" driver = self.network.instance_dns_manager driver.create_entry("HostTen", "10.0.0.10", "A", zone1) addresses = driver.get_entries_by_address("10.0.0.10", zone1) self.assertEqual(len(addresses), 1) for n in addresses: driver.delete_entry(n, zone1) addresses = driver.get_entries_by_address("10.0.0.10", zone1) self.assertEqual(len(addresses), 0) @mock.patch('nova.objects.quotas.Quotas.reserve') def test_instance_dns(self, reserve): self.stubs.Set(self.network, '_do_trigger_security_group_members_refresh_for_instance', lambda *a, **kw: None) fixedip = dict(test_fixed_ip.fake_fixed_ip, address='192.168.0.101') self.mox.StubOutWithMock(db, 'network_get_by_uuid') self.mox.StubOutWithMock(db, 'network_update') self.mox.StubOutWithMock(db, 'fixed_ip_associate_pool') self.mox.StubOutWithMock(db, 'virtual_interface_get_by_instance_and_network') self.mox.StubOutWithMock(db, 'fixed_ip_update') self.mox.StubOutWithMock(db, 'instance_get_by_uuid') self.mox.StubOutWithMock(self.network, 'get_instance_nw_info') db.fixed_ip_associate_pool(mox.IgnoreArg(), mox.IgnoreArg(), instance_uuid=mox.IgnoreArg(), host=None ).AndReturn(fixedip) db.virtual_interface_get_by_instance_and_network(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(vifs[0]) db.fixed_ip_update(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) inst = fake_inst(display_name=HOST, uuid=FAKEUUID) db.instance_get_by_uuid(self.context, mox.IgnoreArg(), use_slave=False, columns_to_join=['info_cache', 'security_groups'] ).AndReturn(inst) db.network_get_by_uuid(mox.IgnoreArg(), mox.IgnoreArg() ).AndReturn(dict(test_network.fake_network, **networks[0])) db.network_update(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.network.get_instance_nw_info(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.mox.ReplayAll() self.network.add_fixed_ip_to_instance(self.context, FAKEUUID, HOST, networks[0]['uuid']) instance_manager = self.network.instance_dns_manager addresses = instance_manager.get_entries_by_name(HOST, self.network.instance_dns_domain) self.assertEqual(len(addresses), 1) self.assertEqual(addresses[0], fixedip['address']) addresses = instance_manager.get_entries_by_name(FAKEUUID, self.network.instance_dns_domain) self.assertEqual(len(addresses), 1) self.assertEqual(addresses[0], fixedip['address']) exp_project, exp_user = quotas_obj.ids_from_instance(self.context, inst) reserve.assert_called_once_with(self.context, fixed_ips=1, project_id=exp_project, user_id=exp_user) def test_allocate_floating_ip(self): self.assertIsNone(self.network.allocate_floating_ip(self.context, 1, None)) def test_deallocate_floating_ip(self): self.assertIsNone(self.network.deallocate_floating_ip(self.context, 1, None)) def test_associate_floating_ip(self): self.assertIsNone(self.network.associate_floating_ip(self.context, None, None)) def test_disassociate_floating_ip(self): self.assertIsNone(self.network.disassociate_floating_ip(self.context, None, None)) def test_get_networks_by_uuids_ordering(self): self.mox.StubOutWithMock(db, 'network_get_all_by_uuids') requested_networks = ['bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'] db.network_get_all_by_uuids(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( [dict(test_network.fake_network, **net) for net in networks]) self.mox.ReplayAll() res = self.network._get_networks_by_uuids(self.context, requested_networks) self.assertEqual(res[0]['id'], 1) self.assertEqual(res[1]['id'], 0) @mock.patch('nova.objects.instance.Instance.get_by_uuid') @mock.patch('nova.objects.quotas.Quotas.reserve') @mock.patch('nova.objects.quotas.ids_from_instance') def test_allocate_calculates_quota_auth(self, util_method, reserve, get_by_uuid): inst = instance_obj.Instance() get_by_uuid.return_value = inst reserve.side_effect = exception.OverQuota(overs='testing') util_method.return_value = ('foo', 'bar') self.assertRaises(exception.FixedIpLimitExceeded, self.network.allocate_fixed_ip, self.context, 123, None) util_method.assert_called_once_with(self.context, inst) @mock.patch('nova.objects.fixed_ip.FixedIP.get_by_address') @mock.patch('nova.objects.quotas.Quotas.reserve') @mock.patch('nova.objects.quotas.ids_from_instance') def test_deallocate_calculates_quota_auth(self, util_method, reserve, get_by_address): inst = instance_obj.Instance(uuid='fake-uuid') fip = fixed_ip_obj.FixedIP(instance_uuid='fake-uuid', virtual_interface_id=1) get_by_address.return_value = fip util_method.return_value = ('foo', 'bar') # This will fail right after the reserve call when it tries # to look up the fake instance we created above self.assertRaises(exception.InstanceNotFound, self.network.deallocate_fixed_ip, self.context, '1.2.3.4', instance=inst) util_method.assert_called_once_with(self.context, inst) class VlanNetworkTestCase(test.TestCase): def setUp(self): super(VlanNetworkTestCase, self).setUp() self.useFixture(test.SampleNetworks()) self.flags(use_local=True, group='conductor') self.network = network_manager.VlanManager(host=HOST) self.network.db = db self.context = context.RequestContext('testuser', 'testproject', is_admin=False) self.context_admin = context.RequestContext('testuser', 'testproject', is_admin=True) def test_quota_driver_type(self): self.assertEqual(quotas_obj.QuotasNoOp, self.network.quotas_cls) def test_vpn_allocate_fixed_ip(self): self.mox.StubOutWithMock(db, 'fixed_ip_associate') self.mox.StubOutWithMock(db, 'fixed_ip_update') self.mox.StubOutWithMock(db, 'virtual_interface_get_by_instance_and_network') self.mox.StubOutWithMock(db, 'instance_get_by_uuid') fixed = dict(test_fixed_ip.fake_fixed_ip, address='192.168.0.1') db.fixed_ip_associate(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), network_id=mox.IgnoreArg(), reserved=True).AndReturn(fixed) db.fixed_ip_update(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) db.virtual_interface_get_by_instance_and_network(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(vifs[0]) db.instance_get_by_uuid(mox.IgnoreArg(), mox.IgnoreArg(), use_slave=False, columns_to_join=['info_cache', 'security_groups'] ).AndReturn(fake_inst(display_name=HOST, uuid=FAKEUUID)) self.mox.ReplayAll() network = network_obj.Network._from_db_object( self.context, network_obj.Network(), dict(test_network.fake_network, **networks[0])) network.vpn_private_address = '192.168.0.2' self.network.allocate_fixed_ip(self.context, FAKEUUID, network, vpn=True) def test_vpn_allocate_fixed_ip_no_network_id(self): network = dict(networks[0]) network['vpn_private_address'] = '192.168.0.2' network['id'] = None instance = db.instance_create(self.context, {}) self.assertRaises(exception.FixedIpNotFoundForNetwork, self.network.allocate_fixed_ip, self.context_admin, instance['uuid'], network, vpn=True) def test_allocate_fixed_ip(self): self.stubs.Set(self.network, '_do_trigger_security_group_members_refresh_for_instance', lambda *a, **kw: None) self.mox.StubOutWithMock(db, 'fixed_ip_associate_pool') self.mox.StubOutWithMock(db, 'fixed_ip_update') self.mox.StubOutWithMock(db, 'virtual_interface_get_by_instance_and_network') self.mox.StubOutWithMock(db, 'instance_get_by_uuid') fixed = dict(test_fixed_ip.fake_fixed_ip, address='192.168.0.1') db.fixed_ip_associate_pool(mox.IgnoreArg(), mox.IgnoreArg(), instance_uuid=mox.IgnoreArg(), host=None).AndReturn(fixed) db.fixed_ip_update(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) db.virtual_interface_get_by_instance_and_network(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(vifs[0]) db.instance_get_by_uuid(mox.IgnoreArg(), mox.IgnoreArg(), use_slave=False, columns_to_join=['info_cache', 'security_groups'] ).AndReturn(fake_inst(display_name=HOST, uuid=FAKEUUID)) self.mox.ReplayAll() network = network_obj.Network._from_db_object( self.context, network_obj.Network(), dict(test_network.fake_network, **networks[0])) network.vpn_private_address = '192.168.0.2' self.network.allocate_fixed_ip(self.context, FAKEUUID, network) def test_create_networks_too_big(self): self.assertRaises(ValueError, self.network.create_networks, None, num_networks=4094, vlan_start=1) def test_create_networks_too_many(self): self.assertRaises(ValueError, self.network.create_networks, None, num_networks=100, vlan_start=1, cidr='192.168.0.1/24', network_size=100) def test_duplicate_vlan_raises(self): # VLAN 100 is already used and we force the network to be created # in that vlan (vlan=100). self.assertRaises(exception.DuplicateVlan, self.network.create_networks, self.context_admin, label="fake", num_networks=1, vlan=100, cidr='192.168.0.1/24', network_size=100) def test_vlan_start(self): # VLAN 100 and 101 are used, so this network shoud be created in 102 networks = self.network.create_networks( self.context_admin, label="fake", num_networks=1, vlan_start=100, cidr='192.168.3.1/24', network_size=100) self.assertEqual(networks[0]["vlan"], 102) def test_vlan_start_multiple(self): # VLAN 100 and 101 are used, so these networks shoud be created in 102 # and 103 networks = self.network.create_networks( self.context_admin, label="fake", num_networks=2, vlan_start=100, cidr='192.168.3.1/24', network_size=100) self.assertEqual(networks[0]["vlan"], 102) self.assertEqual(networks[1]["vlan"], 103) def test_vlan_start_used(self): # VLAN 100 and 101 are used, but vlan_start=99. networks = self.network.create_networks( self.context_admin, label="fake", num_networks=1, vlan_start=99, cidr='192.168.3.1/24', network_size=100) self.assertEqual(networks[0]["vlan"], 102) @mock.patch('nova.db.network_get') def test_validate_networks(self, net_get): def network_get(_context, network_id, project_only='allow_none'): return dict(test_network.fake_network, **networks[network_id]) net_get.side_effect = network_get self.mox.StubOutWithMock(db, 'network_get_all_by_uuids') self.mox.StubOutWithMock(db, "fixed_ip_get_by_address") requested_networks = [('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '192.168.1.100'), ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '192.168.0.100')] db.network_get_all_by_uuids(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( [dict(test_network.fake_network, **net) for net in networks]) db_fixed1 = dict(test_fixed_ip.fake_fixed_ip, network_id=networks[1]['id'], network=dict(test_network.fake_network, **networks[1]), instance_uuid=None) db.fixed_ip_get_by_address(mox.IgnoreArg(), mox.IgnoreArg(), columns_to_join=mox.IgnoreArg() ).AndReturn(db_fixed1) db_fixed2 = dict(test_fixed_ip.fake_fixed_ip, network_id=networks[0]['id'], network=dict(test_network.fake_network, **networks[0]), instance_uuid=None) db.fixed_ip_get_by_address(mox.IgnoreArg(), mox.IgnoreArg(), columns_to_join=mox.IgnoreArg() ).AndReturn(db_fixed2) self.mox.ReplayAll() self.network.validate_networks(self.context, requested_networks) def test_validate_networks_none_requested_networks(self): self.network.validate_networks(self.context, None) def test_validate_networks_empty_requested_networks(self): requested_networks = [] self.mox.ReplayAll() self.network.validate_networks(self.context, requested_networks) def test_validate_networks_invalid_fixed_ip(self): self.mox.StubOutWithMock(db, 'network_get_all_by_uuids') requested_networks = [('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '192.168.1.100.1'), ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '192.168.0.100.1')] db.network_get_all_by_uuids(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( [dict(test_network.fake_network, **net) for net in networks]) self.mox.ReplayAll() self.assertRaises(exception.FixedIpInvalid, self.network.validate_networks, self.context, requested_networks) def test_validate_networks_empty_fixed_ip(self): self.mox.StubOutWithMock(db, 'network_get_all_by_uuids') requested_networks = [('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', ''), ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '')] db.network_get_all_by_uuids(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( [dict(test_network.fake_network, **net) for net in networks]) self.mox.ReplayAll() self.assertRaises(exception.FixedIpInvalid, self.network.validate_networks, self.context, requested_networks) def test_validate_networks_none_fixed_ip(self): self.mox.StubOutWithMock(db, 'network_get_all_by_uuids') requested_networks = [('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', None), ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', None)] db.network_get_all_by_uuids(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( [dict(test_network.fake_network, **net) for net in networks]) self.mox.ReplayAll() self.network.validate_networks(self.context, requested_networks) def test_floating_ip_owned_by_project(self): ctxt = context.RequestContext('testuser', 'testproject', is_admin=False) # raises because floating_ip project_id is None floating_ip = floating_ip_obj.FloatingIP(address='10.0.0.1', project_id=None) self.assertRaises(exception.Forbidden, self.network._floating_ip_owned_by_project, ctxt, floating_ip) # raises because floating_ip project_id is not equal to ctxt project_id floating_ip = floating_ip_obj.FloatingIP( address='10.0.0.1', project_id=ctxt.project_id + '1') self.assertRaises(exception.Forbidden, self.network._floating_ip_owned_by_project, ctxt, floating_ip) # does not raise (floating ip is owned by ctxt project) floating_ip = floating_ip_obj.FloatingIP(address='10.0.0.1', project_id=ctxt.project_id) self.network._floating_ip_owned_by_project(ctxt, floating_ip) ctxt = context.RequestContext(None, None, is_admin=True) # does not raise (ctxt is admin) floating_ip = floating_ip_obj.FloatingIP(address='10.0.0.1', project_id=None) self.network._floating_ip_owned_by_project(ctxt, floating_ip) # does not raise (ctxt is admin) floating_ip = floating_ip_obj.FloatingIP(address='10.0.0.1', project_id='testproject') self.network._floating_ip_owned_by_project(ctxt, floating_ip) def test_allocate_floating_ip(self): ctxt = context.RequestContext('testuser', 'testproject', is_admin=False) def fake_allocate_address(*args, **kwargs): return {'address': '10.0.0.1', 'project_id': ctxt.project_id} self.stubs.Set(self.network.db, 'floating_ip_allocate_address', fake_allocate_address) self.network.allocate_floating_ip(ctxt, ctxt.project_id) def test_deallocate_floating_ip(self): ctxt = context.RequestContext('testuser', 'testproject', is_admin=False) def fake1(*args, **kwargs): pass def fake2(*args, **kwargs): return dict(test_floating_ip.fake_floating_ip, address='10.0.0.1', fixed_ip_id=1) def fake3(*args, **kwargs): return dict(test_floating_ip.fake_floating_ip, address='10.0.0.1', fixed_ip_id=None, project_id=ctxt.project_id) self.stubs.Set(self.network.db, 'floating_ip_deallocate', fake1) self.stubs.Set(self.network, '_floating_ip_owned_by_project', fake1) # this time should raise because floating ip is associated to fixed_ip self.stubs.Set(self.network.db, 'floating_ip_get_by_address', fake2) self.assertRaises(exception.FloatingIpAssociated, self.network.deallocate_floating_ip, ctxt, mox.IgnoreArg()) # this time should not raise self.stubs.Set(self.network.db, 'floating_ip_get_by_address', fake3) self.network.deallocate_floating_ip(ctxt, ctxt.project_id) @mock.patch('nova.db.fixed_ip_get') def test_associate_floating_ip(self, fixed_get): ctxt = context.RequestContext('testuser', 'testproject', is_admin=False) def fake1(*args, **kwargs): return dict(test_fixed_ip.fake_fixed_ip, address='10.0.0.1', network=test_network.fake_network) # floating ip that's already associated def fake2(*args, **kwargs): return dict(test_floating_ip.fake_floating_ip, address='10.0.0.1', pool='nova', interface='eth0', fixed_ip_id=1) # floating ip that isn't associated def fake3(*args, **kwargs): return dict(test_floating_ip.fake_floating_ip, address='10.0.0.1', pool='nova', interface='eth0', fixed_ip_id=None) # fixed ip with remote host def fake4(*args, **kwargs): return dict(test_fixed_ip.fake_fixed_ip, address='10.0.0.1', pool='nova', instance_uuid=FAKEUUID, interface='eth0', network_id=123) def fake4_network(*args, **kwargs): return dict(test_network.fake_network, multi_host=False, host='jibberjabber') # fixed ip with local host def fake5(*args, **kwargs): return dict(test_fixed_ip.fake_fixed_ip, address='10.0.0.1', pool='nova', instance_uuid=FAKEUUID, interface='eth0', network_id=1234) def fake5_network(*args, **kwargs): return dict(test_network.fake_network, multi_host=False, host='testhost') def fake6(ctxt, method, **kwargs): self.local = False def fake7(*args, **kwargs): self.local = True def fake8(*args, **kwargs): raise processutils.ProcessExecutionError('', 'Cannot find device "em0"\n') def fake9(*args, **kwargs): raise test.TestingException() # raises because interface doesn't exist self.stubs.Set(self.network.db, 'floating_ip_fixed_ip_associate', fake1) self.stubs.Set(self.network.db, 'floating_ip_disassociate', fake1) self.stubs.Set(self.network.driver, 'ensure_floating_forward', fake8) self.assertRaises(exception.NoFloatingIpInterface, self.network._associate_floating_ip, ctxt, '1.2.3.4', '1.2.3.5', mox.IgnoreArg(), mox.IgnoreArg()) self.stubs.Set(self.network, '_floating_ip_owned_by_project', fake1) # raises because floating_ip is already associated to a fixed_ip self.stubs.Set(self.network.db, 'floating_ip_get_by_address', fake2) self.stubs.Set(self.network, 'disassociate_floating_ip', fake9) fixed_get.return_value = dict(test_fixed_ip.fake_fixed_ip, address='1.2.3.4', instance_uuid='fake_uuid', network=test_network.fake_network) # doesn't raise because we exit early if the address is the same self.network.associate_floating_ip(ctxt, mox.IgnoreArg(), '1.2.3.4') # raises because we call disassociate which is mocked self.assertRaises(test.TestingException, self.network.associate_floating_ip, ctxt, mox.IgnoreArg(), 'new') self.stubs.Set(self.network.db, 'floating_ip_get_by_address', fake3) # does not raise and makes call remotely self.local = True self.stubs.Set(self.network.db, 'fixed_ip_get_by_address', fake4) self.stubs.Set(self.network.db, 'network_get', fake4_network) self.stubs.Set(self.network.network_rpcapi.client, 'prepare', lambda **kw: self.network.network_rpcapi.client) self.stubs.Set(self.network.network_rpcapi.client, 'call', fake6) self.network.associate_floating_ip(ctxt, mox.IgnoreArg(), mox.IgnoreArg()) self.assertFalse(self.local) # does not raise and makes call locally self.local = False self.stubs.Set(self.network.db, 'fixed_ip_get_by_address', fake5) self.stubs.Set(self.network.db, 'network_get', fake5_network) self.stubs.Set(self.network, '_associate_floating_ip', fake7) self.network.associate_floating_ip(ctxt, mox.IgnoreArg(), mox.IgnoreArg()) self.assertTrue(self.local) def test_add_floating_ip_nat_before_bind(self): # Tried to verify order with documented mox record/verify # functionality, but it doesn't seem to work since I can't make it # fail. I'm using stubs and a flag for now, but if this mox feature # can be made to work, it would be a better way to test this. # # self.mox.StubOutWithMock(self.network.driver, # 'ensure_floating_forward') # self.mox.StubOutWithMock(self.network.driver, 'bind_floating_ip') # # self.network.driver.ensure_floating_forward(mox.IgnoreArg(), # mox.IgnoreArg(), # mox.IgnoreArg(), # mox.IgnoreArg()) # self.network.driver.bind_floating_ip(mox.IgnoreArg(), # mox.IgnoreArg()) # self.mox.ReplayAll() nat_called = [False] def fake_nat(*args, **kwargs): nat_called[0] = True def fake_bind(*args, **kwargs): self.assertTrue(nat_called[0]) self.stubs.Set(self.network.driver, 'ensure_floating_forward', fake_nat) self.stubs.Set(self.network.driver, 'bind_floating_ip', fake_bind) self.network.l3driver.add_floating_ip('fakefloat', 'fakefixed', 'fakeiface', 'fakenet') @mock.patch('nova.db.floating_ip_get_all_by_host') @mock.patch('nova.db.fixed_ip_get') def _test_floating_ip_init_host(self, fixed_get, floating_get, public_interface, expected_arg): floating_get.return_value = [ dict(test_floating_ip.fake_floating_ip, interface='foo', address='1.2.3.4'), dict(test_floating_ip.fake_floating_ip, interface='fakeiface', address='1.2.3.5', fixed_ip_id=1), dict(test_floating_ip.fake_floating_ip, interface='bar', address='1.2.3.6', fixed_ip_id=2), ] def fixed_ip_get(_context, fixed_ip_id, get_network): if fixed_ip_id == 1: return dict(test_fixed_ip.fake_fixed_ip, address='1.2.3.4', network=test_network.fake_network) raise exception.FixedIpNotFound(id=fixed_ip_id) fixed_get.side_effect = fixed_ip_get self.mox.StubOutWithMock(self.network.l3driver, 'add_floating_ip') self.flags(public_interface=public_interface) self.network.l3driver.add_floating_ip(netaddr.IPAddress('1.2.3.5'), netaddr.IPAddress('1.2.3.4'), expected_arg, mox.IsA(network_obj.Network)) self.mox.ReplayAll() self.network.init_host_floating_ips() self.mox.UnsetStubs() self.mox.VerifyAll() def test_floating_ip_init_host_without_public_interface(self): self._test_floating_ip_init_host(public_interface=False, expected_arg='fakeiface') def test_floating_ip_init_host_with_public_interface(self): self._test_floating_ip_init_host(public_interface='fooiface', expected_arg='fooiface') def test_disassociate_floating_ip(self): ctxt = context.RequestContext('testuser', 'testproject', is_admin=False) def fake1(*args, **kwargs): pass # floating ip that isn't associated def fake2(*args, **kwargs): return dict(test_floating_ip.fake_floating_ip, address='10.0.0.1', pool='nova', interface='eth0', fixed_ip_id=None) # floating ip that is associated def fake3(*args, **kwargs): return dict(test_floating_ip.fake_floating_ip, address='10.0.0.1', pool='nova', interface='eth0', fixed_ip_id=1, project_id=ctxt.project_id) # fixed ip with remote host def fake4(*args, **kwargs): return dict(test_fixed_ip.fake_fixed_ip, address='10.0.0.1', pool='nova', instance_uuid=FAKEUUID, interface='eth0', network_id=123) def fake4_network(*args, **kwargs): return dict(test_network.fake_network, multi_host=False, host='jibberjabber') # fixed ip with local host def fake5(*args, **kwargs): return dict(test_fixed_ip.fake_fixed_ip, address='10.0.0.1', pool='nova', instance_uuid=FAKEUUID, interface='eth0', network_id=1234) def fake5_network(*args, **kwargs): return dict(test_network.fake_network, multi_host=False, host='testhost') def fake6(ctxt, method, **kwargs): self.local = False def fake7(*args, **kwargs): self.local = True def fake8(*args, **kwargs): return dict(test_floating_ip.fake_floating_ip, address='10.0.0.1', pool='nova', interface='eth0', fixed_ip_id=1, auto_assigned=True, project_id=ctxt.project_id) self.stubs.Set(self.network, '_floating_ip_owned_by_project', fake1) # raises because floating_ip is not associated to a fixed_ip self.stubs.Set(self.network.db, 'floating_ip_get_by_address', fake2) self.assertRaises(exception.FloatingIpNotAssociated, self.network.disassociate_floating_ip, ctxt, mox.IgnoreArg()) self.stubs.Set(self.network.db, 'floating_ip_get_by_address', fake3) # does not raise and makes call remotely self.local = True self.stubs.Set(self.network.db, 'fixed_ip_get', fake4) self.stubs.Set(self.network.db, 'network_get', fake4_network) self.stubs.Set(self.network.network_rpcapi.client, 'prepare', lambda **kw: self.network.network_rpcapi.client) self.stubs.Set(self.network.network_rpcapi.client, 'call', fake6) self.network.disassociate_floating_ip(ctxt, mox.IgnoreArg()) self.assertFalse(self.local) # does not raise and makes call locally self.local = False self.stubs.Set(self.network.db, 'fixed_ip_get', fake5) self.stubs.Set(self.network.db, 'network_get', fake5_network) self.stubs.Set(self.network, '_disassociate_floating_ip', fake7) self.network.disassociate_floating_ip(ctxt, mox.IgnoreArg()) self.assertTrue(self.local) # raises because auto_assigned floating IP cannot be disassociated self.stubs.Set(self.network.db, 'floating_ip_get_by_address', fake8) self.assertRaises(exception.CannotDisassociateAutoAssignedFloatingIP, self.network.disassociate_floating_ip, ctxt, mox.IgnoreArg()) def test_add_fixed_ip_instance_without_vpn_requested_networks(self): self.stubs.Set(self.network, '_do_trigger_security_group_members_refresh_for_instance', lambda *a, **kw: None) self.mox.StubOutWithMock(db, 'network_get') self.mox.StubOutWithMock(db, 'fixed_ip_associate_pool') self.mox.StubOutWithMock(db, 'virtual_interface_get_by_instance_and_network') self.mox.StubOutWithMock(db, 'fixed_ip_update') self.mox.StubOutWithMock(db, 'instance_get_by_uuid') self.mox.StubOutWithMock(self.network, 'get_instance_nw_info') db.fixed_ip_update(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) db.virtual_interface_get_by_instance_and_network(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(vifs[0]) fixed = dict(test_fixed_ip.fake_fixed_ip, address='192.168.0.101') db.fixed_ip_associate_pool(mox.IgnoreArg(), mox.IgnoreArg(), instance_uuid=mox.IgnoreArg(), host=None).AndReturn(fixed) db.network_get(mox.IgnoreArg(), mox.IgnoreArg(), project_only=mox.IgnoreArg() ).AndReturn(dict(test_network.fake_network, **networks[0])) db.instance_get_by_uuid(mox.IgnoreArg(), mox.IgnoreArg(), use_slave=False, columns_to_join=['info_cache', 'security_groups'] ).AndReturn(fake_inst(display_name=HOST, uuid=FAKEUUID)) self.network.get_instance_nw_info(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.mox.ReplayAll() self.network.add_fixed_ip_to_instance(self.context, FAKEUUID, HOST, networks[0]['id']) @mock.patch('nova.db.fixed_ip_get_by_address') @mock.patch('nova.db.network_get') def test_ip_association_and_allocation_of_other_project(self, net_get, fixed_get): """Makes sure that we cannot deallocaate or disassociate a public ip of other project. """ net_get.return_value = dict(test_network.fake_network, **networks[1]) context1 = context.RequestContext('user', 'project1') context2 = context.RequestContext('user', 'project2') float_ip = db.floating_ip_create(context1.elevated(), {'address': '1.2.3.4', 'project_id': context1.project_id}) float_addr = float_ip['address'] instance = db.instance_create(context1, {'project_id': 'project1'}) fix_addr = db.fixed_ip_associate_pool(context1.elevated(), 1, instance['uuid']).address fixed_get.return_value = dict(test_fixed_ip.fake_fixed_ip, address=fix_addr, instance_uuid=instance.uuid, network=dict(test_network.fake_network, **networks[1])) # Associate the IP with non-admin user context self.assertRaises(exception.Forbidden, self.network.associate_floating_ip, context2, float_addr, fix_addr) # Deallocate address from other project self.assertRaises(exception.Forbidden, self.network.deallocate_floating_ip, context2, float_addr) # Now Associates the address to the actual project self.network.associate_floating_ip(context1, float_addr, fix_addr) # Now try dis-associating from other project self.assertRaises(exception.Forbidden, self.network.disassociate_floating_ip, context2, float_addr) # Clean up the ip addresses self.network.disassociate_floating_ip(context1, float_addr) self.network.deallocate_floating_ip(context1, float_addr) self.network.deallocate_fixed_ip(context1, fix_addr, 'fake') db.floating_ip_destroy(context1.elevated(), float_addr) db.fixed_ip_disassociate(context1.elevated(), fix_addr) @mock.patch('nova.db.fixed_ip_get_by_address') @mock.patch('nova.db.network_get') @mock.patch('nova.db.fixed_ip_update') def test_deallocate_fixed(self, fixed_update, net_get, fixed_get): """Verify that release is called properly. Ensures https://bugs.launchpad.net/nova/+bug/973442 doesn't return """ net_get.return_value = dict(test_network.fake_network, **networks[1]) def vif_get(_context, _vif_id): return vifs[0] self.stubs.Set(db, 'virtual_interface_get', vif_get) context1 = context.RequestContext('user', 'project1') instance = db.instance_create(context1, {'project_id': 'project1'}) elevated = context1.elevated() fix_addr = db.fixed_ip_associate_pool(elevated, 1, instance['uuid']) fixed_get.return_value = dict(test_fixed_ip.fake_fixed_ip, address=fix_addr.address, instance_uuid=instance.uuid, allocated=True, virtual_interface_id=3, network=dict(test_network.fake_network, **networks[1])) self.flags(force_dhcp_release=True) self.mox.StubOutWithMock(linux_net, 'release_dhcp') linux_net.release_dhcp(networks[1]['bridge'], fix_addr.address, 'DE:AD:BE:EF:00:00') self.mox.ReplayAll() self.network.deallocate_fixed_ip(context1, fix_addr.address, 'fake') fixed_update.assert_called_once_with(context1, fix_addr.address, {'allocated': False, 'virtual_interface_id': None}) def test_deallocate_fixed_deleted(self): # Verify doesn't deallocate deleted fixed_ip from deleted network. def teardown_network_on_host(_context, network): if network['id'] == 0: raise test.TestingException() self.stubs.Set(self.network, '_teardown_network_on_host', teardown_network_on_host) context1 = context.RequestContext('user', 'project1') elevated = context1.elevated() instance = db.instance_create(context1, {'project_id': 'project1'}) network = db.network_create_safe(elevated, networks[0]) _fix_addr = db.fixed_ip_associate_pool(elevated, 1, instance['uuid']) fix_addr = _fix_addr.address db.fixed_ip_update(elevated, fix_addr, {'deleted': 1}) elevated.read_deleted = 'yes' delfixed = db.fixed_ip_get_by_address(elevated, fix_addr) values = {'address': fix_addr, 'network_id': network.id, 'instance_uuid': delfixed['instance_uuid']} db.fixed_ip_create(elevated, values) elevated.read_deleted = 'no' elevated.read_deleted = 'yes' deallocate = self.network.deallocate_fixed_ip self.assertRaises(test.TestingException, deallocate, context1, fix_addr, 'fake') @mock.patch('nova.db.fixed_ip_get_by_address') @mock.patch('nova.db.network_get') @mock.patch('nova.db.fixed_ip_update') def test_deallocate_fixed_no_vif(self, fixed_update, net_get, fixed_get): """Verify that deallocate doesn't raise when no vif is returned. Ensures https://bugs.launchpad.net/nova/+bug/968457 doesn't return """ net_get.return_value = dict(test_network.fake_network, **networks[1]) def vif_get(_context, _vif_id): return None self.stubs.Set(db, 'virtual_interface_get', vif_get) context1 = context.RequestContext('user', 'project1') instance = db.instance_create(context1, {'project_id': 'project1'}) elevated = context1.elevated() fix_addr = db.fixed_ip_associate_pool(elevated, 1, instance['uuid']) fixed_get.return_value = dict(test_fixed_ip.fake_fixed_ip, address=fix_addr.address, allocated=True, virtual_interface_id=3, instance_uuid=instance.uuid, network=dict(test_network.fake_network, **networks[1])) self.flags(force_dhcp_release=True) fixed_update.return_value = fixed_get.return_value self.network.deallocate_fixed_ip(context1, fix_addr.address, 'fake') fixed_update.assert_called_once_with(context1, fix_addr.address, {'allocated': False, 'virtual_interface_id': None}) @mock.patch('nova.db.fixed_ip_get_by_address') @mock.patch('nova.db.network_get') @mock.patch('nova.db.fixed_ip_update') def test_fixed_ip_cleanup_fail(self, fixed_update, net_get, fixed_get): # Verify IP is not deallocated if the security group refresh fails. net_get.return_value = dict(test_network.fake_network, **networks[1]) context1 = context.RequestContext('user', 'project1') instance = db.instance_create(context1, {'project_id': 'project1'}) elevated = context1.elevated() fix_addr = fixed_ip_obj.FixedIP.associate_pool(elevated, 1, instance['uuid']) def fake_refresh(instance_uuid): raise test.TestingException() self.stubs.Set(self.network, '_do_trigger_security_group_members_refresh_for_instance', fake_refresh) fixed_get.return_value = dict(test_fixed_ip.fake_fixed_ip, address=fix_addr.address, allocated=True, virtual_interface_id=3, instance_uuid=instance.uuid, network=dict(test_network.fake_network, **networks[1])) self.assertRaises(test.TestingException, self.network.deallocate_fixed_ip, context1, str(fix_addr.address), 'fake') self.assertFalse(fixed_update.called) def test_get_networks_by_uuids_ordering(self): self.mox.StubOutWithMock(db, 'network_get_all_by_uuids') requested_networks = ['bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'] db.network_get_all_by_uuids(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( [dict(test_network.fake_network, **net) for net in networks]) self.mox.ReplayAll() res = self.network._get_networks_by_uuids(self.context, requested_networks) self.assertEqual(res[0]['id'], 1) self.assertEqual(res[1]['id'], 0) class _TestDomainObject(object): def __init__(self, **kwargs): for k, v in kwargs.iteritems(): self.__setattr__(k, v) class FakeNetwork(object): def __init__(self, **kwargs): self.vlan = None for k, v in kwargs.iteritems(): self.__setattr__(k, v) def __getitem__(self, item): return getattr(self, item) class CommonNetworkTestCase(test.TestCase): def setUp(self): super(CommonNetworkTestCase, self).setUp() self.context = context.RequestContext('fake', 'fake') self.flags(ipv6_backend='rfc2462') self.flags(use_local=True, group='conductor') ipv6.reset_backend() def test_validate_instance_zone_for_dns_domain(self): domain = 'example.com' az = 'test_az' domains = { domain: _TestDomainObject( domain=domain, availability_zone=az)} def dnsdomain_get(context, instance_domain): return domains.get(instance_domain) self.stubs.Set(db, 'dnsdomain_get', dnsdomain_get) fake_instance = {'uuid': FAKEUUID, 'availability_zone': az} manager = network_manager.NetworkManager() res = manager._validate_instance_zone_for_dns_domain(self.context, fake_instance) self.assertTrue(res) def fake_create_fixed_ips(self, context, network_id, fixed_cidr=None): return None def test_get_instance_nw_info_client_exceptions(self): manager = network_manager.NetworkManager() self.mox.StubOutWithMock(manager.db, 'virtual_interface_get_by_instance') manager.db.virtual_interface_get_by_instance( self.context, FAKEUUID, use_slave=False).AndRaise(exception.InstanceNotFound( instance_id=FAKEUUID)) self.mox.ReplayAll() self.assertRaises(messaging.ExpectedException, manager.get_instance_nw_info, self.context, FAKEUUID, 'fake_rxtx_factor', HOST) @mock.patch('nova.db.instance_get') @mock.patch('nova.db.fixed_ip_get_by_instance') def test_deallocate_for_instance_passes_host_info(self, fixed_get, instance_get): manager = fake_network.FakeNetworkManager() db = manager.db instance_get.return_value = fake_inst(uuid='ignoreduuid') db.virtual_interface_delete_by_instance = lambda _x, _y: None ctx = context.RequestContext('igonre', 'igonre') fixed_get.return_value = [dict(test_fixed_ip.fake_fixed_ip, address='1.2.3.4', network_id=123)] manager.deallocate_for_instance( ctx, instance=instance_obj.Instance._from_db_object(self.context, instance_obj.Instance(), instance_get.return_value)) self.assertEqual([ (ctx, '1.2.3.4', 'fake-host') ], manager.deallocate_fixed_ip_calls) @mock.patch('nova.db.fixed_ip_get_by_instance') @mock.patch('nova.db.fixed_ip_disassociate') def test_remove_fixed_ip_from_instance(self, disassociate, get): manager = fake_network.FakeNetworkManager() get.return_value = [ dict(test_fixed_ip.fake_fixed_ip, **x) for x in manager.db.fixed_ip_get_by_instance(None, FAKEUUID)] manager.remove_fixed_ip_from_instance(self.context, FAKEUUID, HOST, '10.0.0.1') self.assertEqual(manager.deallocate_called, '10.0.0.1') disassociate.assert_called_once_with(self.context, '10.0.0.1') @mock.patch('nova.db.fixed_ip_get_by_instance') def test_remove_fixed_ip_from_instance_bad_input(self, get): manager = fake_network.FakeNetworkManager() get.return_value = [] self.assertRaises(exception.FixedIpNotFoundForSpecificInstance, manager.remove_fixed_ip_from_instance, self.context, 99, HOST, 'bad input') def test_validate_cidrs(self): manager = fake_network.FakeNetworkManager() nets = manager.create_networks(self.context.elevated(), 'fake', '192.168.0.0/24', False, 1, 256, None, None, None, None, None) self.assertEqual(1, len(nets)) cidrs = [str(net['cidr']) for net in nets] self.assertIn('192.168.0.0/24', cidrs) def test_validate_cidrs_split_exact_in_half(self): manager = fake_network.FakeNetworkManager() nets = manager.create_networks(self.context.elevated(), 'fake', '192.168.0.0/24', False, 2, 128, None, None, None, None, None) self.assertEqual(2, len(nets)) cidrs = [str(net['cidr']) for net in nets] self.assertIn('192.168.0.0/25', cidrs) self.assertIn('192.168.0.128/25', cidrs) @mock.patch('nova.db.network_get_all') def test_validate_cidrs_split_cidr_in_use_middle_of_range(self, get_all): manager = fake_network.FakeNetworkManager() get_all.return_value = [dict(test_network.fake_network, id=1, cidr='192.168.2.0/24')] nets = manager.create_networks(self.context.elevated(), 'fake', '192.168.0.0/16', False, 4, 256, None, None, None, None, None) self.assertEqual(4, len(nets)) cidrs = [str(net['cidr']) for net in nets] exp_cidrs = ['192.168.0.0/24', '192.168.1.0/24', '192.168.3.0/24', '192.168.4.0/24'] for exp_cidr in exp_cidrs: self.assertIn(exp_cidr, cidrs) self.assertNotIn('192.168.2.0/24', cidrs) @mock.patch('nova.db.network_get_all') def test_validate_cidrs_smaller_subnet_in_use(self, get_all): manager = fake_network.FakeNetworkManager() get_all.return_value = [dict(test_network.fake_network, id=1, cidr='192.168.2.9/25')] # CidrConflict: requested cidr (192.168.2.0/24) conflicts with # existing smaller cidr args = (self.context.elevated(), 'fake', '192.168.2.0/24', False, 1, 256, None, None, None, None, None) self.assertRaises(exception.CidrConflict, manager.create_networks, *args) @mock.patch('nova.db.network_get_all') def test_validate_cidrs_split_smaller_cidr_in_use(self, get_all): manager = fake_network.FakeNetworkManager() get_all.return_value = [dict(test_network.fake_network, id=1, cidr='192.168.2.0/25')] nets = manager.create_networks(self.context.elevated(), 'fake', '192.168.0.0/16', False, 4, 256, None, None, None, None, None) self.assertEqual(4, len(nets)) cidrs = [str(net['cidr']) for net in nets] exp_cidrs = ['192.168.0.0/24', '192.168.1.0/24', '192.168.3.0/24', '192.168.4.0/24'] for exp_cidr in exp_cidrs: self.assertIn(exp_cidr, cidrs) self.assertNotIn('192.168.2.0/24', cidrs) @mock.patch('nova.db.network_get_all') def test_validate_cidrs_split_smaller_cidr_in_use2(self, get_all): manager = fake_network.FakeNetworkManager() self.mox.StubOutWithMock(manager.db, 'network_get_all') get_all.return_value = [dict(test_network.fake_network, id=1, cidr='192.168.2.9/29')] nets = manager.create_networks(self.context.elevated(), 'fake', '192.168.2.0/24', False, 3, 32, None, None, None, None, None) self.assertEqual(3, len(nets)) cidrs = [str(net['cidr']) for net in nets] exp_cidrs = ['192.168.2.32/27', '192.168.2.64/27', '192.168.2.96/27'] for exp_cidr in exp_cidrs: self.assertIn(exp_cidr, cidrs) self.assertNotIn('192.168.2.0/27', cidrs) @mock.patch('nova.db.network_get_all') def test_validate_cidrs_split_all_in_use(self, get_all): manager = fake_network.FakeNetworkManager() in_use = [dict(test_network.fake_network, **values) for values in [{'id': 1, 'cidr': '192.168.2.9/29'}, {'id': 2, 'cidr': '192.168.2.64/26'}, {'id': 3, 'cidr': '192.168.2.128/26'}]] get_all.return_value = in_use args = (self.context.elevated(), 'fake', '192.168.2.0/24', False, 3, 64, None, None, None, None, None) # CidrConflict: Not enough subnets avail to satisfy requested num_ # networks - some subnets in requested range already # in use self.assertRaises(exception.CidrConflict, manager.create_networks, *args) def test_validate_cidrs_one_in_use(self): manager = fake_network.FakeNetworkManager() args = (None, 'fake', '192.168.0.0/24', False, 2, 256, None, None, None, None, None) # ValueError: network_size * num_networks exceeds cidr size self.assertRaises(ValueError, manager.create_networks, *args) @mock.patch('nova.db.network_get_all') def test_validate_cidrs_already_used(self, get_all): manager = fake_network.FakeNetworkManager() get_all.return_value = [dict(test_network.fake_network, cidr='192.168.0.0/24')] # CidrConflict: cidr already in use args = (self.context.elevated(), 'fake', '192.168.0.0/24', False, 1, 256, None, None, None, None, None) self.assertRaises(exception.CidrConflict, manager.create_networks, *args) def test_validate_cidrs_too_many(self): manager = fake_network.FakeNetworkManager() args = (None, 'fake', '192.168.0.0/24', False, 200, 256, None, None, None, None, None) # ValueError: Not enough subnets avail to satisfy requested # num_networks self.assertRaises(ValueError, manager.create_networks, *args) def test_validate_cidrs_split_partial(self): manager = fake_network.FakeNetworkManager() nets = manager.create_networks(self.context.elevated(), 'fake', '192.168.0.0/16', False, 2, 256, None, None, None, None, None) returned_cidrs = [str(net['cidr']) for net in nets] self.assertIn('192.168.0.0/24', returned_cidrs) self.assertIn('192.168.1.0/24', returned_cidrs) @mock.patch('nova.db.network_get_all') def test_validate_cidrs_conflict_existing_supernet(self, get_all): manager = fake_network.FakeNetworkManager() get_all.return_value = [dict(test_network.fake_network, id=1, cidr='192.168.0.0/8')] args = (self.context.elevated(), 'fake', '192.168.0.0/24', False, 1, 256, None, None, None, None, None) # CidrConflict: requested cidr (192.168.0.0/24) conflicts # with existing supernet self.assertRaises(exception.CidrConflict, manager.create_networks, *args) def test_create_networks(self): cidr = '192.168.0.0/24' manager = fake_network.FakeNetworkManager() self.stubs.Set(manager, '_create_fixed_ips', self.fake_create_fixed_ips) args = [self.context.elevated(), 'foo', cidr, None, 1, 256, 'fd00::/48', None, None, None, None, None] self.assertTrue(manager.create_networks(*args)) @mock.patch('nova.db.network_get_all') def test_create_networks_cidr_already_used(self, get_all): manager = fake_network.FakeNetworkManager() get_all.return_value = [dict(test_network.fake_network, id=1, cidr='192.168.0.0/24')] args = [self.context.elevated(), 'foo', '192.168.0.0/24', None, 1, 256, 'fd00::/48', None, None, None, None, None] self.assertRaises(exception.CidrConflict, manager.create_networks, *args) def test_create_networks_many(self): cidr = '192.168.0.0/16' manager = fake_network.FakeNetworkManager() self.stubs.Set(manager, '_create_fixed_ips', self.fake_create_fixed_ips) args = [self.context.elevated(), 'foo', cidr, None, 10, 256, 'fd00::/48', None, None, None, None, None] self.assertTrue(manager.create_networks(*args)) @mock.patch('nova.db.network_get') @mock.patch('nova.db.fixed_ips_by_virtual_interface') def test_get_instance_uuids_by_ip_regex(self, fixed_get, network_get): manager = fake_network.FakeNetworkManager(self.stubs) fixed_get.side_effect = manager.db.fixed_ips_by_virtual_interface _vifs = manager.db.virtual_interface_get_all(None) fake_context = context.RequestContext('user', 'project') network_get.return_value = dict(test_network.fake_network, **manager.db.network_get(None, 1)) # Greedy get eveything res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip': '.*'}) self.assertEqual(len(res), len(_vifs)) # Doesn't exist res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip': '10.0.0.1'}) self.assertFalse(res) # Get instance 1 res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip': '172.16.0.2'}) self.assertTrue(res) self.assertEqual(len(res), 1) self.assertEqual(res[0]['instance_uuid'], _vifs[1]['instance_uuid']) # Get instance 2 res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip': '173.16.0.2'}) self.assertTrue(res) self.assertEqual(len(res), 1) self.assertEqual(res[0]['instance_uuid'], _vifs[2]['instance_uuid']) # Get instance 0 and 1 res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip': '172.16.0.*'}) self.assertTrue(res) self.assertEqual(len(res), 2) self.assertEqual(res[0]['instance_uuid'], _vifs[0]['instance_uuid']) self.assertEqual(res[1]['instance_uuid'], _vifs[1]['instance_uuid']) # Get instance 1 and 2 res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip': '17..16.0.2'}) self.assertTrue(res) self.assertEqual(len(res), 2) self.assertEqual(res[0]['instance_uuid'], _vifs[1]['instance_uuid']) self.assertEqual(res[1]['instance_uuid'], _vifs[2]['instance_uuid']) @mock.patch('nova.db.network_get') def test_get_instance_uuids_by_ipv6_regex(self, network_get): manager = fake_network.FakeNetworkManager(self.stubs) _vifs = manager.db.virtual_interface_get_all(None) fake_context = context.RequestContext('user', 'project') def _network_get(context, network_id, **args): return dict(test_network.fake_network, **manager.db.network_get(context, network_id)) network_get.side_effect = _network_get # Greedy get eveything res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip6': '.*'}) self.assertEqual(len(res), len(_vifs)) # Doesn't exist res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip6': '.*1034.*'}) self.assertFalse(res) # Get instance 1 res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip6': '2001:.*2'}) self.assertTrue(res) self.assertEqual(len(res), 1) self.assertEqual(res[0]['instance_uuid'], _vifs[1]['instance_uuid']) # Get instance 2 ip6 = '2001:db8:69:1f:dead:beff:feff:ef03' res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip6': ip6}) self.assertTrue(res) self.assertEqual(len(res), 1) self.assertEqual(res[0]['instance_uuid'], _vifs[2]['instance_uuid']) # Get instance 0 and 1 res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip6': '.*ef0[1,2]'}) self.assertTrue(res) self.assertEqual(len(res), 2) self.assertEqual(res[0]['instance_uuid'], _vifs[0]['instance_uuid']) self.assertEqual(res[1]['instance_uuid'], _vifs[1]['instance_uuid']) # Get instance 1 and 2 ip6 = '2001:db8:69:1.:dead:beff:feff:ef0.' res = manager.get_instance_uuids_by_ip_filter(fake_context, {'ip6': ip6}) self.assertTrue(res) self.assertEqual(len(res), 2) self.assertEqual(res[0]['instance_uuid'], _vifs[1]['instance_uuid']) self.assertEqual(res[1]['instance_uuid'], _vifs[2]['instance_uuid']) @mock.patch('nova.db.network_get') @mock.patch('nova.db.fixed_ips_by_virtual_interface') def test_get_instance_uuids_by_ip(self, fixed_get, network_get): manager = fake_network.FakeNetworkManager(self.stubs) fixed_get.side_effect = manager.db.fixed_ips_by_virtual_interface _vifs = manager.db.virtual_interface_get_all(None) fake_context = context.RequestContext('user', 'project') network_get.return_value = dict(test_network.fake_network, **manager.db.network_get(None, 1)) # No regex for you! res = manager.get_instance_uuids_by_ip_filter(fake_context, {'fixed_ip': '.*'}) self.assertFalse(res) # Doesn't exist ip = '10.0.0.1' res = manager.get_instance_uuids_by_ip_filter(fake_context, {'fixed_ip': ip}) self.assertFalse(res) # Get instance 1 ip = '172.16.0.2' res = manager.get_instance_uuids_by_ip_filter(fake_context, {'fixed_ip': ip}) self.assertTrue(res) self.assertEqual(len(res), 1) self.assertEqual(res[0]['instance_uuid'], _vifs[1]['instance_uuid']) # Get instance 2 ip = '173.16.0.2' res = manager.get_instance_uuids_by_ip_filter(fake_context, {'fixed_ip': ip}) self.assertTrue(res) self.assertEqual(len(res), 1) self.assertEqual(res[0]['instance_uuid'], _vifs[2]['instance_uuid']) @mock.patch('nova.db.network_get_by_uuid') def test_get_network(self, get): manager = fake_network.FakeNetworkManager() fake_context = context.RequestContext('user', 'project') get.return_value = dict(test_network.fake_network, **networks[0]) uuid = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' network = manager.get_network(fake_context, uuid) self.assertEqual(network['uuid'], uuid) @mock.patch('nova.db.network_get_by_uuid') def test_get_network_not_found(self, get): manager = fake_network.FakeNetworkManager() fake_context = context.RequestContext('user', 'project') get.side_effect = exception.NetworkNotFoundForUUID(uuid='foo') uuid = 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee' self.assertRaises(exception.NetworkNotFound, manager.get_network, fake_context, uuid) @mock.patch('nova.db.network_get_all') def test_get_all_networks(self, get_all): manager = fake_network.FakeNetworkManager() fake_context = context.RequestContext('user', 'project') get_all.return_value = [dict(test_network.fake_network, **net) for net in networks] output = manager.get_all_networks(fake_context) self.assertEqual(len(networks), 2) self.assertEqual(output[0]['uuid'], 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa') self.assertEqual(output[1]['uuid'], 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb') @mock.patch('nova.db.network_get_by_uuid') @mock.patch('nova.db.network_disassociate') def test_disassociate_network(self, disassociate, get): manager = fake_network.FakeNetworkManager() disassociate.return_value = True fake_context = context.RequestContext('user', 'project') get.return_value = dict(test_network.fake_network, **networks[0]) uuid = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' manager.disassociate_network(fake_context, uuid) @mock.patch('nova.db.network_get_by_uuid') def test_disassociate_network_not_found(self, get): manager = fake_network.FakeNetworkManager() fake_context = context.RequestContext('user', 'project') get.side_effect = exception.NetworkNotFoundForUUID(uuid='fake') uuid = 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee' self.assertRaises(exception.NetworkNotFound, manager.disassociate_network, fake_context, uuid) def _test_init_host_dynamic_fixed_range(self, net_manager): self.flags(fake_network=True, routing_source_ip='172.16.0.1', metadata_host='172.16.0.1', public_interface='eth1', dmz_cidr=['10.0.3.0/24']) binary_name = linux_net.get_binary_name() # Stub out calls we don't want to really run, mock the db self.stubs.Set(linux_net.iptables_manager, '_apply', lambda: None) self.stubs.Set(floating_ips.FloatingIP, 'init_host_floating_ips', lambda *args: None) self.stubs.Set(net_manager.l3driver, 'initialize_gateway', lambda *args: None) self.mox.StubOutWithMock(db, 'network_get_all_by_host') fake_networks = [dict(test_network.fake_network, **n) for n in networks] db.network_get_all_by_host(mox.IgnoreArg(), mox.IgnoreArg() ).MultipleTimes().AndReturn(fake_networks) self.mox.ReplayAll() net_manager.init_host() # Get the iptables rules that got created current_lines = [] new_lines = linux_net.iptables_manager._modify_rules(current_lines, linux_net.iptables_manager.ipv4['nat'], table_name='nat') expected_lines = ['[0:0] -A %s-snat -s %s -d 0.0.0.0/0 ' '-j SNAT --to-source %s -o %s' % (binary_name, networks[0]['cidr'], CONF.routing_source_ip, CONF.public_interface), '[0:0] -A %s-POSTROUTING -s %s -d %s/32 -j ACCEPT' % (binary_name, networks[0]['cidr'], CONF.metadata_host), '[0:0] -A %s-POSTROUTING -s %s -d %s -j ACCEPT' % (binary_name, networks[0]['cidr'], CONF.dmz_cidr[0]), '[0:0] -A %s-POSTROUTING -s %s -d %s -m conntrack ! ' '--ctstate DNAT -j ACCEPT' % (binary_name, networks[0]['cidr'], networks[0]['cidr']), '[0:0] -A %s-snat -s %s -d 0.0.0.0/0 ' '-j SNAT --to-source %s -o %s' % (binary_name, networks[1]['cidr'], CONF.routing_source_ip, CONF.public_interface), '[0:0] -A %s-POSTROUTING -s %s -d %s/32 -j ACCEPT' % (binary_name, networks[1]['cidr'], CONF.metadata_host), '[0:0] -A %s-POSTROUTING -s %s -d %s -j ACCEPT' % (binary_name, networks[1]['cidr'], CONF.dmz_cidr[0]), '[0:0] -A %s-POSTROUTING -s %s -d %s -m conntrack ! ' '--ctstate DNAT -j ACCEPT' % (binary_name, networks[1]['cidr'], networks[1]['cidr'])] # Compare the expected rules against the actual ones for line in expected_lines: self.assertIn(line, new_lines) # Add an additional network and ensure the rules get configured new_network = {'id': 2, 'uuid': 'cccccccc-cccc-cccc-cccc-cccccccc', 'label': 'test2', 'injected': False, 'multi_host': False, 'cidr': '192.168.2.0/24', 'cidr_v6': '2001:dba::/64', 'gateway_v6': '2001:dba::1', 'netmask_v6': '64', 'netmask': '255.255.255.0', 'bridge': 'fa1', 'bridge_interface': 'fake_fa1', 'gateway': '192.168.2.1', 'broadcast': '192.168.2.255', 'dns1': '192.168.2.1', 'dns2': '192.168.2.2', 'vlan': None, 'host': HOST, 'project_id': 'fake_project', 'vpn_public_address': '192.168.2.2', 'vpn_public_port': '22', 'vpn_private_address': '10.0.0.2'} new_network_obj = network_obj.Network._from_db_object( self.context, network_obj.Network(), dict(test_network.fake_network, **new_network)) ctxt = context.get_admin_context() net_manager._setup_network_on_host(ctxt, new_network_obj) # Get the new iptables rules that got created from adding a new network current_lines = [] new_lines = linux_net.iptables_manager._modify_rules(current_lines, linux_net.iptables_manager.ipv4['nat'], table_name='nat') # Add the new expected rules to the old ones expected_lines += ['[0:0] -A %s-snat -s %s -d 0.0.0.0/0 ' '-j SNAT --to-source %s -o %s' % (binary_name, new_network['cidr'], CONF.routing_source_ip, CONF.public_interface), '[0:0] -A %s-POSTROUTING -s %s -d %s/32 -j ACCEPT' % (binary_name, new_network['cidr'], CONF.metadata_host), '[0:0] -A %s-POSTROUTING -s %s -d %s -j ACCEPT' % (binary_name, new_network['cidr'], CONF.dmz_cidr[0]), '[0:0] -A %s-POSTROUTING -s %s -d %s -m conntrack ' '! --ctstate DNAT -j ACCEPT' % (binary_name, new_network['cidr'], new_network['cidr'])] # Compare the expected rules (with new network) against the actual ones for line in expected_lines: self.assertIn(line, new_lines) def test_flatdhcpmanager_dynamic_fixed_range(self): """Test FlatDHCPManager NAT rules for fixed_range.""" # Set the network manager self.network = network_manager.FlatDHCPManager(host=HOST) self.network.db = db # Test new behavior: # CONF.fixed_range is not set, defaults to None # Determine networks to NAT based on lookup self._test_init_host_dynamic_fixed_range(self.network) def test_vlanmanager_dynamic_fixed_range(self): """Test VlanManager NAT rules for fixed_range.""" # Set the network manager self.network = network_manager.VlanManager(host=HOST) self.network.db = db # Test new behavior: # CONF.fixed_range is not set, defaults to None # Determine networks to NAT based on lookup self._test_init_host_dynamic_fixed_range(self.network) class TestRPCFixedManager(network_manager.RPCAllocateFixedIP, network_manager.NetworkManager): """Dummy manager that implements RPCAllocateFixedIP.""" class RPCAllocateTestCase(test.TestCase): """Tests nova.network.manager.RPCAllocateFixedIP.""" def setUp(self): super(RPCAllocateTestCase, self).setUp() self.flags(use_local=True, group='conductor') self.rpc_fixed = TestRPCFixedManager() self.context = context.RequestContext('fake', 'fake') def test_rpc_allocate(self): """Test to verify bug 855030 doesn't resurface. Mekes sure _rpc_allocate_fixed_ip returns a value so the call returns properly and the greenpool completes. """ address = '10.10.10.10' def fake_allocate(*args, **kwargs): return address def fake_network_get(*args, **kwargs): return test_network.fake_network self.stubs.Set(self.rpc_fixed, 'allocate_fixed_ip', fake_allocate) self.stubs.Set(self.rpc_fixed.db, 'network_get', fake_network_get) rval = self.rpc_fixed._rpc_allocate_fixed_ip(self.context, 'fake_instance', 'fake_network') self.assertEqual(rval, address) class TestFloatingIPManager(floating_ips.FloatingIP, network_manager.NetworkManager): """Dummy manager that implements FloatingIP.""" class AllocateTestCase(test.TestCase): def setUp(self): super(AllocateTestCase, self).setUp() self.useFixture(test.SampleNetworks()) self.conductor = self.start_service( 'conductor', manager=CONF.conductor.manager) self.compute = self.start_service('compute') self.network = self.start_service('network') self.user_id = 'fake' self.project_id = 'fake' self.context = context.RequestContext(self.user_id, self.project_id, is_admin=True) def test_allocate_for_instance(self): address = "10.10.10.10" self.flags(auto_assign_floating_ip=True) db.floating_ip_create(self.context, {'address': address, 'pool': 'nova'}) inst = instance_obj.Instance() inst.host = self.compute.host inst.display_name = HOST inst.instance_type_id = 1 inst.uuid = FAKEUUID inst.create(self.context) networks = db.network_get_all(self.context) for network in networks: db.network_update(self.context, network['id'], {'host': self.network.host}) project_id = self.context.project_id nw_info = self.network.allocate_for_instance(self.context, instance_id=inst['id'], instance_uuid=inst['uuid'], host=inst['host'], vpn=None, rxtx_factor=3, project_id=project_id, macs=None) self.assertEqual(1, len(nw_info)) fixed_ip = nw_info.fixed_ips()[0]['address'] self.assertTrue(utils.is_valid_ipv4(fixed_ip)) self.network.deallocate_for_instance(self.context, instance=inst) def test_allocate_for_instance_with_mac(self): available_macs = set(['ca:fe:de:ad:be:ef']) inst = db.instance_create(self.context, {'host': self.compute.host, 'display_name': HOST, 'instance_type_id': 1}) networks = db.network_get_all(self.context) for network in networks: db.network_update(self.context, network['id'], {'host': self.network.host}) project_id = self.context.project_id nw_info = self.network.allocate_for_instance(self.context, instance_id=inst['id'], instance_uuid=inst['uuid'], host=inst['host'], vpn=None, rxtx_factor=3, project_id=project_id, macs=available_macs) assigned_macs = [vif['address'] for vif in nw_info] self.assertEqual(1, len(assigned_macs)) self.assertEqual(available_macs.pop(), assigned_macs[0]) self.network.deallocate_for_instance(self.context, instance_id=inst['id'], host=self.network.host, project_id=project_id) def test_allocate_for_instance_not_enough_macs(self): available_macs = set() inst = db.instance_create(self.context, {'host': self.compute.host, 'display_name': HOST, 'instance_type_id': 1}) networks = db.network_get_all(self.context) for network in networks: db.network_update(self.context, network['id'], {'host': self.network.host}) project_id = self.context.project_id self.assertRaises(exception.VirtualInterfaceCreateException, self.network.allocate_for_instance, self.context, instance_id=inst['id'], instance_uuid=inst['uuid'], host=inst['host'], vpn=None, rxtx_factor=3, project_id=project_id, macs=available_macs) class FloatingIPTestCase(test.TestCase): """Tests nova.network.manager.FloatingIP.""" def setUp(self): super(FloatingIPTestCase, self).setUp() self.tempdir = self.useFixture(fixtures.TempDir()).path self.flags(log_dir=self.tempdir) self.flags(use_local=True, group='conductor') self.network = TestFloatingIPManager() self.network.db = db self.project_id = 'testproject' self.context = context.RequestContext('testuser', self.project_id, is_admin=False) @mock.patch('nova.db.fixed_ip_get') @mock.patch('nova.db.network_get') @mock.patch('nova.db.instance_get_by_uuid') @mock.patch('nova.db.service_get_by_host_and_topic') @mock.patch('nova.db.floating_ip_get_by_address') def test_disassociate_floating_ip_multi_host_calls(self, floating_get, service_get, inst_get, net_get, fixed_get): floating_ip = dict(test_floating_ip.fake_floating_ip, fixed_ip_id=12) fixed_ip = dict(test_fixed_ip.fake_fixed_ip, network_id=None, instance_uuid='instance-uuid') network = dict(test_network.fake_network, multi_host=True) instance = dict(fake_instance.fake_db_instance(host='some-other-host')) ctxt = context.RequestContext('testuser', 'testproject', is_admin=False) self.stubs.Set(self.network, '_floating_ip_owned_by_project', lambda _x, _y: True) floating_get.return_value = floating_ip fixed_get.return_value = fixed_ip net_get.return_value = network inst_get.return_value = instance service_get.return_value = test_service.fake_service self.stubs.Set(self.network.servicegroup_api, 'service_is_up', lambda _x: True) self.mox.StubOutWithMock( self.network.network_rpcapi, '_disassociate_floating_ip') self.network.network_rpcapi._disassociate_floating_ip( ctxt, 'fl_ip', mox.IgnoreArg(), 'some-other-host', 'instance-uuid') self.mox.ReplayAll() self.network.disassociate_floating_ip(ctxt, 'fl_ip', True) @mock.patch('nova.db.fixed_ip_get_by_address') @mock.patch('nova.db.network_get') @mock.patch('nova.db.instance_get_by_uuid') @mock.patch('nova.db.floating_ip_get_by_address') def test_associate_floating_ip_multi_host_calls(self, floating_get, inst_get, net_get, fixed_get): floating_ip = dict(test_floating_ip.fake_floating_ip, fixed_ip_id=None) fixed_ip = dict(test_fixed_ip.fake_fixed_ip, network_id=None, instance_uuid='instance-uuid') network = dict(test_network.fake_network, multi_host=True) instance = dict(fake_instance.fake_db_instance(host='some-other-host')) ctxt = context.RequestContext('testuser', 'testproject', is_admin=False) self.stubs.Set(self.network, '_floating_ip_owned_by_project', lambda _x, _y: True) floating_get.return_value = floating_ip fixed_get.return_value = fixed_ip net_get.return_value = network inst_get.return_value = instance self.mox.StubOutWithMock( self.network.network_rpcapi, '_associate_floating_ip') self.network.network_rpcapi._associate_floating_ip( ctxt, 'fl_ip', 'fix_ip', mox.IgnoreArg(), 'some-other-host', 'instance-uuid') self.mox.ReplayAll() self.network.associate_floating_ip(ctxt, 'fl_ip', 'fix_ip', True) def test_double_deallocation(self): instance_ref = db.instance_create(self.context, {"project_id": self.project_id}) # Run it twice to make it fault if it does not handle # instances without fixed networks # If this fails in either, it does not handle having no addresses self.network.deallocate_for_instance(self.context, instance_id=instance_ref['id']) self.network.deallocate_for_instance(self.context, instance_id=instance_ref['id']) def test_deallocation_deleted_instance(self): self.stubs.Set(self.network, '_teardown_network_on_host', lambda *args, **kwargs: None) instance = instance_obj.Instance() instance.project_id = self.project_id instance.deleted = True instance.create(self.context) network = db.network_create_safe(self.context.elevated(), { 'project_id': self.project_id, 'host': CONF.host, 'label': 'foo'}) fixed = db.fixed_ip_create(self.context, {'allocated': True, 'instance_uuid': instance.uuid, 'address': '10.1.1.1', 'network_id': network['id']}) db.floating_ip_create(self.context, { 'address': '10.10.10.10', 'instance_uuid': instance.uuid, 'fixed_ip_id': fixed['id'], 'project_id': self.project_id}) self.network.deallocate_for_instance(self.context, instance=instance) def test_deallocation_duplicate_floating_ip(self): self.stubs.Set(self.network, '_teardown_network_on_host', lambda *args, **kwargs: None) instance = instance_obj.Instance() instance.project_id = self.project_id instance.create(self.context) network = db.network_create_safe(self.context.elevated(), { 'project_id': self.project_id, 'host': CONF.host, 'label': 'foo'}) fixed = db.fixed_ip_create(self.context, {'allocated': True, 'instance_uuid': instance.uuid, 'address': '10.1.1.1', 'network_id': network['id']}) db.floating_ip_create(self.context, { 'address': '10.10.10.10', 'deleted': True}) db.floating_ip_create(self.context, { 'address': '10.10.10.10', 'instance_uuid': instance.uuid, 'fixed_ip_id': fixed['id'], 'project_id': self.project_id}) self.network.deallocate_for_instance(self.context, instance=instance) @mock.patch('nova.db.fixed_ip_get') @mock.patch('nova.db.floating_ip_get_by_address') @mock.patch('nova.db.floating_ip_update') def test_migrate_instance_start(self, floating_update, floating_get, fixed_get): called = {'count': 0} def fake_floating_ip_get_by_address(context, address): return dict(test_floating_ip.fake_floating_ip, address=address, fixed_ip_id=0) def fake_is_stale_floating_ip_address(context, floating_ip): return str(floating_ip.address) == '172.24.4.23' floating_get.side_effect = fake_floating_ip_get_by_address fixed_get.return_value = dict(test_fixed_ip.fake_fixed_ip, instance_uuid='fake_uuid', address='10.0.0.2', network=test_network.fake_network) floating_update.return_value = fake_floating_ip_get_by_address( None, '1.2.3.4') def fake_remove_floating_ip(floating_addr, fixed_addr, interface, network): called['count'] += 1 def fake_clean_conntrack(fixed_ip): if not str(fixed_ip) == "10.0.0.2": raise exception.FixedIpInvalid(address=fixed_ip) self.stubs.Set(self.network, '_is_stale_floating_ip_address', fake_is_stale_floating_ip_address) self.stubs.Set(self.network.l3driver, 'remove_floating_ip', fake_remove_floating_ip) self.stubs.Set(self.network.l3driver, 'clean_conntrack', fake_clean_conntrack) self.mox.ReplayAll() addresses = ['172.24.4.23', '172.24.4.24', '172.24.4.25'] self.network.migrate_instance_start(self.context, instance_uuid=FAKEUUID, floating_addresses=addresses, rxtx_factor=3, project_id=self.project_id, source='fake_source', dest='fake_dest') self.assertEqual(called['count'], 2) @mock.patch('nova.db.fixed_ip_get') @mock.patch('nova.db.floating_ip_update') def test_migrate_instance_finish(self, floating_update, fixed_get): called = {'count': 0} def fake_floating_ip_get_by_address(context, address): return dict(test_floating_ip.fake_floating_ip, address=address, fixed_ip_id=0) def fake_is_stale_floating_ip_address(context, floating_ip): return str(floating_ip.address) == '172.24.4.23' fixed_get.return_value = dict(test_fixed_ip.fake_fixed_ip, instance_uuid='fake_uuid', address='10.0.0.2', network=test_network.fake_network) floating_update.return_value = fake_floating_ip_get_by_address( None, '1.2.3.4') def fake_add_floating_ip(floating_addr, fixed_addr, interface, network): called['count'] += 1 self.stubs.Set(self.network.db, 'floating_ip_get_by_address', fake_floating_ip_get_by_address) self.stubs.Set(self.network, '_is_stale_floating_ip_address', fake_is_stale_floating_ip_address) self.stubs.Set(self.network.l3driver, 'add_floating_ip', fake_add_floating_ip) self.mox.ReplayAll() addresses = ['172.24.4.23', '172.24.4.24', '172.24.4.25'] self.network.migrate_instance_finish(self.context, instance_uuid=FAKEUUID, floating_addresses=addresses, host='fake_dest', rxtx_factor=3, project_id=self.project_id, source='fake_source') self.assertEqual(called['count'], 2) def test_floating_dns_create_conflict(self): zone = "example.org" address1 = "10.10.10.11" name1 = "foo" self.network.add_dns_entry(self.context, address1, name1, "A", zone) self.assertRaises(exception.FloatingIpDNSExists, self.network.add_dns_entry, self.context, address1, name1, "A", zone) def test_floating_create_and_get(self): zone = "example.org" address1 = "10.10.10.11" name1 = "foo" name2 = "bar" entries = self.network.get_dns_entries_by_address(self.context, address1, zone) self.assertFalse(entries) self.network.add_dns_entry(self.context, address1, name1, "A", zone) self.network.add_dns_entry(self.context, address1, name2, "A", zone) entries = self.network.get_dns_entries_by_address(self.context, address1, zone) self.assertEqual(len(entries), 2) self.assertEqual(entries[0], name1) self.assertEqual(entries[1], name2) entries = self.network.get_dns_entries_by_name(self.context, name1, zone) self.assertEqual(len(entries), 1) self.assertEqual(entries[0], address1) def test_floating_dns_delete(self): zone = "example.org" address1 = "10.10.10.11" name1 = "foo" name2 = "bar" self.network.add_dns_entry(self.context, address1, name1, "A", zone) self.network.add_dns_entry(self.context, address1, name2, "A", zone) self.network.delete_dns_entry(self.context, name1, zone) entries = self.network.get_dns_entries_by_address(self.context, address1, zone) self.assertEqual(len(entries), 1) self.assertEqual(entries[0], name2) self.assertRaises(exception.NotFound, self.network.delete_dns_entry, self.context, name1, zone) def test_floating_dns_domains_public(self): zone1 = "testzone" domain1 = "example.org" domain2 = "example.com" address1 = '10.10.10.10' entryname = 'testentry' context_admin = context.RequestContext('testuser', 'testproject', is_admin=True) self.assertRaises(exception.AdminRequired, self.network.create_public_dns_domain, self.context, domain1, zone1) self.network.create_public_dns_domain(context_admin, domain1, 'testproject') self.network.create_public_dns_domain(context_admin, domain2, 'fakeproject') domains = self.network.get_dns_domains(self.context) self.assertEqual(len(domains), 2) self.assertEqual(domains[0]['domain'], domain1) self.assertEqual(domains[1]['domain'], domain2) self.assertEqual(domains[0]['project'], 'testproject') self.assertEqual(domains[1]['project'], 'fakeproject') self.network.add_dns_entry(self.context, address1, entryname, 'A', domain1) entries = self.network.get_dns_entries_by_name(self.context, entryname, domain1) self.assertEqual(len(entries), 1) self.assertEqual(entries[0], address1) self.assertRaises(exception.AdminRequired, self.network.delete_dns_domain, self.context, domain1) self.network.delete_dns_domain(context_admin, domain1) self.network.delete_dns_domain(context_admin, domain2) # Verify that deleting the domain deleted the associated entry entries = self.network.get_dns_entries_by_name(self.context, entryname, domain1) self.assertFalse(entries) def test_delete_all_by_ip(self): domain1 = "example.org" domain2 = "example.com" address = "10.10.10.10" name1 = "foo" name2 = "bar" def fake_domains(context): return [{'domain': 'example.org', 'scope': 'public'}, {'domain': 'example.com', 'scope': 'public'}, {'domain': 'test.example.org', 'scope': 'public'}] self.stubs.Set(self.network, 'get_dns_domains', fake_domains) context_admin = context.RequestContext('testuser', 'testproject', is_admin=True) self.network.create_public_dns_domain(context_admin, domain1, 'testproject') self.network.create_public_dns_domain(context_admin, domain2, 'fakeproject') domains = self.network.get_dns_domains(self.context) for domain in domains: self.network.add_dns_entry(self.context, address, name1, "A", domain['domain']) self.network.add_dns_entry(self.context, address, name2, "A", domain['domain']) entries = self.network.get_dns_entries_by_address(self.context, address, domain['domain']) self.assertEqual(len(entries), 2) self.network._delete_all_entries_for_ip(self.context, address) for domain in domains: entries = self.network.get_dns_entries_by_address(self.context, address, domain['domain']) self.assertFalse(entries) self.network.delete_dns_domain(context_admin, domain1) self.network.delete_dns_domain(context_admin, domain2) def test_mac_conflicts(self): # Make sure MAC collisions are retried. self.flags(create_unique_mac_address_attempts=3) ctxt = context.RequestContext('testuser', 'testproject', is_admin=True) macs = ['bb:bb:bb:bb:bb:bb', 'aa:aa:aa:aa:aa:aa'] # Create a VIF with aa:aa:aa:aa:aa:aa crash_test_dummy_vif = { 'address': macs[1], 'instance_uuid': 'fake_uuid', 'network_id': 123, 'uuid': 'fake_uuid', } self.network.db.virtual_interface_create(ctxt, crash_test_dummy_vif) # Hand out a collision first, then a legit MAC def fake_gen_mac(): return macs.pop() self.stubs.Set(utils, 'generate_mac_address', fake_gen_mac) # SQLite doesn't seem to honor the uniqueness constraint on the # address column, so fake the collision-avoidance here def fake_vif_save(vif): if vif.address == crash_test_dummy_vif['address']: raise db_exc.DBError("If you're smart, you'll retry!") # NOTE(russellb) The VirtualInterface object requires an ID to be # set, and we expect it to get set automatically when we do the # save. vif.id = 1 self.stubs.Set(models.VirtualInterface, 'save', fake_vif_save) # Attempt to add another and make sure that both MACs are consumed # by the retry loop self.network._add_virtual_interface(ctxt, 'fake_uuid', 123) self.assertEqual(macs, []) def test_deallocate_client_exceptions(self): # Ensure that FloatingIpNotFoundForAddress is wrapped. self.mox.StubOutWithMock(self.network.db, 'floating_ip_get_by_address') self.network.db.floating_ip_get_by_address( self.context, '1.2.3.4').AndRaise( exception.FloatingIpNotFoundForAddress(address='fake')) self.mox.ReplayAll() self.assertRaises(messaging.ExpectedException, self.network.deallocate_floating_ip, self.context, '1.2.3.4') def test_associate_client_exceptions(self): # Ensure that FloatingIpNotFoundForAddress is wrapped. self.mox.StubOutWithMock(self.network.db, 'floating_ip_get_by_address') self.network.db.floating_ip_get_by_address( self.context, '1.2.3.4').AndRaise( exception.FloatingIpNotFoundForAddress(address='fake')) self.mox.ReplayAll() self.assertRaises(messaging.ExpectedException, self.network.associate_floating_ip, self.context, '1.2.3.4', '10.0.0.1') def test_disassociate_client_exceptions(self): # Ensure that FloatingIpNotFoundForAddress is wrapped. self.mox.StubOutWithMock(self.network.db, 'floating_ip_get_by_address') self.network.db.floating_ip_get_by_address( self.context, '1.2.3.4').AndRaise( exception.FloatingIpNotFoundForAddress(address='fake')) self.mox.ReplayAll() self.assertRaises(messaging.ExpectedException, self.network.disassociate_floating_ip, self.context, '1.2.3.4') def test_get_floating_ip_client_exceptions(self): # Ensure that FloatingIpNotFoundForAddress is wrapped. self.mox.StubOutWithMock(self.network.db, 'floating_ip_get') self.network.db.floating_ip_get(self.context, 'fake-id').AndRaise( exception.FloatingIpNotFound(id='fake')) self.mox.ReplayAll() self.assertRaises(messaging.ExpectedException, self.network.get_floating_ip, self.context, 'fake-id') def _test_associate_floating_ip_failure(self, stdout, expected_exception): def _fake_catchall(*args, **kwargs): return dict(test_fixed_ip.fake_fixed_ip, network=test_network.fake_network) def _fake_add_floating_ip(*args, **kwargs): raise processutils.ProcessExecutionError(stdout) self.stubs.Set(self.network.db, 'floating_ip_fixed_ip_associate', _fake_catchall) self.stubs.Set(self.network.db, 'floating_ip_disassociate', _fake_catchall) self.stubs.Set(self.network.l3driver, 'add_floating_ip', _fake_add_floating_ip) self.assertRaises(expected_exception, self.network._associate_floating_ip, self.context, '1.2.3.4', '1.2.3.5', '', '') def test_associate_floating_ip_failure(self): self._test_associate_floating_ip_failure(None, processutils.ProcessExecutionError) def test_associate_floating_ip_failure_interface_not_found(self): self._test_associate_floating_ip_failure('Cannot find device', exception.NoFloatingIpInterface) class InstanceDNSTestCase(test.TestCase): """Tests nova.network.manager instance DNS.""" def setUp(self): super(InstanceDNSTestCase, self).setUp() self.tempdir = self.useFixture(fixtures.TempDir()).path self.flags(log_dir=self.tempdir) self.flags(use_local=True, group='conductor') self.network = TestFloatingIPManager() self.network.db = db self.project_id = 'testproject' self.context = context.RequestContext('testuser', self.project_id, is_admin=False) def test_dns_domains_private(self): zone1 = 'testzone' domain1 = 'example.org' context_admin = context.RequestContext('testuser', 'testproject', is_admin=True) self.assertRaises(exception.AdminRequired, self.network.create_private_dns_domain, self.context, domain1, zone1) self.network.create_private_dns_domain(context_admin, domain1, zone1) domains = self.network.get_dns_domains(self.context) self.assertEqual(len(domains), 1) self.assertEqual(domains[0]['domain'], domain1) self.assertEqual(domains[0]['availability_zone'], zone1) self.assertRaises(exception.AdminRequired, self.network.delete_dns_domain, self.context, domain1) self.network.delete_dns_domain(context_admin, domain1) domain1 = "example.org" domain2 = "example.com" class LdapDNSTestCase(test.TestCase): """Tests nova.network.ldapdns.LdapDNS.""" def setUp(self): super(LdapDNSTestCase, self).setUp() self.useFixture(test.ReplaceModule('ldap', fake_ldap)) dns_class = 'nova.network.ldapdns.LdapDNS' self.driver = importutils.import_object(dns_class) attrs = {'objectClass': ['domainrelatedobject', 'dnsdomain', 'domain', 'dcobject', 'top'], 'associateddomain': ['root'], 'dc': ['root']} self.driver.lobj.add_s("ou=hosts,dc=example,dc=org", attrs.items()) self.driver.create_domain(domain1) self.driver.create_domain(domain2) def tearDown(self): self.driver.delete_domain(domain1) self.driver.delete_domain(domain2) super(LdapDNSTestCase, self).tearDown() def test_ldap_dns_domains(self): domains = self.driver.get_domains() self.assertEqual(len(domains), 2) self.assertIn(domain1, domains) self.assertIn(domain2, domains) def test_ldap_dns_create_conflict(self): address1 = "10.10.10.11" name1 = "foo" self.driver.create_entry(name1, address1, "A", domain1) self.assertRaises(exception.FloatingIpDNSExists, self.driver.create_entry, name1, address1, "A", domain1) def test_ldap_dns_create_and_get(self): address1 = "10.10.10.11" name1 = "foo" name2 = "bar" entries = self.driver.get_entries_by_address(address1, domain1) self.assertFalse(entries) self.driver.create_entry(name1, address1, "A", domain1) self.driver.create_entry(name2, address1, "A", domain1) entries = self.driver.get_entries_by_address(address1, domain1) self.assertEqual(len(entries), 2) self.assertEqual(entries[0], name1) self.assertEqual(entries[1], name2) entries = self.driver.get_entries_by_name(name1, domain1) self.assertEqual(len(entries), 1) self.assertEqual(entries[0], address1) def test_ldap_dns_delete(self): address1 = "10.10.10.11" name1 = "foo" name2 = "bar" self.driver.create_entry(name1, address1, "A", domain1) self.driver.create_entry(name2, address1, "A", domain1) entries = self.driver.get_entries_by_address(address1, domain1) self.assertEqual(len(entries), 2) self.driver.delete_entry(name1, domain1) entries = self.driver.get_entries_by_address(address1, domain1) LOG.debug("entries: %s" % entries) self.assertEqual(len(entries), 1) self.assertEqual(entries[0], name2) self.assertRaises(exception.NotFound, self.driver.delete_entry, name1, domain1)
CiscoSystems/nova
nova/tests/network/test_manager.py
Python
apache-2.0
131,638
[ "FEFF" ]
27df6e5ced6c883ec08eda2993d4eca306a925b7bd78b42f6395184a0118aa7b
############################################################################## ############################################################################## # Example code for # quasi-Newton particle Metropolis-Hastings # for a linear Gaussian state space model # # Please cite: # # J. Dahlin, F. Lindsten, T. B. Sch\"{o}n # "Quasi-Newton particle Metropolis-Hastings" # Proceedings of the 17th IFAC Symposium on System Identification, # Beijing, China, October 2015. # # (c) 2015 Johan Dahlin # johan.dahlin (at) liu.se # # Distributed under the MIT license. # ############################################################################## ############################################################################## import numpy as np from pmh_helpers import * import pandas ########################################################################## # Main class ########################################################################## class stPMH(object): # Initalise some variables memoryLength = None; empHessian = None; ########################################################################## # Main sampling routine ########################################################################## def runSampler(self,sm,sys,thSys,PMHtype): #===================================================================== # Initalisation #===================================================================== # Set file prefix from model self.filePrefix = thSys.filePrefix; self.iter = 0; self.PMHtype = PMHtype; self.nPars = thSys.nParInference; # Allocate vectors self.ll = np.zeros((self.nIter,1)) self.llp = np.zeros((self.nIter,1)) self.th = np.zeros((self.nIter,self.nPars)) self.tho = np.zeros((self.nIter,self.nPars)) self.thp = np.zeros((self.nIter,self.nPars)) self.aprob = np.zeros((self.nIter,1)) self.accept = np.zeros((self.nIter,1)) self.gradient = np.zeros((self.nIter,self.nPars)) self.gradientp = np.zeros((self.nIter,self.nPars)) self.hessian = np.zeros((self.nIter,self.nPars,self.nPars)) self.hessianp = np.zeros((self.nIter,self.nPars,self.nPars)) self.prior = np.zeros((self.nIter,1)) self.priorp = np.zeros((self.nIter,1)) self.J = np.zeros((self.nIter,1)) self.Jp = np.zeros((self.nIter,1)) self.proposalProb = np.zeros((self.nIter,1)) self.proposalProbP = np.zeros((self.nIter,1)) self.llDiff = np.zeros((self.nIter,1)) # Get the order of the PMH sampler if ( PMHtype == "pPMH0" ): self.PMHtypeN = 0; elif ( PMHtype == "pPMH1" ): self.PMHtypeN = 1; elif ( PMHtype == "qPMH2" ): self.PMHtypeN = 2; self.nHessianSamples = np.zeros((self.nIter,1)) # Initialise the parameters in the proposal thSys.storeParameters(self.initPar,sys); # Run the initial filter/smoother self.estimateLikelihoodGradients(sm,thSys); self.acceptParameters(thSys); # Save the current parameters self.th[0,:] = thSys.returnParameters(); #===================================================================== # Main MCMC-loop #===================================================================== for kk in range(1,self.nIter): self.iter = kk; # Propose parameters self.sampleProposal(); thSys.storeParameters( self.thp[kk,:], sys ); # Calculate acceptance probability self.calculateAcceptanceProbability( sm, thSys ); # Accept/reject step if ( np.random.random(1) < self.aprob[kk] ): self.acceptParameters( thSys ); else: self.rejectParameters( thSys ); # Write out progress report if np.remainder( kk, 100 ) == 0: progressPrint( self ); progressPrint(self); ########################################################################## # Sample the proposal ########################################################################## def sampleProposal(self,): if ( self.PMHtype == "pPMH0" ): # Sample the preconditioned PMH0 proposal self.thp[self.iter,:] = self.th[self.iter-1,:] + np.random.multivariate_normal(np.zeros(self.nPars), self.stepSize**2 * self.invHessian ); if( self.PMHtype == "pPMH1" ): # Sample the preconditioned PMH1 proposal self.thp[self.iter,:] = self.th[self.iter-1,:] + 0.5 * self.stepSize**2 * np.dot(self.invHessian,self.gradient[self.iter-1,:]) + np.random.multivariate_normal(np.zeros(self.nPars), self.stepSize**2 * self.invHessian ); if ( self.PMHtype == "qPMH2" ): # Using PMH0 in initial phase and then quasi-Newton proposal if ( self.iter > self.memoryLength ): self.thp[self.iter,:] = self.th[self.iter-1-self.memoryLength,:] + 0.5 * self.stepSize**2 * np.dot( self.gradient[self.iter-1-self.memoryLength,:], self.hessian[self.iter-1-self.memoryLength,:,:] ) + np.random.multivariate_normal(np.zeros(self.nPars), self.stepSize**2 * self.hessian[self.iter-1-self.memoryLength,:,:] ); else: self.thp[self.iter,:] = self.th[self.iter-1,:] + np.random.multivariate_normal( np.zeros(self.nPars), self.stepSize**2 * self.hessian[self.iter-1,:,:] ); ########################################################################## # Calculate Acceptance Probability ########################################################################## def calculateAcceptanceProbability(self, sm, thSys, ): # Run the smoother to get estimates of the log-likelihood and gradiets self.estimateLikelihoodGradients(sm,thSys); # Compute the part in the acceptance probability related to the non-symmetric proposal if ( self.PMHtype == "pPMH0" ): proposalP = 0; proposal0 = 0; if ( self.PMHtype == "pPMH1" ): proposalP = lognormpdf( self.thp[self.iter,:], self.th[self.iter-1,:] + 0.5 * self.stepSize**2 * np.dot( self.invHessian,self.gradient[self.iter-1,:]), self.stepSize**2 * self.invHessian ); proposal0 = lognormpdf( self.th[self.iter-1,:],self.thp[self.iter,:] + 0.5 * self.stepSize**2 * np.dot( self.invHessian,self.gradientp[self.iter,:]) , self.stepSize**2 * self.invHessian ); if ( self.PMHtype == "qPMH2" ): if ( self.iter > self.memoryLength ): proposalP = lognormpdf( self.thp[self.iter,:], self.th[self.iter-1-self.memoryLength,:] + 0.5 * self.stepSize**2 * np.dot( self.gradient[self.iter-1-self.memoryLength,:], self.hessian[self.iter-1-self.memoryLength,:,:]) , self.stepSize**2 * self.hessian[self.iter-1-self.memoryLength,:,:] ); proposal0 = lognormpdf( self.th[self.iter-1-self.memoryLength,:], self.thp[self.iter,:] + 0.5 * self.stepSize**2 * np.dot( self.gradientp[self.iter,:], self.hessianp[self.iter,:,:]) , self.stepSize**2 * self.hessianp[self.iter,:,:] ); else: # Initial phase, use pPMH0 proposalP = lognormpdf( self.thp[self.iter,:], self.th[self.iter-1,:] , self.stepSize**2 * self.hessian[self.iter-1,:,:] ); proposal0 = lognormpdf( self.th[self.iter-1,:], self.thp[self.iter,:] , self.stepSize**2 * self.hessianp[self.iter,:,:] ); # Compute the log-prior self.priorp[ self.iter ] = thSys.prior(); # Compute the acceptance probability self.aprob[ self.iter ] = self.flag * np.exp( self.llp[ self.iter, :] - self.ll[ self.iter-1, :] + proposal0 - proposalP + self.priorp[ self.iter, :] - self.prior[ self.iter-1, :] ); # Store the proposal calculations self.proposalProb[ self.iter ] = proposal0; self.proposalProbP[ self.iter ] = proposalP; self.llDiff[ self.iter ] = self.llp[ self.iter, :] - self.ll[ self.iter-1, :]; ########################################################################## # Run the SMC algorithm and get the required information ########################################################################## def estimateLikelihoodGradients(self,sm,thSys,): # Flag if the Hessian is PSD or not. self.flag = 1.0 # PMH0, only run the filter and extract the likelihood estimate if ( self.PMHtypeN == 0 ): sm.filter(thSys); # PMH1, only run the smoother and extract the likelihood estimate and gradient if ( self.PMHtypeN == 1 ): sm.smoother(thSys); self.gradientp[ self.iter,: ] = sm.gradient; # PMH2, only run the smoother and extract the likelihood estimate and gradient if ( self.PMHtypeN == 2 ): sm.smoother(thSys); self.gradientp[ self.iter,: ] = sm.gradient; # Note that this is the inverse Hessian self.hessianp [ self.iter,:,: ] = self.lbfgs_hessian_update( ); # Extract the diagonal if needed and regularise if not PSD self.checkHessian(); # Create output self.llp[ self.iter ] = sm.ll; return None; ########################################################################## # Extract the diagonal if needed and regularise if not PSD ########################################################################## def checkHessian(self): # Pre-calculate posterior covariance estimate if ( ( self.iter >= self.nBurnIn ) & ( self.empHessian == None ) ) : self.empHessian = np.cov( self.th[range( self.nBurnIn - self.PSDmethodhybridSamps, self.nBurnIn ),].transpose() ); # Check if it is PSD if ( ~isPSD( self.hessianp [ self.iter,:,: ] ) ): eigens = np.linalg.eig(self.hessianp [ self.iter,:,: ])[0]; # Add a diagonal matrix proportional to the largest negative eigv during burnin if ( self.iter <= self.nBurnIn ): mineigv = np.min( np.linalg.eig( self.hessianp [ self.iter,:,: ] )[0] ) self.hessianp [ self.iter,:,: ] = self.hessianp [ self.iter,:,: ] - 2.0 * mineigv * np.eye( self.nPars ) print("Iteration: " + str(self.iter) + " has eigenvalues: " + str( eigens ) + " mirroring by adding " + str( - 2.0 * mineigv ) ); # Replace the Hessian with the posterior covariance matrix after burin if ( self.iter > self.nBurnIn ): self.hessianp [ self.iter,:,: ] = self.empHessian; print("Iteration: " + str(self.iter) + " has eigenvalues: " + str( eigens ) + " replaced Hessian with pre-computed estimated." ); ########################################################################## # Quasi-Netwon proposal ########################################################################## def lbfgs_hessian_update(self): I = np.eye(self.nPars, dtype=int); Hk = np.eye(self.nPars) / self.epsilon; # BFGS update for Hessian estimate if ( self.iter > self.memoryLength ): # Extract estimates of log-likelihood and gradients from the # last moves self.extractUniqueElements(); if ( self.nHessianSamples[ self.iter ] > 2 ): # Extract the last unique parameters and their gradients idx = np.sort( np.unique(self.ll,return_index=True)[1] )[-2:]; if ( np.max( self.iter - idx ) < self.memoryLength ): # The last accepted step is inside of the memory length skk = self.th[ idx[1] , : ] - self.th[ idx[0], : ]; ykk = self.gradient[ idx[1] , : ] - self.gradient[ idx[0], : ]; foo = np.dot( skk, ykk) / np.dot( ykk, ykk); Hk = np.eye(self.nPars) * foo; # Add the contribution from the last memoryLength samples for ii in range( (self.thU).shape[0] ): # Calculate difference in gradient (ykk) and theta (skk) ykk = self.gradientU[ii,:] - self.gradientU[ii-1,:]; skk = self.thU[ii,:] - self.thU[ii-1,:]; # Check if we have moved, otherwise to not add contribution to Hessian if ( np.sum( skk ) != 0.0 ): # Compute rho rhok = 1.0 / ( np.dot( ykk, skk) ); # Update Hessian estimate A1 = I - skk[:, np.newaxis] * ykk[np.newaxis, :] * rhok A2 = I - ykk[:, np.newaxis] * skk[np.newaxis, :] * rhok Hk = np.dot(A1, np.dot(Hk, A2)) + ( rhok * skk[:, np.newaxis] * skk[np.newaxis, :] ) # Return the negative Hessian estimate Hk = -Hk; return Hk; ########################################################################## # Helper to Quasi-Netwon proposal: # Extract the last n unique parameters and their gradients ########################################################################## def extractUniqueElements(self): # Find the unique elements idx = np.sort( np.unique(self.ll[0:(self.iter-1)],return_index=True)[1] ); # Extract the ones inside the memory length idx = [ii for ii in idx if ii >= (self.iter - self.memoryLength) ] # Sort the indicies according to the log-likelihood idx2 = np.argsort( self.ll[idx], axis=0 )[:,0] # Get the new indicies idx3 = np.zeros( len(idx), dtype=int ) for ii in idx2: idx3[ii] = idx[ii] # Extract and export the parameters and their gradients self.thU = self.th[idx3,:]; self.gradientU = self.gradient[idx3,:]; # Save the number of indicies self.nHessianSamples[ self.iter ] = np.max((0,(self.thU).shape[0] - 1)); ########################################################################## # Compute the IACT ########################################################################## def calcIACT( self, nSamples=None ): IACT = np.zeros( self.nPars ); for ii in range( self.nPars ): if ( nSamples == None ): IACT[ii] = proto_IACT( self.th[self.nBurnIn:self.nIter,ii] ) else: if (( self.nIter-nSamples ) > 0 ): IACT[ii] = proto_IACT( self.th[(self.nIter-nSamples):self.nIter,ii] ) else: raise NameError("More samples to compute IACT than iterations of the PMH algorithm.") return IACT ########################################################################## # Helper if parameters are accepted ########################################################################## def acceptParameters(self,thSys,): self.th[self.iter,:] = self.thp[self.iter,:]; self.tho[self.iter,:] = thSys.returnParameters(); self.ll[self.iter] = self.llp[self.iter]; self.gradient[self.iter,:] = self.gradientp[self.iter,:]; self.hessian[self.iter,:,:] = self.hessianp[self.iter,:]; self.accept[self.iter] = 1.0; self.prior[self.iter,:] = self.priorp[self.iter,:]; self.J[self.iter,:] = self.Jp[self.iter,:]; ########################################################################## # Helper if parameters are rejected ########################################################################## def rejectParameters(self,thSys,): if ( ( self.PMHtype == "qPMH2" ) & ( self.iter > self.memoryLength ) ): self.th[self.iter,:] = self.th[self.iter-1-self.memoryLength,:]; self.tho[self.iter,:] = self.tho[self.iter-1-self.memoryLength,:]; self.ll[self.iter] = self.ll[self.iter-1-self.memoryLength]; self.prior[self.iter,:] = self.prior[self.iter-1-self.memoryLength,:] self.gradient[self.iter,:] = self.gradient[self.iter-1-self.memoryLength,:]; self.hessian[self.iter,:,:] = self.hessian[self.iter-1-self.memoryLength,:,:]; self.J[self.iter,:] = self.J[self.iter-1-self.memoryLength,:]; else: self.th[self.iter,:] = self.th[self.iter-1,:]; self.tho[self.iter,:] = self.tho[self.iter-1,:]; self.ll[self.iter] = self.ll[self.iter-1]; self.prior[self.iter,:] = self.prior[self.iter-1,:] self.gradient[self.iter,:] = self.gradient[self.iter-1,:]; self.hessian[self.iter,:,:] = self.hessian[self.iter-1,:,:]; self.J[self.iter,:] = self.J[self.iter-1,:]; ########################################################################## # Helper: compile the results and write to file ########################################################################## def writeToFile(self,sm=None,fileOutName=None): # Set file name from parameter if ( ( self.fileOutName != None ) & (fileOutName == None) ): fileOutName = self.fileOutName; # Calculate the natural gradient ngrad = np.zeros((self.nIter,self.nPars)); if ( self.PMHtype == "pPMH1" ): for kk in range(0,self.nIter): ngrad[kk,:] = np.dot( self.gradient[kk,:], self.invHessian ); # Construct the columns labels columnlabels = [None]*(3*self.nPars+3); for ii in xrange(3*self.nPars+3): columnlabels[ii] = ii; for ii in range(0,self.nPars): columnlabels[ii] = "th" + str(ii); columnlabels[ii+self.nPars] = "thp" + str(ii); columnlabels[ii+2*self.nPars] = "ng" + str(ii); columnlabels[3*self.nPars] = "acceptProb"; columnlabels[3*self.nPars+1] = "loglikelihood"; columnlabels[3*self.nPars+2] = "acceptflag"; # Compile the results for output out = np.hstack((self.th,self.thp,ngrad,self.aprob,self.ll,self.accept)); # Write out the results to file fileOut = pandas.DataFrame(out,columns=columnlabels); ensure_dir(fileOutName); fileOut.to_csv(fileOutName); print("writeToFile: wrote results to file: " + fileOutName) ############################################################################## ############################################################################## # End of file ############################################################################## ##############################################################################
compops/qpmh2-sysid2015
para/pmh.py
Python
gpl-3.0
19,261
[ "Gaussian" ]
cc129ec6ed7889d3790b9afb94e8ed228eed04d16c77feb4ab7b2a3b70bfd544
import pytest import numpy as np import json import pandas.util.testing as tm from pandas import compat, Index, DataFrame from pandas.io.json import json_normalize from pandas.io.json.normalize import nested_to_record @pytest.fixture def deep_nested(): # deeply nested data return [{'country': 'USA', 'states': [{'name': 'California', 'cities': [{'name': 'San Francisco', 'pop': 12345}, {'name': 'Los Angeles', 'pop': 12346}] }, {'name': 'Ohio', 'cities': [{'name': 'Columbus', 'pop': 1234}, {'name': 'Cleveland', 'pop': 1236}]} ] }, {'country': 'Germany', 'states': [{'name': 'Bayern', 'cities': [{'name': 'Munich', 'pop': 12347}] }, {'name': 'Nordrhein-Westfalen', 'cities': [{'name': 'Duesseldorf', 'pop': 1238}, {'name': 'Koeln', 'pop': 1239}]} ] } ] @pytest.fixture def state_data(): return [ {'counties': [{'name': 'Dade', 'population': 12345}, {'name': 'Broward', 'population': 40000}, {'name': 'Palm Beach', 'population': 60000}], 'info': {'governor': 'Rick Scott'}, 'shortname': 'FL', 'state': 'Florida'}, {'counties': [{'name': 'Summit', 'population': 1234}, {'name': 'Cuyahoga', 'population': 1337}], 'info': {'governor': 'John Kasich'}, 'shortname': 'OH', 'state': 'Ohio'}] @pytest.fixture def author_missing_data(): return [ {'info': None}, {'info': {'created_at': '11/08/1993', 'last_updated': '26/05/2012'}, 'author_name': {'first': 'Jane', 'last_name': 'Doe'} }] class TestJSONNormalize(object): def test_simple_records(self): recs = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}, {'a': 7, 'b': 8, 'c': 9}, {'a': 10, 'b': 11, 'c': 12}] result = json_normalize(recs) expected = DataFrame(recs) tm.assert_frame_equal(result, expected) def test_simple_normalize(self, state_data): result = json_normalize(state_data[0], 'counties') expected = DataFrame(state_data[0]['counties']) tm.assert_frame_equal(result, expected) result = json_normalize(state_data, 'counties') expected = [] for rec in state_data: expected.extend(rec['counties']) expected = DataFrame(expected) tm.assert_frame_equal(result, expected) result = json_normalize(state_data, 'counties', meta='state') expected['state'] = np.array(['Florida', 'Ohio']).repeat([3, 2]) tm.assert_frame_equal(result, expected) def test_empty_array(self): result = json_normalize([]) expected = DataFrame() tm.assert_frame_equal(result, expected) def test_simple_normalize_with_separator(self, deep_nested): # GH 14883 result = json_normalize({'A': {'A': 1, 'B': 2}}) expected = DataFrame([[1, 2]], columns=['A.A', 'A.B']) tm.assert_frame_equal(result.reindex_like(expected), expected) result = json_normalize({'A': {'A': 1, 'B': 2}}, sep='_') expected = DataFrame([[1, 2]], columns=['A_A', 'A_B']) tm.assert_frame_equal(result.reindex_like(expected), expected) result = json_normalize({'A': {'A': 1, 'B': 2}}, sep=u'\u03c3') expected = DataFrame([[1, 2]], columns=[u'A\u03c3A', u'A\u03c3B']) tm.assert_frame_equal(result.reindex_like(expected), expected) result = json_normalize(deep_nested, ['states', 'cities'], meta=['country', ['states', 'name']], sep='_') expected = Index(['name', 'pop', 'country', 'states_name']).sort_values() assert result.columns.sort_values().equals(expected) def test_more_deeply_nested(self, deep_nested): result = json_normalize(deep_nested, ['states', 'cities'], meta=['country', ['states', 'name']]) # meta_prefix={'states': 'state_'}) ex_data = {'country': ['USA'] * 4 + ['Germany'] * 3, 'states.name': ['California', 'California', 'Ohio', 'Ohio', 'Bayern', 'Nordrhein-Westfalen', 'Nordrhein-Westfalen'], 'name': ['San Francisco', 'Los Angeles', 'Columbus', 'Cleveland', 'Munich', 'Duesseldorf', 'Koeln'], 'pop': [12345, 12346, 1234, 1236, 12347, 1238, 1239]} expected = DataFrame(ex_data, columns=result.columns) tm.assert_frame_equal(result, expected) def test_shallow_nested(self): data = [{'state': 'Florida', 'shortname': 'FL', 'info': { 'governor': 'Rick Scott' }, 'counties': [{'name': 'Dade', 'population': 12345}, {'name': 'Broward', 'population': 40000}, {'name': 'Palm Beach', 'population': 60000}]}, {'state': 'Ohio', 'shortname': 'OH', 'info': { 'governor': 'John Kasich' }, 'counties': [{'name': 'Summit', 'population': 1234}, {'name': 'Cuyahoga', 'population': 1337}]}] result = json_normalize(data, 'counties', ['state', 'shortname', ['info', 'governor']]) ex_data = {'name': ['Dade', 'Broward', 'Palm Beach', 'Summit', 'Cuyahoga'], 'state': ['Florida'] * 3 + ['Ohio'] * 2, 'shortname': ['FL', 'FL', 'FL', 'OH', 'OH'], 'info.governor': ['Rick Scott'] * 3 + ['John Kasich'] * 2, 'population': [12345, 40000, 60000, 1234, 1337]} expected = DataFrame(ex_data, columns=result.columns) tm.assert_frame_equal(result, expected) def test_meta_name_conflict(self): data = [{'foo': 'hello', 'bar': 'there', 'data': [{'foo': 'something', 'bar': 'else'}, {'foo': 'something2', 'bar': 'else2'}]}] with pytest.raises(ValueError): json_normalize(data, 'data', meta=['foo', 'bar']) result = json_normalize(data, 'data', meta=['foo', 'bar'], meta_prefix='meta') for val in ['metafoo', 'metabar', 'foo', 'bar']: assert val in result def test_meta_parameter_not_modified(self): # GH 18610 data = [{'foo': 'hello', 'bar': 'there', 'data': [{'foo': 'something', 'bar': 'else'}, {'foo': 'something2', 'bar': 'else2'}]}] COLUMNS = ['foo', 'bar'] result = json_normalize(data, 'data', meta=COLUMNS, meta_prefix='meta') assert COLUMNS == ['foo', 'bar'] for val in ['metafoo', 'metabar', 'foo', 'bar']: assert val in result def test_record_prefix(self, state_data): result = json_normalize(state_data[0], 'counties') expected = DataFrame(state_data[0]['counties']) tm.assert_frame_equal(result, expected) result = json_normalize(state_data, 'counties', meta='state', record_prefix='county_') expected = [] for rec in state_data: expected.extend(rec['counties']) expected = DataFrame(expected) expected = expected.rename(columns=lambda x: 'county_' + x) expected['state'] = np.array(['Florida', 'Ohio']).repeat([3, 2]) tm.assert_frame_equal(result, expected) def test_non_ascii_key(self): if compat.PY3: testjson = ( b'[{"\xc3\x9cnic\xc3\xb8de":0,"sub":{"A":1, "B":2}},' + b'{"\xc3\x9cnic\xc3\xb8de":1,"sub":{"A":3, "B":4}}]' ).decode('utf8') else: testjson = ('[{"\xc3\x9cnic\xc3\xb8de":0,"sub":{"A":1, "B":2}},' '{"\xc3\x9cnic\xc3\xb8de":1,"sub":{"A":3, "B":4}}]') testdata = { u'sub.A': [1, 3], u'sub.B': [2, 4], b"\xc3\x9cnic\xc3\xb8de".decode('utf8'): [0, 1] } expected = DataFrame(testdata) result = json_normalize(json.loads(testjson)) tm.assert_frame_equal(result, expected) def test_missing_field(self, author_missing_data): # GH20030: result = json_normalize(author_missing_data) ex_data = [ {'info': np.nan, 'author_name.first': np.nan, 'author_name.last_name': np.nan, 'info.created_at': np.nan, 'info.last_updated': np.nan}, {'info': None, 'author_name.first': 'Jane', 'author_name.last_name': 'Doe', 'info.created_at': '11/08/1993', 'info.last_updated': '26/05/2012'} ] expected = DataFrame(ex_data) tm.assert_frame_equal(result, expected) class TestNestedToRecord(object): def test_flat_stays_flat(self): recs = [dict(flat1=1, flat2=2), dict(flat1=3, flat2=4), ] result = nested_to_record(recs) expected = recs assert result == expected def test_one_level_deep_flattens(self): data = dict(flat1=1, dict1=dict(c=1, d=2)) result = nested_to_record(data) expected = {'dict1.c': 1, 'dict1.d': 2, 'flat1': 1} assert result == expected def test_nested_flattens(self): data = dict(flat1=1, dict1=dict(c=1, d=2), nested=dict(e=dict(c=1, d=2), d=2)) result = nested_to_record(data) expected = {'dict1.c': 1, 'dict1.d': 2, 'flat1': 1, 'nested.d': 2, 'nested.e.c': 1, 'nested.e.d': 2} assert result == expected def test_json_normalize_errors(self): # GH14583: If meta keys are not always present # a new option to set errors='ignore' has been implemented i = { "Trades": [{ "general": { "tradeid": 100, "trade_version": 1, "stocks": [{ "symbol": "AAPL", "name": "Apple", "price": "0" }, { "symbol": "GOOG", "name": "Google", "price": "0" } ] } }, { "general": { "tradeid": 100, "stocks": [{ "symbol": "AAPL", "name": "Apple", "price": "0" }, { "symbol": "GOOG", "name": "Google", "price": "0" } ] } } ] } j = json_normalize(data=i['Trades'], record_path=[['general', 'stocks']], meta=[['general', 'tradeid'], ['general', 'trade_version']], errors='ignore') expected = {'general.trade_version': {0: 1.0, 1: 1.0, 2: '', 3: ''}, 'general.tradeid': {0: 100, 1: 100, 2: 100, 3: 100}, 'name': {0: 'Apple', 1: 'Google', 2: 'Apple', 3: 'Google'}, 'price': {0: '0', 1: '0', 2: '0', 3: '0'}, 'symbol': {0: 'AAPL', 1: 'GOOG', 2: 'AAPL', 3: 'GOOG'}} assert j.fillna('').to_dict() == expected pytest.raises(KeyError, json_normalize, data=i['Trades'], record_path=[['general', 'stocks']], meta=[['general', 'tradeid'], ['general', 'trade_version']], errors='raise' ) def test_donot_drop_nonevalues(self): # GH21356 data = [ {'info': None, 'author_name': {'first': 'Smith', 'last_name': 'Appleseed'} }, {'info': {'created_at': '11/08/1993', 'last_updated': '26/05/2012'}, 'author_name': {'first': 'Jane', 'last_name': 'Doe'} } ] result = nested_to_record(data) expected = [ {'info': None, 'author_name.first': 'Smith', 'author_name.last_name': 'Appleseed'}, {'author_name.first': 'Jane', 'author_name.last_name': 'Doe', 'info.created_at': '11/08/1993', 'info.last_updated': '26/05/2012'}] assert result == expected def test_nonetype_top_level_bottom_level(self): # GH21158: If inner level json has a key with a null value # make sure it doesnt do a new_d.pop twice and except data = { "id": None, "location": { "country": { "state": { "id": None, "town.info": { "id": None, "region": None, "x": 49.151580810546875, "y": -33.148521423339844, "z": 27.572303771972656}}} } } result = nested_to_record(data) expected = { 'id': None, 'location.country.state.id': None, 'location.country.state.town.info.id': None, 'location.country.state.town.info.region': None, 'location.country.state.town.info.x': 49.151580810546875, 'location.country.state.town.info.y': -33.148521423339844, 'location.country.state.town.info.z': 27.572303771972656} assert result == expected def test_nonetype_multiple_levels(self): # GH21158: If inner level json has a key with a null value # make sure it doesnt do a new_d.pop twice and except data = { "id": None, "location": { "id": None, "country": { "id": None, "state": { "id": None, "town.info": { "region": None, "x": 49.151580810546875, "y": -33.148521423339844, "z": 27.572303771972656}}} } } result = nested_to_record(data) expected = { 'id': None, 'location.id': None, 'location.country.id': None, 'location.country.state.id': None, 'location.country.state.town.info.region': None, 'location.country.state.town.info.x': 49.151580810546875, 'location.country.state.town.info.y': -33.148521423339844, 'location.country.state.town.info.z': 27.572303771972656} assert result == expected
louispotok/pandas
pandas/tests/io/json/test_normalize.py
Python
bsd-3-clause
16,104
[ "COLUMBUS" ]
fba875c57e9b3d0e4a4237d7d6c2efcc6768fc77ee09eadef403a79a836c6ae3
# Copyright 2016 United States Government as represented by the Administrator # of the National Aeronautics and Space Administration. All Rights Reserved. # # Portion of this code is Copyright Geoscience Australia, 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 # # The CEOS 2 platform is 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. from django import forms from django.core.validators import RegexValidator, validate_comma_separated_integer_list, validate_slug from django.core import validators from django.db.models import Q import re import datetime from apps.data_cube_manager.models import DatasetType class IngestionMetadataForm(forms.Form): """Form meant to validate all metadata fields for an ingestion configuration file.""" dataset_type_ref = forms.ModelChoiceField( queryset=None, label="Source Dataset Type", help_text="Select an existing source dataset type for this ingestion configuration.", error_messages={'required': 'Source Dataset Type is required.'}, widget=forms.Select(attrs={'class': "onchange_refresh", 'onchange': "update_forms()"}), required=True) output_type = forms.CharField( label="Output Type Name", help_text="Enter a description for this new ingested dataset", error_messages={'required': 'Output Type Name is required.'}, widget=forms.TextInput()) description = forms.CharField( label="Description", help_text="Enter a description for this new ingested dataset", error_messages={'required': "Description is required."}, widget=forms.TextInput()) location = forms.CharField( label="Data Storage Location", help_text="Enter the absolute base path for your storage units", error_messages={'required': 'Data Storage Location is required.'}, widget=forms.TextInput(attrs={'placeholder': "/datacube/ingested_data/"})) file_path_template = forms.CharField( label="Storage Unit Naming Template", help_text="Enter the naming template for your storage units. Available variables include {tile_index[0]}, {tile_index[1]}, and {start_time}. This will be appended to the data storage location to create the path to your storage units.", error_messages={'required': 'Storage Unit Naming Template is required.'}, widget=forms.TextInput(attrs={ 'placeholder': "LS7_ETM_LEDAPS/General/LS7_ETM_LEDAPS_4326_{tile_index[0]}_{tile_index[1]}_{start_time}.nc" })) title = forms.CharField( label="Title", help_text="Enter a title for your new dataset.", error_messages={'required': 'Title is required.'}, widget=forms.TextInput(attrs={'placeholder': "CEOS Data Cube Landsat Surface Reflectance"})) summary = forms.CharField( label="Summary", help_text="Enter a brief summary describing your dataset.", error_messages={'required': 'Summary is required.'}, widget=forms.TextInput( attrs={'placeholder': "Landsat 7 Enhanced Thematic Mapper Plus ARD prepared by NASA on behalf of CEOS."})) source = forms.CharField( label="Source", help_text="Enter the source of your dataset.", error_messages={'required': 'Source is required.'}, widget=forms.TextInput( attrs={'placeholder': "LEDAPS surface reflectance product prepared using USGS Collection 1 data."})) institution = forms.CharField( label="Institution", help_text="Enter your institution affiliation", error_messages={'required': 'Institution is required.'}, initial="CEOS", widget=forms.TextInput(attrs={'placeholder': "CEOS"})) platform = forms.CharField( label="Platform", help_text="Enter your dataset's platform. This should correspond with the source dataset type.", error_messages={'required': 'Platform is required.'}, widget=forms.TextInput(attrs={'placeholder': "LANDSAT_7"})) instrument = forms.CharField( label="Instrument", help_text="Enter this dataset's instrument. This should correspond with the source dataset type.", error_messages={'required': 'Instrument is required.'}, widget=forms.TextInput(attrs={'placeholder': "ETM"})) processing_level = forms.CharField( label="Processing Level", help_text="Enter the processing level for your dataset.", error_messages={'required': 'Processing Level is required.'}, widget=forms.TextInput(attrs={'placeholder': "L2"})) product_version = forms.CharField( label="Product Version", help_text="Enter your product's version.", error_messages={'required': 'Product Version is required.'}, widget=forms.TextInput(attrs={'placeholder': "2.0.0"})) references = forms.CharField( label="References", help_text="Enter any reference links for your dataset.", error_messages={'required': 'References is required.'}, widget=forms.TextInput(attrs={'placeholder': "http://dx.doi.org/10.3334/ORNLDAAC/1146"})) def __init__(self, *args, **kwargs): super(IngestionMetadataForm, self).__init__(*args, **kwargs) self.fields['dataset_type_ref'].queryset = DatasetType.objects.using('agdc').filter(~Q( definition__has_keys=['managed']) & Q(definition__has_keys=['measurements'])) class IngestionBoundsForm(forms.Form): """Form meant to validate the ingestion bounds section of the ingestion configuration file.""" left = forms.FloatField( label="Minimum Longitude", help_text="Enter your desired minimum longitude ingestion bound. Ensure that the maximum value is greater than the minimum value.", required=True, initial=-180, error_messages={ 'required': 'Ingestion bounding box values are required. Please enter a valid number in the Metadata panel.' }) right = forms.FloatField( label="Maximum Longitude", help_text="Enter your desired maximum longitude ingestion bound. Ensure that the maximum value is greater than the minimum value.", required=True, initial=180, error_messages={ 'required': 'Ingestion bounding box values are required. Please enter a valid number in the Metadata panel.' }) bottom = forms.FloatField( label="Minimum Latitude", help_text="Enter your desired minimum latitude ingestion bound. Ensure that the maximum value is greater than the minimum value.", required=True, initial=-90, error_messages={ 'required': 'Ingestion bounding box values are required. Please enter a valid number in the Metadata panel.' }) top = forms.FloatField( label="Maximum Latitude", help_text="Enter your desired maximum latitude ingestion bound. Ensure that the maximum value is greater than the minimum value.", required=True, initial=90, error_messages={ 'required': 'Ingestion bounding box values are required. Please enter a valid number in the Metadata panel.' }) def clean(self, clean=True): cleaned_data = super(IngestionBoundsForm, self).clean() if cleaned_data['left'] > cleaned_data['right']: self.add_error('left', 'The minimum ingestion bound longitude must be less than the maximum longitude.') if cleaned_data['bottom'] > cleaned_data['top']: self.add_error('left', 'The minimum ingestion bound latitude must be less than the maximum latitude.') class IngestionStorageForm(forms.Form): """Validate the storage section of the ingestion configuration file Added additional validation to ensure that the resolution evenly divides into the tile sizing. """ crs = forms.CharField( label="CRS", help_text="Please enter the EPSG code of your desired CRS.", widget=forms.TextInput(attrs={'placeholder': "EPSG:4326"}), initial="EPSG:4326", required=True, error_messages={'required': 'CRS is required. Please enter a valid EPSG code in the metadata panel.'}) units = ["degrees", "meters"] crs_units = forms.ChoiceField( label="CRS Units", help_text="Select the units of your chosen CRS. For Mercator projections this will be meters, while projections like EPSG:4326 will be degrees.", choices=((unit, unit) for unit in units), initial="degrees", required=True) tile_size_longitude = forms.DecimalField( label="Longitude/X Tile Size", help_text="Enter your desired tile size in the units of your CRS. This can be a floating point number, but please ensure that your tile size is evenly divisible by the resolution.", required=True, initial=0.943231048326, decimal_places=12, error_messages={ 'max_decimal_places': "Please ensure that the tile size values do not exceed 12 decimal places.", 'required': 'Tile size is required. Please enter a valid number in the Metadata panel.' }) tile_size_latitude = forms.DecimalField( label="Latitude/Y Tile Size", help_text="Enter your desired tile size in the units of your CRS. This can be a floating point number, but please ensure that your tile size is evenly divisible by the resolution.", required=True, initial=0.943231048326, decimal_places=12, error_messages={ 'max_decimal_places': "Please ensure that the tile size values do not exceed 12 decimal places.", 'required': 'Tile size is required. Please enter a valid number in the Metadata panel.' }) resolution_longitude = forms.DecimalField( label="Longitude/X Resolution", help_text="Enter your desired resolution in the units of your CRS. This can be a floating point number, but please ensure that your tile size is evenly divisible by the resolution", required=True, initial=0.000269494585236, decimal_places=15, error_messages={ 'max_decimal_places': "Please ensure that the resolution values do not exceed 15 decimal places.", 'required': 'Resoultion values are required. Please enter a valid number in the Metadata panel.' }) resolution_latitude = forms.DecimalField( label="Latitude/Y Resolution", help_text="Enter your desired resolution in the units of your CRS. The latitude resolution must be less than zero (negative). This can be a floating point number, but please ensure that your tile size is evenly divisible by the resolution", required=True, initial=-0.000269494585236, decimal_places=15, validators=[validators.MaxValueValidator(0)], error_messages={ 'max_decimal_places': "Please ensure that the resolution values do not exceed 15 decimal places.", 'required': 'Resoultion values are required. Please enter a valid number in the Metadata panel.' }) chunking_longitude = forms.IntegerField( label="Longitude Chunk Size", help_text="Enter the NetCDF internal chunk size in number of pixels.", required=True, initial=200, error_messages={'required': 'Chunk size is required. Pleaes enter a valid integer in the Metadata panel.'}) chunking_latitude = forms.IntegerField( label="Latitude Chunk Size", help_text="Enter the NetCDF internal chunk size in number of pixels.", required=True, initial=200, error_messages={'required': 'Chunk size is required. Pleaes enter a valid integer in the Metadata panel.'}) def clean(self): cleaned_data = super(IngestionStorageForm, self).clean() if not self.is_valid(): return float_casting = ['tile_size_latitude', 'tile_size_longitude', 'resolution_latitude', 'resolution_longitude'] for field in float_casting: self.cleaned_data[field] = float(self.cleaned_data[field]) if (cleaned_data['tile_size_latitude'] / cleaned_data['resolution_latitude']) != int( cleaned_data['tile_size_latitude'] / cleaned_data['resolution_latitude']): self.add_error( 'tile_size_latitude', "Latitude tile size must be evenly divisible by the latitude resolution. Use a precise calculator to ensure that there are no errors in your ingested data." ) if (cleaned_data['tile_size_longitude'] / cleaned_data['resolution_longitude']) != int( cleaned_data['tile_size_longitude'] / cleaned_data['resolution_longitude']): self.add_error( 'tile_size_longitude', "Longitude tile size must be evenly divisible by the longitude resolution. Use a precise calculator to ensure that there are no errors in your ingested data." ) class IngestionMeasurementForm(forms.Form): """Validate the ingestion configuration measurements. These differ slightly from the dataset type fields""" name = forms.CharField( label="Measurement Name", help_text="Please enter the name of the measurement. Spaces and special characters are not allowed.", widget=forms.TextInput(attrs={'placeholder': "swir1"}), required=True, validators=[validate_slug], error_messages={ 'required': 'Measurement name is required. Please enter a valid name in the Measurement panel.' }) dtypes = ["float16", "float32", "int8", "int16", "int32", "uint8"] dtype = forms.ChoiceField( label="Data Type", help_text="Choose your dataset's data type from the provided options.", choices=((dtype, dtype) for dtype in dtypes), initial="int16", required=True) nodata = forms.FloatField( label="Nodata Value", help_text="Please enter the number that represents nodata in your dataset.", required=True, error_messages={'required': 'Nodata value is required. Please enter a valid value in the Measurement panel.'}) resampling_method_choices = ['nearest', 'cubic', 'bilinear', 'cubic_spline', 'lanczos', 'average'] resampling_method = forms.ChoiceField( label="Resampling Method", help_text="Choose your dataset's resampling method.", choices=((method, method) for method in resampling_method_choices), initial="nearest", required=False) src_varname = forms.CharField( label="Source Variable Name", help_text="Enter the source variable name. This should correspond with the measurement from your dataset type.", widget=forms.TextInput(attrs={'placeholder': "sr_band1"}), error_messages={ 'required': 'Source Variable Name is a required field. Please enter a valid string in the Measurement panel.' }, required=True) long_name = forms.CharField( label="Long Name", help_text="Enter a long/descriptive name for this measurement.", widget=forms.TextInput(attrs={'placeholder': "Surface Reflectance 0.63-0.69 microns (Red)"}), required=False) alias = forms.CharField( label="Alias", help_text="Any any alias that exists for your dataset.", widget=forms.TextInput(attrs={'placeholder': "band_3"}), required=False) class IngestionRequestForm(forms.Form): """Information required to submit an ingestion request, including start/end date and geographic bounds. Can be initialized as a bound form with initial data or as a readonly form """ dataset_type_ref = forms.ModelChoiceField( queryset=None, label="Source Dataset Type", help_text="Select an existing source dataset type for this ingestion configuration.", error_messages={'required': 'Source Dataset Type is required.'}, widget=forms.Select(attrs={'class': "onchange_refresh onchange_filter", 'onchange': "update_forms()"}), required=False) start_date = forms.DateField( label='Start Date', error_messages={'required': 'Start date is required.'}, widget=forms.DateInput(attrs={'class': 'datepicker field-divided onchange_filter', 'placeholder': '01/01/2010'})) end_date = forms.DateField( label='End Date', error_messages={'required': 'End date is required.'}, widget=forms.DateInput(attrs={'class': 'datepicker field-divided onchange_filter', 'placeholder': '01/02/2010'})) latitude_min = forms.FloatField( label='Min Latitude', validators=[validators.MaxValueValidator(90), validators.MinValueValidator(-90)], error_messages={'required': 'Latitude min is required.'}, widget=forms.NumberInput(attrs={'class': 'field-divided onchange_filter', 'step': "any", 'min': -90, 'max': 90})) latitude_max = forms.FloatField( label='Max Latitude', validators=[validators.MaxValueValidator(90), validators.MinValueValidator(-90)], error_messages={'required': 'Latitude max is required.'}, widget=forms.NumberInput(attrs={'class': 'field-divided onchange_filter', 'step': "any", 'min': -90, 'max': 90})) longitude_min = forms.FloatField( label='Min Longitude', validators=[validators.MaxValueValidator(180), validators.MinValueValidator(-180)], error_messages={'required': 'Longitude min is required.'}, widget=forms.NumberInput( attrs={'class': 'field-divided onchange_filter', 'step': "any", 'min': -180, 'max': 180})) longitude_max = forms.FloatField( label='Max Longitude', validators=[validators.MaxValueValidator(180), validators.MinValueValidator(-180)], error_messages={'required': 'Longitude max is required.'}, widget=forms.NumberInput( attrs={'class': 'field-divided onchange_filter', 'step': "any", 'min': -180, 'max': 180})) def __init__(self, *args, **kwargs): """Initialize the ingestion request form with optional kwargs Args: initial_vals: dict with form data - sets initial rather than binding readonly: boolean value signifying whether or not this form should be modified. """ initial_vals = kwargs.pop('initial', None) readonly = kwargs.pop('readonly', None) super(IngestionRequestForm, self).__init__(*args, **kwargs) self.fields['dataset_type_ref'].queryset = DatasetType.objects.using('agdc').filter( Q(definition__has_keys=['managed']) & Q(definition__has_keys=['measurements'])) if initial_vals: for field in initial_vals: self.fields[field].initial = initial_vals[field] if readonly: self.fields['dataset_type_ref'].queryset = DatasetType.objects.using('agdc').filter( id=initial_vals['dataset_type_ref']) for field in self.fields: self.fields[field].widget.attrs['readonly'] = True def clean(self): """Validate the ingestion form - similar to dataset form but with required fields Does the +- 0.01 to avoid rounding issues and checks for a max 1deg area. """ cleaned_data = super(IngestionRequestForm, self).clean() if not self.is_valid(): return # this id done to get rid of some weird rounding issues - a lot of the solid BBs end up being 3.999999999123412 rather than # the expected 4 cleaned_data['latitude_min'] -= 0.01 cleaned_data['longitude_min'] -= 0.01 cleaned_data['latitude_max'] += 0.01 cleaned_data['longitude_max'] += 0.01 if cleaned_data.get('latitude_min') > cleaned_data.get('latitude_max'): self.add_error( 'latitude_min', "Please enter a valid pair of latitude values where the lower bound is less than the upper bound.") if cleaned_data.get('longitude_min') > cleaned_data.get('longitude_max'): self.add_error( 'longitude_min', "Please enter a valid pair of longitude values where the lower bound is less than the upper bound.") area = (cleaned_data.get('latitude_max') - cleaned_data.get('latitude_min')) * ( cleaned_data.get('longitude_max') - cleaned_data.get('longitude_min')) if area > 1.05: self.add_error('latitude_min', 'Tasks over an area greater than one square degrees are not permitted.') if cleaned_data.get('start_date') > cleaned_data.get('end_date'): self.add_error('start_date', "Please enter a valid start and end time range where the start is before the end.") if (cleaned_data.get('end_date') - cleaned_data.get('start_date')).days > 367: self.add_error('start_date', "Please enter a date range of less than one year.") self.cleaned_data = cleaned_data
ceos-seo/data_cube_ui
apps/data_cube_manager/forms/ingestion.py
Python
apache-2.0
22,231
[ "NetCDF" ]
1364cf1808c0c5a43a9d3fc1853054891173e9256d00974aaa436247a7c216fa
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """WebsiteTest testing class.""" import logging import time from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys import environment SCRIPT_DEBUG = 9 # TODO(vabr) -- make this consistent with run_tests.py. class WebsiteTest: """WebsiteTest testing class. Represents one website, defines some generic operations on that site. To customise for a particular website, this class needs to be inherited and the Login() method overridden. """ # Possible values of self.autofill_expectation. AUTOFILLED = 1 # Expect password and username to be autofilled. NOT_AUTOFILLED = 2 # Expect password and username not to be autofilled. # The maximal accumulated time to spend in waiting for website UI # interaction. MAX_WAIT_TIME_IN_SECONDS = 200 def __init__(self, name, username_not_auto=False, password_not_auto=False): """Creates a new WebsiteTest. Args: name: The website name, identifying it in the test results. username_not_auto: Expect that the tested website fills username field on load, and Chrome cannot autofill in that case. password_not_auto: Expect that the tested website fills password field on load, and Chrome cannot autofill in that case. """ self.name = name self.username = None self.password = None self.username_not_auto = username_not_auto self.password_not_auto = password_not_auto # Specify, whether it is expected that credentials get autofilled. self.autofill_expectation = WebsiteTest.NOT_AUTOFILLED self.remaining_seconds_to_wait = WebsiteTest.MAX_WAIT_TIME_IN_SECONDS # The testing Environment, if added to any. self.environment = None # The webdriver from the environment. self.driver = None # Mouse/Keyboard actions. def Click(self, selector): """Clicks on the element described by |selector|. Args: selector: The clicked element's CSS selector. """ logging.log(SCRIPT_DEBUG, "action: Click %s" % selector) element = self.WaitUntilDisplayed(selector) element.click() def ClickIfClickable(self, selector): """Clicks on the element described by |selector| if it is clickable. The driver's find_element_by_css_selector method defines what is clickable -- anything for which it does not throw, is clickable. To be clickable, the element must: * exist in the DOM, * be not covered by another element * be inside the visible area. Note that transparency does not influence clickability. Args: selector: The clicked element's CSS selector. Returns: True if the element is clickable (and was clicked on). False otherwise. """ logging.log(SCRIPT_DEBUG, "action: ClickIfVisible %s" % selector) element = self.WaitUntilDisplayed(selector) try: element.click() return True except Exception: return False def GoTo(self, url): """Navigates the main frame to |url|. Args: url: The URL of where to go to. """ logging.log(SCRIPT_DEBUG, "action: GoTo %s" % self.name) self.driver.get(url) def HoverOver(self, selector): """Hovers over the element described by |selector|. Args: selector: The CSS selector of the element to hover over. """ logging.log(SCRIPT_DEBUG, "action: Hover %s" % selector) element = self.WaitUntilDisplayed(selector) hover = ActionChains(self.driver).move_to_element(element) hover.perform() # Waiting/Displaying actions. def _ReturnElementIfDisplayed(self, selector): """Returns the element described by |selector|, if displayed. Note: This takes neither overlapping among elements nor position with regards to the visible area into account. Args: selector: The CSS selector of the checked element. Returns: The element if displayed, None otherwise. """ try: element = self.driver.find_element_by_css_selector(selector) return element if element.is_displayed() else None except Exception: return None def IsDisplayed(self, selector): """Check if the element described by |selector| is displayed. Note: This takes neither overlapping among elements nor position with regards to the visible area into account. Args: selector: The CSS selector of the checked element. Returns: True if the element is in the DOM and less than 100% transparent. False otherwise. """ logging.log(SCRIPT_DEBUG, "action: IsDisplayed %s" % selector) return self._ReturnElementIfDisplayed(selector) is not None def Wait(self, duration): """Wait for |duration| in seconds. To avoid deadlocks, the accummulated waiting time for the whole object does not exceed MAX_WAIT_TIME_IN_SECONDS. Args: duration: The time to wait in seconds. Raises: Exception: In case the accummulated waiting limit is exceeded. """ logging.log(SCRIPT_DEBUG, "action: Wait %s" % duration) self.remaining_seconds_to_wait -= duration if self.remaining_seconds_to_wait < 0: raise Exception("Waiting limit exceeded for website: %s" % self.name) time.sleep(duration) # TODO(vabr): Pull this out into some website-utils and use in Environment # also? def WaitUntilDisplayed(self, selector): """Waits until the element described by |selector| is displayed. Args: selector: The CSS selector of the element to wait for. Returns: The displayed element. """ element = self._ReturnElementIfDisplayed(selector) while not element: self.Wait(1) element = self._ReturnElementIfDisplayed(selector) return element # Form actions. def FillPasswordInto(self, selector): """Ensures that the selected element's value is the saved password. Depending on self.autofill_expectation, this either checks that the element already has the password autofilled, or checks that the value is empty and replaces it with the password. If self.password_not_auto is true, it skips the checks and just overwrites the value with the password. Args: selector: The CSS selector for the filled element. Raises: Exception: An exception is raised if the element's value is different from the expectation. """ logging.log(SCRIPT_DEBUG, "action: FillPasswordInto %s" % selector) password_element = self.WaitUntilDisplayed(selector) # Chrome protects the password inputs and doesn't fill them until # the user interacts with the page. To be sure that such thing has # happened we perform |Keys.CONTROL| keypress. action_chains = ActionChains(self.driver) action_chains.key_down(Keys.CONTROL).key_up(Keys.CONTROL).perform() self.Wait(2) # TODO(vabr): Detect when autofill finished. if not self.password_not_auto: if self.autofill_expectation == WebsiteTest.AUTOFILLED: if password_element.get_attribute("value") != self.password: raise Exception("Error: autofilled password is different from the" "saved one on website: %s" % self.name) elif self.autofill_expectation == WebsiteTest.NOT_AUTOFILLED: if password_element.get_attribute("value"): raise Exception("Error: password value unexpectedly not empty on" "website: %s" % self.name) password_element.clear() password_element.send_keys(self.password) def FillUsernameInto(self, selector): """Ensures that the selected element's value is the saved username. Depending on self.autofill_expectation, this either checks that the element already has the username autofilled, or checks that the value is empty and replaces it with the password. If self.username_not_auto is true, it skips the checks and just overwrites the value with the username. Args: selector: The CSS selector for the filled element. Raises: Exception: An exception is raised if the element's value is different from the expectation. """ logging.log(SCRIPT_DEBUG, "action: FillUsernameInto %s" % selector) username_element = self.WaitUntilDisplayed(selector) self.Wait(2) # TODO(vabr): Detect when autofill finished. if not self.username_not_auto: if self.autofill_expectation == WebsiteTest.AUTOFILLED: if username_element.get_attribute("value") != self.username: raise Exception("Error: filled username different from the saved" " one on website: %s" % self.name) return if self.autofill_expectation == WebsiteTest.NOT_AUTOFILLED: if username_element.get_attribute("value"): raise Exception("Error: username value unexpectedly not empty on" "website: %s" % self.name) username_element.clear() username_element.send_keys(self.username) def Submit(self, selector): """Finds an element using CSS |selector| and calls its submit() handler. Args: selector: The CSS selector for the element to call submit() on. """ logging.log(SCRIPT_DEBUG, "action: Submit %s" % selector) element = self.WaitUntilDisplayed(selector) element.submit() # Login/Logout methods def Login(self): """Login Method. Has to be overridden by the WebsiteTest test.""" raise NotImplementedError("Login is not implemented.") def LoginWhenAutofilled(self): """Logs in and checks that the password is autofilled.""" self.autofill_expectation = WebsiteTest.AUTOFILLED self.Login() def LoginWhenNotAutofilled(self): """Logs in and checks that the password is not autofilled.""" self.autofill_expectation = WebsiteTest.NOT_AUTOFILLED self.Login() def Logout(self): self.environment.DeleteCookies() # Test scenarios def PromptFailTest(self): """Checks that prompt is not shown on a failed login attempt. Tries to login with a wrong password and checks that the password is not offered for saving. Raises: Exception: An exception is raised if the test fails. """ logging.log(SCRIPT_DEBUG, "PromptFailTest for %s" % self.name) correct_password = self.password # Hardcoded random wrong password. Chosen by fair `pwgen` call. # For details, see: http://xkcd.com/221/. self.password = "ChieF2ae" self.LoginWhenNotAutofilled() self.password = correct_password self.environment.CheckForNewString( [environment.MESSAGE_ASK, environment.MESSAGE_SAVE], False, "Error: did not detect wrong login on website: %s" % self.name) def PromptSuccessTest(self): """Checks that prompt is shown on a successful login attempt. Tries to login with a correct password and checks that the password is offered for saving. Chrome cannot have the auto-save option on when running this test. Raises: Exception: An exception is raised if the test fails. """ logging.log(SCRIPT_DEBUG, "PromptSuccessTest for %s" % self.name) if not self.environment.show_prompt: raise Exception("Switch off auto-save during PromptSuccessTest.") self.LoginWhenNotAutofilled() self.environment.CheckForNewString( [environment.MESSAGE_ASK], True, "Error: did not detect login success on website: %s" % self.name) def SaveAndAutofillTest(self): """Checks that a correct password is saved and autofilled. Tries to login with a correct password and checks that the password is saved and autofilled on next visit. Chrome must have the auto-save option on when running this test. Raises: Exception: An exception is raised if the test fails. """ logging.log(SCRIPT_DEBUG, "SaveAndAutofillTest for %s" % self.name) if self.environment.show_prompt: raise Exception("Switch off auto-save during PromptSuccessTest.") self.LoginWhenNotAutofilled() self.environment.CheckForNewString( [environment.MESSAGE_SAVE], True, "Error: did not detect login success on website: %s" % self.name) self.Logout() self.LoginWhenAutofilled() self.environment.CheckForNewString( [environment.MESSAGE_SAVE], True, "Error: failed autofilled login on website: %s" % self.name)
axinging/chromium-crosswalk
components/test/data/password_manager/automated_tests/websitetest.py
Python
bsd-3-clause
12,521
[ "VisIt" ]
83332e7bc9809217bbd5749bc8eba299cffaee8e2f9923f0fd5c0fa5bbded641
#!/usr/bin/env python # # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2021 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3. # # Psi4 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along # with Psi4; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # @END LICENSE # """Run on a single gbs file to get a periodic table printout or on two to compare gbs contents.""" from __future__ import print_function import os import sys import subprocess qcdb_module = os.path.normpath(os.path.dirname(os.path.abspath(__file__)) + '../../../../../driver') sys.path.append(qcdb_module) import qcdb from qcdb.libmintsbasissetparser import Gaussian94BasisSetParser import qcelemental as qcel class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def bas_sanitize(fl): if fl[-4] == '.gbs': fl = fl[:-4] return fl.lower().replace('+', 'p').replace('*', 's').replace('(', '_').replace(')', '_').replace(',', '_') parser = Gaussian94BasisSetParser() elements = qcel.periodictable.E os.system("echo '#differing basis sets' > basisdunningdiffer.txt") with open(sys.argv[1], 'r') as basfile: bascontents = basfile.readlines() bname = bas_sanitize(sys.argv[1]) isdiff = False if len(sys.argv) > 2: isdiff = True with open(sys.argv[2], 'r') as reffile: refcontents = reffile.readlines() rname = bas_sanitize(os.path.basename(sys.argv[2])) if isdiff: if bname != rname: print('%s / %s' % (bname, rname), end='') else: print('%-40s' % (bname), end='') else: print('%-40s' % (bname), end='') anychange = False forbiddenchange = False postKr = False for el in elements: if el.upper() == "RB": postKr = True shells, msg, ecp_shells, ecp_msg, ecp_ncore = parser.parse(el.upper(), bascontents) if isdiff: rshells, rmsg, recp_shells, recp_msg, recp_ncore = parser.parse(el.upper(), refcontents) if not shells and not rshells: print('%s' % ('' if postKr else ' '), end='') continue if shells and not rshells: print(bcolors.OKBLUE + '{:3}'.format(el.upper()) + bcolors.ENDC, end='') anychange = True if not shells and rshells: print(bcolors.FAIL + '{:3}'.format(el.upper()) + bcolors.ENDC, end='') anychange = True forbiddenchange = True if shells and rshells: mol = qcdb.Molecule("""\n{}\n""".format(el)) mol.update_geometry() mol.set_basis_all_atoms(bname, role='BASIS') bdict = {bname: ''.join(bascontents)} rdict = {bname: ''.join(refcontents)} bs, msg, ecp = qcdb.BasisSet.construct(parser, mol, 'BASIS', None, bdict, False) rbs, rmsg, recp = qcdb.BasisSet.construct(parser, mol, 'BASIS', None, rdict, False) if bs == rbs: print('{:3}'.format(el.lower()), end='') else: print(bcolors.WARNING + '{:3}'.format(el.upper()) + bcolors.ENDC, end='') anychange = True tbs = bs.print_detail(out='tmpB.txt') rtbs = rbs.print_detail(out='tmpR.txt') try: outdiff = subprocess.check_output("diff -bwy -W 180 tmpB.txt tmpR.txt >> basisdunningdiffer.txt", shell=True) #outdiff = subprocess.check_output("diff -bw --context=1 tmpB.txt tmpR.txt >> basisdunningdiffer.txt", shell=True) except subprocess.CalledProcessError: pass else: if not shells: print('%s' % ('' if postKr else ' '), end='') else: print('{:3}'.format(el.lower()), end='') print('') if anychange and not forbiddenchange: os.system("echo 'mv {} ../' >> basisdunningfiles.txt".format(sys.argv[1]))
ashutoshvt/psi4
psi4/share/psi4/basis/primitives/diff_gbs.py
Python
lgpl-3.0
4,597
[ "Psi4" ]
9348668487059faa972c997652759b1177cf686be2d8355286de3dcf5ebe90d2
from ..errors import AngrExitError from . import ExplorationTechnique import logging l = logging.getLogger(name=__name__) class Slicecutor(ExplorationTechnique): """ The Slicecutor is an exploration that executes provided code slices. """ def __init__(self, annotated_cfg, force_taking_exit=False, force_sat: bool=False): """ All parameters except `annotated_cfg` are optional. :param annotated_cfg: The AnnotatedCFG that provides the code slice. :param force_taking_exit: Set to True if you want to create a successor based on our slice in case of unconstrained successors. :param force_sat: If a branch specified by the slice is unsatisfiable, set this option to True if you want to force it to be satisfiable and be taken anyway. """ super(Slicecutor, self).__init__() self._annotated_cfg = annotated_cfg self._force_taking_exit = force_taking_exit self._force_sat = force_sat def setup(self, simgr): for stash in ('cut', 'mysteries'): simgr.populate(stash, []) def filter(self, simgr, state, **kwargs): l.debug("Checking state %s for filtering...", state) return simgr.filter(state, **kwargs) def step_state(self, simgr, state, **kwargs): l.debug("%s ticking state %s at address %#x.", self, state, state.addr) stashes = simgr.step_state(state, **kwargs) new_active = [] new_cut = [] new_mystery = [] # SimulationManager returns new active states in the None stash by default. flat_successors = stashes.get(None, None) if flat_successors is None: # Did the user explicitly put them into the 'active' stash instead? flat_successors = stashes.pop('active', []) for successor in flat_successors: l.debug("... checking exit to %#x from %#x.", successor.addr, state.addr) try: taken = self._annotated_cfg.should_take_exit(state.addr, successor.addr) except AngrExitError: # TODO: which exception? l.debug("... annotated CFG did not know about it!") new_mystery.append(successor) else: if taken: l.debug("... taking the exit.") new_active.append(successor) # the else case isn't here, because the state should set errored in this # case and we'll catch it below else: l.debug("... not taking the exit.") new_cut.append(successor) unconstrained_successors = stashes.get('unconstrained', []) if not new_active and unconstrained_successors and self._force_taking_exit: stashes['unconstrained'] = [] # somehow there is no feasible state. We are forced to create a successor based on our slice if len(unconstrained_successors) != 1: raise Exception("This should absolutely never happen, what?") for target in self._annotated_cfg.get_targets(state.addr): successor = unconstrained_successors[0].copy() successor.regs._ip = target new_active.append(successor) l.debug('Got unconstrained: %d new states are created based on AnnotatedCFG.', len(new_active)) unsat_successors = stashes.get('unsat', None) if not new_active and unsat_successors and self._force_sat: stashes['unsat'] = [] # find the state targets = self._annotated_cfg.get_targets(state.addr) if targets is None: targets = [ ] for target in targets: try: suc = next(iter(u for u in unsat_successors if u.addr == target)) except StopIteration: continue # drop all constraints if suc.mode == "fastpath": # dropping constraints and making the state satisfiable again under fastpath mode is easy suc.solver._solver.constraints = [ ] suc._satisfiable = True new_active.append(suc) l.debug("Forced unsat at %#x to be sat again.", suc.addr) else: # with multiple possible solver frontends, dropping states in other state modes is not # straightforward. I'll leave it to the next person who uses this feature l.warning("force_sat is not implemented for solver mode %s.", suc.moe) stashes[None] = new_active stashes['mystery'] = new_mystery stashes['cut'] = new_cut return stashes def successors(self, simgr, state, **kwargs): kwargs['whitelist'] = self._annotated_cfg.get_whitelisted_statements(state.addr) kwargs['last_stmt'] = self._annotated_cfg.get_last_statement_index(state.addr) return simgr.successors(state, **kwargs)
angr/angr
angr/exploration_techniques/slicecutor.py
Python
bsd-2-clause
5,141
[ "MOE" ]
f9c397ea091b461ed494cf7f5ddfd5e2af5d03fb4b1ccd4027687ad0b707fdaa
#!/usr/bin/env python """ """ import vtk def main(): colors = vtk.vtkNamedColors() fileName = get_program_parameters() # Read the image. readerFactory = vtk.vtkImageReader2Factory() reader = readerFactory.CreateImageReader2(fileName) reader.SetFileName(fileName) reader.Update() fft = vtk.vtkImageFFT() fft.SetInputConnection(reader.GetOutputPort()) mag = vtk.vtkImageMagnitude() mag.SetInputConnection(fft.GetOutputPort()) center = vtk.vtkImageFourierCenter() center.SetInputConnection(mag.GetOutputPort()) compress = vtk.vtkImageLogarithmicScale() compress.SetInputConnection(center.GetOutputPort()) compress.SetConstant(15) compress.Update() # Create the actors. originalActor = vtk.vtkImageActor() originalActor.GetMapper().SetInputConnection(reader.GetOutputPort()) originalActor.GetProperty().SetInterpolationTypeToNearest() compressedActor = vtk.vtkImageActor() compressedActor.GetMapper().SetInputConnection(compress.GetOutputPort()) compressedActor.GetProperty().SetInterpolationTypeToNearest() CreateImageActor(compressedActor, 160, 120) # Define the viewport ranges. # (xmin, ymin, xmax, ymax) originalViewport = [0.0, 0.0, 0.5, 1.0] compressedViewport = [0.5, 0.0, 1.0, 1.0] # Setup the renderers. originalRenderer = vtk.vtkRenderer() originalRenderer.SetViewport(originalViewport) originalRenderer.AddActor(originalActor) originalRenderer.ResetCamera() originalRenderer.SetBackground(colors.GetColor3d("SlateGray")) compressedRenderer = vtk.vtkRenderer() compressedRenderer.SetViewport(compressedViewport) compressedRenderer.AddActor(compressedActor) compressedRenderer.ResetCamera() compressedRenderer.SetBackground(colors.GetColor3d("LightSlateGray")) renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(600, 300) renderWindow.AddRenderer(originalRenderer) renderWindow.AddRenderer(compressedRenderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() style = vtk.vtkInteractorStyleImage() renderWindowInteractor.SetInteractorStyle(style) renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.Initialize() renderWindowInteractor.Start() def get_program_parameters(): import argparse description = 'The discrete Fourier transform.' epilogue = ''' This changes an image from the spatial domain into the frequency domain, where each pixel represents a sinusoidal function. This figure shows an image and its power spectrum displayed using a logarithmic transfer function. ''' parser = argparse.ArgumentParser(description=description, epilog=epilogue, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('filename', help='vtks.pgm.') args = parser.parse_args() return args.filename def CreateImageActor(actor, colorWindow, colorLevel): wlut = vtk.vtkWindowLevelLookupTable() wlut.SetWindow(colorWindow) wlut.SetLevel(colorLevel) wlut.Build() # Map the image through the lookup table. color = vtk.vtkImageMapToColors() color.SetLookupTable(wlut) color.SetInputData(actor.GetMapper().GetInput()) actor.GetMapper().SetInputConnection(color.GetOutputPort()) return if __name__ == '__main__': main()
lorensen/VTKExamples
src/Python/ImageProcessing/VTKSpectrum.py
Python
apache-2.0
3,417
[ "VTK" ]
741dc56ac57fd6e169063dec99c8c7fc275482c9bf79c1da8b5e65f576e717a5
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Bsseeker2(Package): """A versatile aligning pipeline for bisulfite sequencing data.""" homepage = "http://pellegrini.mcdb.ucla.edu/BS_Seeker2" url = "https://github.com/BSSeeker/BSseeker2/archive/v2.1.2.tar.gz" version('2.1.2', '5f7f0ef4071711e56b59c5c16b7f34a7') depends_on('python@2.6:2.999', type=('build', 'run')) depends_on('py-pysam', type=('build', 'run')) def install(self, spec, prefix): mkdirp(prefix.bin) install('Antisense.py', prefix.bin) install_tree('bs_index', prefix.bin.bs_index) install('bs_seeker2-build.py', prefix.bin) install_tree('bs_utils', prefix.bin.bs_utils) install_tree('galaxy', prefix.bin.galaxy) install_tree('bs_align', prefix.bin.bs_align) install('bs_seeker2-align.py', prefix.bin) install('bs_seeker2-call_methylation.py', prefix.bin) install('FilterReads.py', prefix.bin)
wscullin/spack
var/spack/repos/builtin/packages/bsseeker2/package.py
Python
lgpl-2.1
2,193
[ "Galaxy", "pysam" ]
f1e428ce779096c94507637bee2097a15e67deb5afbfc57be7bcd6e9fd1ec113
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time # !! This is the configuration of Nikola. !! # # !! You should edit it to your liking. !! # # ! Some settings can be different in different languages. # ! A comment stating (translatable) is used to denote those. # ! There are two ways to specify a translatable setting: # ! (a) BLOG_TITLE = "My Blog" # ! (b) BLOG_TITLE = {"en": "My Blog", "es": "Mi Blog"} # ! Option (a) is used when you don't want that setting translated. # ! Option (b) is used for settings that are different in different languages. # Data about this site BLOG_AUTHOR = "Kyle Kastner" # (translatable) BLOG_TITLE = "Garbage In Garbage Out" # (translatable) # This is the main URL for your site. It will be used # in a prominent link SITE_URL = "https://kastnerkyle.github.io/" # This is the URL where Nikola's output will be deployed. # If not set, defaults to SITE_URL # BASE_URL = "https://kastnerkyle.github.io/" BLOG_EMAIL = "kastnerkyle+blogsite@gmail.com" BLOG_DESCRIPTION = "A blog about many things" # (translatable) # Nikola is multilingual! # # Currently supported languages are: # # en English # ar Arabic # az Azerbaijani # bg Bulgarian # ca Catalan # cs Czech [ALTERNATIVELY cz] # da Danish # de German # el Greek [NOT gr] # eo Esperanto # es Spanish # et Estonian # eu Basque # fa Persian # fi Finnish # fr French # hi Hindi # hr Croatian # id Indonesian # it Italian # ja Japanese [NOT jp] # ko Korean # nb Norwegian Bokmål # nl Dutch # pl Polish # pt_br Portuguese (Brasil) # ru Russian # sk Slovak # sl Slovene # sr Serbian (Cyrillic) # sv Swedish # tr Turkish [NOT tr_TR] # uk Ukrainian # ur Urdu # zh_cn Chinese (Simplified) # # If you want to use Nikola with a non-supported language you have to provide # a module containing the necessary translations # (cf. the modules at nikola/data/themes/base/messages/). # If a specific post is not translated to a language, then the version # in the default language will be shown instead. # What is the default language? DEFAULT_LANG = "en" # What other languages do you have? # The format is {"translationcode" : "path/to/translation" } # the path will be used as a prefix for the generated pages location TRANSLATIONS = { DEFAULT_LANG: "", # Example for another language: # "es": "./es", } # What will translated input files be named like? # If you have a page something.rst, then something.pl.rst will be considered # its Polish translation. # (in the above example: path == "something", ext == "rst", lang == "pl") # this pattern is also used for metadata: # something.meta -> something.pl.meta TRANSLATIONS_PATTERN = "{path}.{lang}.{ext}" # Links for the sidebar / navigation bar. (translatable) # This is a dict. The keys are languages, and values are tuples. # # For regular links: # ('https://getnikola.com/', 'Nikola Homepage') # # For submenus: # ( # ( # ('http://apple.com/', 'Apple'), # ('http://orange.com/', 'Orange'), # ), # 'Fruits' # ) # # WARNING: Support for submenus is theme-dependent. # Only one level of submenus is supported. # WARNING: Some themes, including the default Bootstrap 3 theme, # may present issues if the menu is too large. # (in bootstrap3, the navbar can grow too large and cover contents.) # WARNING: If you link to directories, make sure to follow # ``STRIP_INDEXES``. If it’s set to ``True``, end your links # with a ``/``, otherwise end them with ``/index.html`` — or # else they won’t be highlighted when active. NAVIGATION_LINKS = { DEFAULT_LANG: ( ( ( ('http://scikit-learn.org', "scikit-learn"), ('http://sklearn-theano.github.io', "sklearn-theano"), ('http://github.com/dagbldr/dagbldr', "dagbldr"), ('http://github.com/tensorlib/tensorlib', "tensorlib"), ('http://github.com/kastnerkyle/arrayprocessing', "arrayprocessing"), ), "Projects I Am Involved In", ), ( ( ('http://kkjkok.blogspot.com/', "MyOtherNotes"), ('http://pushbuttonrobotics.weebly.com/', "PushButtonRobotics"), ('http://www.fastml.com/', "FastML"), ('http://mlwave.com/', "MLWave"), ('http://snippyhollow.github.io/', "SnippyHollow"), ('http://blog.smellthedata.com/', "SmellTheData"), ('http://jakevdp.github.io/', "PythonicPerambulations") ), "Good Blogs", ), ( ( ('http://github.com/kastnerkyle', "GitHub"), ('http://twitter.com/kastnerkyle', "Twitter"), ('http://plus.google.com/+KyleKastner', "Google+"), ('http://www.linkedin.com/pub/kyle-kastner/24/605/4a1', "LinkedIn"), ('http://www.kaggle.com/users/107564/kyle-kastner', "Kaggle"), ), "Social Media", ), ("/archive.html", "Archive"), ("/categories/index.html", "Tags"), ("/rss.xml", "RSS feed"), ), } # Name of the theme to use. THEME = "ipython" # Below this point, everything is optional # Post's dates are considered in UTC by default, if you want to use # another time zone, please set TIMEZONE to match. Check the available # list from Wikipedia: # http://en.wikipedia.org/wiki/List_of_tz_database_time_zones # (e.g. 'Europe/Zurich') # Also, if you want to use a different time zone in some of your posts, # you can use the ISO 8601/RFC 3339 format (ex. 2012-03-30T23:00:00+02:00) TIMEZONE = "America/New_York" # If you want to use ISO 8601 (also valid RFC 3339) throughout Nikola # (especially in new_post), set this to True. # Note that this does not affect DATE_FORMAT. # FORCE_ISO8601 = False # Date format used to display post dates. # (str used by datetime.datetime.strftime) # DATE_FORMAT = '%Y-%m-%d %H:%M' # Date format used to display post dates, if local dates are used. # (str used by moment.js) # JS_DATE_FORMAT = 'YYYY-MM-DD HH:mm' # Date fanciness. # # 0 = using DATE_FORMAT and TIMEZONE # 1 = using JS_DATE_FORMAT and local user time (via moment.js) # 2 = using a string like “2 days ago” # # Your theme must support it, bootstrap and bootstrap3 already do. # DATE_FANCINESS = 0 # While Nikola can select a sensible locale for each language, # sometimes explicit control can come handy. # In this file we express locales in the string form that # python's locales will accept in your OS, by example # "en_US.utf8" in Unix-like OS, "English_United States" in Windows. # LOCALES = dict mapping language --> explicit locale for the languages # in TRANSLATIONS. You can omit one or more keys. # LOCALE_FALLBACK = locale to use when an explicit locale is unavailable # LOCALE_DEFAULT = locale to use for languages not mentioned in LOCALES; if # not set the default Nikola mapping is used. # POSTS and PAGES contains (wildcard, destination, template) tuples. # # The wildcard is used to generate a list of reSt source files # (whatever/thing.txt). # # That fragment could have an associated metadata file (whatever/thing.meta), # and optionally translated files (example for Spanish, with code "es"): # whatever/thing.es.txt and whatever/thing.es.meta # # This assumes you use the default TRANSLATIONS_PATTERN. # # From those files, a set of HTML fragment files will be generated: # cache/whatever/thing.html (and maybe cache/whatever/thing.html.es) # # These files are combined with the template to produce rendered # pages, which will be placed at # output / TRANSLATIONS[lang] / destination / pagename.html # # where "pagename" is the "slug" specified in the metadata file. # # The difference between POSTS and PAGES is that POSTS are added # to feeds and are considered part of a blog, while PAGES are # just independent HTML pages. # POSTS = ( ("posts/*.md", "posts", "post.tmpl"), ("posts/*.ipynb", "posts", "post.tmpl"), ("posts/*.txt", "posts", "post.tmpl"), ("posts/*.rst", "posts", "post.tmpl"), ) PAGES = ( ("stories/*.md", "stories", "story.tmpl"), ("stories/*.ipynb", "stories", "story.tmpl"), ("stories/*.txt", "stories", "story.tmpl"), ("stories/*.rst", "stories", "story.tmpl"), ) # One or more folders containing files to be copied as-is into the output. # The format is a dictionary of {source: relative destination}. # Default is: # FILES_FOLDERS = {'files': ''} # Which means copy 'files' into 'output' # One or more folders containing listings to be processed and stored into # the output. The format is a dictionary of {source: relative destination}. # Default is: # LISTINGS_FOLDERS = {'listings': 'listings'} # Which means process listings from 'listings' into 'output/listings' # A mapping of languages to file-extensions that represent that language. # Feel free to add or delete extensions to any list, but don't add any new # compilers unless you write the interface for it yourself. # # 'rest' is reStructuredText # 'markdown' is MarkDown # 'html' assumes the file is HTML and just copies it COMPILERS = { "rest": ('.rst', '.txt'), "markdown": ('.md', '.mdown', '.markdown'), "textile": ('.textile',), "txt2tags": ('.t2t',), "bbcode": ('.bb',), "wiki": ('.wiki',), "ipynb": ('.ipynb',), "html": ('.html', '.htm'), # PHP files are rendered the usual way (i.e. with the full templates). # The resulting files have .php extensions, making it possible to run # them without reconfiguring your server to recognize them. "php": ('.php',), # Pandoc detects the input from the source filename # but is disabled by default as it would conflict # with many of the others. # "pandoc": ('.rst', '.md', '.txt'), } # Create by default posts in one file format? # Set to False for two-file posts, with separate metadata. ONE_FILE_POSTS = False # If this is set to True, the DEFAULT_LANG version will be displayed for # untranslated posts. # If this is set to False, then posts that are not translated to a language # LANG will not be visible at all in the pages in that language. # Formerly known as HIDE_UNTRANSLATED_POSTS (inverse) # SHOW_UNTRANSLATED_POSTS = True # Nikola supports logo display. If you have one, you can put the URL here. # Final output is <img src="LOGO_URL" id="logo" alt="BLOG_TITLE">. # The URL may be relative to the site root. # LOGO_URL = '' # If you want to hide the title of your website (for example, if your logo # already contains the text), set this to False. # SHOW_BLOG_TITLE = True # Writes tag cloud data in form of tag_cloud_data.json. # Warning: this option will change its default value to False in v8! WRITE_TAG_CLOUD = True # Paths for different autogenerated bits. These are combined with the # translation paths. # Final locations are: # output / TRANSLATION[lang] / TAG_PATH / index.html (list of tags) # output / TRANSLATION[lang] / TAG_PATH / tag.html (list of posts for a tag) # output / TRANSLATION[lang] / TAG_PATH / tag.xml (RSS feed for a tag) # TAG_PATH = "categories" # If TAG_PAGES_ARE_INDEXES is set to True, each tag's page will contain # the posts themselves. If set to False, it will be just a list of links. # TAG_PAGES_ARE_INDEXES = False # Set descriptions for tag pages to make them more interesting. The # default is no description. The value is used in the meta description # and displayed underneath the tag list or index page’s title. # TAG_PAGES_DESCRIPTIONS = { # DEFAULT_LANG: { # "blogging": "Meta-blog posts about blogging about blogging.", # "open source": "My contributions to my many, varied, ever-changing, and eternal libre software projects." # }, #} # If you do not want to display a tag publicly, you can mark it as hidden. # The tag will not be displayed on the tag list page, the tag cloud and posts. # Tag pages will still be generated. HIDDEN_TAGS = ['mathjax'] # Only include tags on the tag list/overview page if there are at least # TAGLIST_MINIMUM_POSTS number of posts or more with every tag. Every tag # page is still generated, linked from posts, and included in the sitemap. # However, more obscure tags can be hidden from the tag index page. # TAGLIST_MINIMUM_POSTS = 1 # Final locations are: # output / TRANSLATION[lang] / CATEGORY_PATH / index.html (list of categories) # output / TRANSLATION[lang] / CATEGORY_PATH / CATEGORY_PREFIX category.html (list of posts for a category) # output / TRANSLATION[lang] / CATEGORY_PATH / CATEGORY_PREFIX category.xml (RSS feed for a category) # CATEGORY_PATH = "categories" # CATEGORY_PREFIX = "cat_" # If CATEGORY_ALLOW_HIERARCHIES is set to True, categories can be organized in # hierarchies. For a post, the whole path in the hierarchy must be specified, # using a forward slash ('/') to separate paths. Use a backslash ('\') to escape # a forward slash or a backslash (i.e. '\//\\' is a path specifying the # subcategory called '\' of the top-level category called '/'). # CATEGORY_ALLOW_HIERARCHIES = False # If CATEGORY_OUTPUT_FLAT_HIERARCHY is set to True, the output written to output # contains only the name of the leaf category and not the whole path. # CATEGORY_OUTPUT_FLAT_HIERARCHY = False # If CATEGORY_PAGES_ARE_INDEXES is set to True, each category's page will contain # the posts themselves. If set to False, it will be just a list of links. # CATEGORY_PAGES_ARE_INDEXES = False # Set descriptions for category pages to make them more interesting. The # default is no description. The value is used in the meta description # and displayed underneath the category list or index page’s title. # CATEGORY_PAGES_DESCRIPTIONS = { # DEFAULT_LANG: { # "blogging": "Meta-blog posts about blogging about blogging.", # "open source": "My contributions to my many, varied, ever-changing, and eternal libre software projects." # }, #} # If you do not want to display a category publicly, you can mark it as hidden. # The category will not be displayed on the category list page. # Category pages will still be generated. HIDDEN_CATEGORIES = [] # Final location for the main blog page and sibling paginated pages is # output / TRANSLATION[lang] / INDEX_PATH / index-*.html # INDEX_PATH = "" # Create per-month archives instead of per-year # CREATE_MONTHLY_ARCHIVE = False # Create one large archive instead of per-year # CREATE_SINGLE_ARCHIVE = False # Create year, month, and day archives each with a (long) list of posts # (overrides both CREATE_MONTHLY_ARCHIVE and CREATE_SINGLE_ARCHIVE) # CREATE_FULL_ARCHIVES = False # If monthly archives or full archives are created, adds also one archive per day # CREATE_DAILY_ARCHIVE = False # Final locations for the archives are: # output / TRANSLATION[lang] / ARCHIVE_PATH / ARCHIVE_FILENAME # output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / index.html # output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / MONTH / index.html # output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / MONTH / DAY / index.html # ARCHIVE_PATH = "" # ARCHIVE_FILENAME = "archive.html" # If ARCHIVES_ARE_INDEXES is set to True, each archive page which contains a list # of posts will contain the posts themselves. If set to False, it will be just a # list of links. # ARCHIVES_ARE_INDEXES = False # URLs to other posts/pages can take 3 forms: # rel_path: a relative URL to the current page/post (default) # full_path: a URL with the full path from the root # absolute: a complete URL (that includes the SITE_URL) # URL_TYPE = 'rel_path' # Final location for the blog main RSS feed is: # output / TRANSLATION[lang] / RSS_PATH / rss.xml # RSS_PATH = "" # Number of posts in RSS feeds # FEED_LENGTH = 10 # Slug the Tag URL easier for users to type, special characters are # often removed or replaced as well. # SLUG_TAG_PATH = True # A list of redirection tuples, [("foo/from.html", "/bar/to.html")]. # # A HTML file will be created in output/foo/from.html that redirects # to the "/bar/to.html" URL. notice that the "from" side MUST be a # relative URL. # # If you don't need any of these, just set to [] REDIRECTIONS = [] # Presets of commands to execute to deploy. Can be anything, for # example, you may use rsync: # "rsync -rav --delete output/ joe@my.site:/srv/www/site" # And then do a backup, or run `nikola ping` from the `ping` # plugin (`nikola plugin -i ping`). Or run `nikola check -l`. # You may also want to use github_deploy (see below). # You can define multiple presets and specify them as arguments # to `nikola deploy`. If no arguments are specified, a preset # named `default` will be executed. You can use as many presets # in a `nikola deploy` command as you like. # DEPLOY_COMMANDS = { # 'default': [ # "rsync -rav --delete output/ joe@my.site:/srv/www/site", # ] # } # For user.github.io OR organization.github.io pages, the DEPLOY branch # MUST be 'master', and 'gh-pages' for other repositories. # GITHUB_SOURCE_BRANCH = 'master' # GITHUB_DEPLOY_BRANCH = 'gh-pages' # The name of the remote where you wish to push to, using github_deploy. # GITHUB_REMOTE_NAME = 'origin' # Where the output site should be located # If you don't use an absolute path, it will be considered as relative # to the location of conf.py # OUTPUT_FOLDER = 'output' # where the "cache" of partial generated content should be located # default: 'cache' # CACHE_FOLDER = 'cache' # Filters to apply to the output. # A directory where the keys are either: a file extensions, or # a tuple of file extensions. # # And the value is a list of commands to be applied in order. # # Each command must be either: # # A string containing a '%s' which will # be replaced with a filename. The command *must* produce output # in place. # # Or: # # A python callable, which will be called with the filename as # argument. # # By default, only .php files uses filters to inject PHP into # Nikola’s templates. All other filters must be enabled through FILTERS. # # Many filters are shipped with Nikola. A list is available in the manual: # <https://getnikola.com/handbook.html#post-processing-filters> # # from nikola import filters # FILTERS = { # ".html": [filters.typogrify], # ".js": [filters.closure_compiler], # ".jpg": ["jpegoptim --strip-all -m75 -v %s"], # } # Expert setting! Create a gzipped copy of each generated file. Cheap server- # side optimization for very high traffic sites or low memory servers. # GZIP_FILES = False # File extensions that will be compressed # GZIP_EXTENSIONS = ('.txt', '.htm', '.html', '.css', '.js', '.json', '.atom', '.xml') # Use an external gzip command? None means no. # Example: GZIP_COMMAND = "pigz -k {filename}" # GZIP_COMMAND = None # Make sure the server does not return a "Accept-Ranges: bytes" header for # files compressed by this option! OR make sure that a ranged request does not # return partial content of another representation for these resources. Do not # use this feature if you do not understand what this means. # Compiler to process LESS files. # LESS_COMPILER = 'lessc' # A list of options to pass to the LESS compiler. # Final command is: LESS_COMPILER LESS_OPTIONS file.less # LESS_OPTIONS = [] # Compiler to process Sass files. # SASS_COMPILER = 'sass' # A list of options to pass to the Sass compiler. # Final command is: SASS_COMPILER SASS_OPTIONS file.s(a|c)ss # SASS_OPTIONS = [] # ############################################################################# # Image Gallery Options # ############################################################################# # One or more folders containing galleries. The format is a dictionary of # {"source": "relative_destination"}, where galleries are looked for in # "source/" and the results will be located in # "OUTPUT_PATH/relative_destination/gallery_name" # Default is: # GALLERY_FOLDERS = {"galleries": "galleries"} # More gallery options: # THUMBNAIL_SIZE = 180 # MAX_IMAGE_SIZE = 1280 # USE_FILENAME_AS_TITLE = True # EXTRA_IMAGE_EXTENSIONS = [] # # If set to False, it will sort by filename instead. Defaults to True # GALLERY_SORT_BY_DATE = True # # Folders containing images to be used in normal posts or pages. Images will be # scaled down according to IMAGE_THUMBNAIL_SIZE and MAX_IMAGE_SIZE options, but # will have to be referenced manually to be visible on the site # (the thumbnail has ``.thumbnail`` added before the file extension). # The format is a dictionary of {source: relative destination}. IMAGE_FOLDERS = {'images': 'posts/images', 'figures': 'posts/figures'} # IMAGE_THUMBNAIL_SIZE = 400 # ############################################################################# # HTML fragments and diverse things that are used by the templates # ############################################################################# # Data about post-per-page indexes. # INDEXES_PAGES defaults to ' old posts, page %d' or ' page %d' (translated), # depending on the value of INDEXES_PAGES_MAIN. # # (translatable) If the following is empty, defaults to BLOG_TITLE: # INDEXES_TITLE = "" # # (translatable) If the following is empty, defaults to ' [old posts,] page %d' (see above): # INDEXES_PAGES = "" # # If the following is True, INDEXES_PAGES is also displayed on the main (the # newest) index page (index.html): # INDEXES_PAGES_MAIN = False # # If the following is True, index-1.html has the oldest posts, index-2.html the # second-oldest posts, etc., and index.html has the newest posts. This ensures # that all posts on index-x.html will forever stay on that page, now matter how # many new posts are added. # If False, index-1.html has the second-newest posts, index-2.html the third-newest, # and index-n.html the oldest posts. When this is active, old posts can be moved # to other index pages when new posts are added. # INDEXES_STATIC = True # # (translatable) If PRETTY_URLS is set to True, this setting will be used to create # prettier URLs for index pages, such as page/2/index.html instead of index-2.html. # Valid values for this settings are: # * False, # * a list or tuple, specifying the path to be generated, # * a dictionary mapping languages to lists or tuples. # Every list or tuple must consist of strings which are used to combine the path; # for example: # ['page', '{number}', '{index_file}'] # The replacements # {number} --> (logical) page number; # {old_number} --> the page number inserted into index-n.html before (zero for # the main page); # {index_file} --> value of option INDEX_FILE # are made. # Note that in case INDEXES_PAGES_MAIN is set to True, a redirection will be created # for the full URL with the page number of the main page to the normal (shorter) main # page URL. # INDEXES_PRETTY_PAGE_URL = False # Color scheme to be used for code blocks. If your theme provides # "assets/css/code.css" this is ignored. # Can be any of: # algol # algol_nu # arduino # autumn # borland # bw # colorful # default # emacs # friendly # fruity # igor # lovelace # manni # monokai # murphy # native # paraiso_dark # paraiso_light # pastie # perldoc # rrt # tango # trac # vim # vs # xcode # This list MAY be incomplete since pygments adds styles every now and then. # CODE_COLOR_SCHEME = 'default' # If you use 'site-reveal' theme you can select several subthemes # THEME_REVEAL_CONFIG_SUBTHEME = 'sky' # You can also use: beige/serif/simple/night/default # Again, if you use 'site-reveal' theme you can select several transitions # between the slides # THEME_REVEAL_CONFIG_TRANSITION = 'cube' # You can also use: page/concave/linear/none/default # FAVICONS contains (name, file, size) tuples. # Used to create favicon link like this: # <link rel="name" href="file" sizes="size"/> # FAVICONS = ( # ("icon", "/favicon.ico", "16x16"), # ("icon", "/icon_128x128.png", "128x128"), # ) # Show only teasers in the index pages? Defaults to False. INDEX_TEASERS = True # HTML fragments with the Read more... links. # The following tags exist and are replaced for you: # {link} A link to the full post page. # {read_more} The string “Read more” in the current language. # {reading_time} An estimate of how long it will take to read the post. # {remaining_reading_time} An estimate of how long it will take to read the post, sans the teaser. # {min_remaining_read} The string “{remaining_reading_time} min remaining to read” in the current language. # {paragraph_count} The amount of paragraphs in the post. # {remaining_paragraph_count} The amount of paragraphs in the post, sans the teaser. # {{ A literal { (U+007B LEFT CURLY BRACKET) # }} A literal } (U+007D RIGHT CURLY BRACKET) # 'Read more...' for the index page, if INDEX_TEASERS is True (translatable) INDEX_READ_MORE_LINK = '<p class="more"><a href="{link}">{read_more}…</a></p>' # 'Read more...' for the RSS_FEED, if RSS_TEASERS is True (translatable) FEED_READ_MORE_LINK = '<p><a href="{link}">{read_more}…</a> ({min_remaining_read})</p>' # Append a URL query to the RSS_READ_MORE_LINK in Atom and RSS feeds. Advanced # option used for traffic source tracking. # Minimum example for use with Piwik: "pk_campaign=feed" # The following tags exist and are replaced for you: # {feedRelUri} A relative link to the feed. # {feedFormat} The name of the syndication format. # Example using replacement for use with Google Analytics: # "utm_source={feedRelUri}&utm_medium=nikola_feed&utm_campaign={feedFormat}_feed" FEED_LINKS_APPEND_QUERY = False # A HTML fragment describing the license, for the sidebar. # (translatable) # LICENSE = "" # I recommend using the Creative Commons' wizard: # http://creativecommons.org/choose/ LICENSE = """ <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/2.5/ar/"> <img alt="Creative Commons License BY-NC-SA" style="border-width:0; margin-bottom:12px;" src="http://i.creativecommons.org/l/by-nc-sa/2.5/ar/88x31.png"></a>""" # A small copyright notice for the page footer (in HTML). # (translatable) CONTENT_FOOTER = 'Contents &copy; {date} <a href="mailto:{email}">{author}</a> - Powered by <a href="https://getnikola.com" rel="nofollow">Nikola</a> {license}' # Things that will be passed to CONTENT_FOOTER.format(). This is done # for translatability, as dicts are not formattable. Nikola will # intelligently format the setting properly. # The setting takes a dict. The keys are languages. The values are # tuples of tuples of positional arguments and dicts of keyword arguments # to format(). For example, {'en': (('Hello'), {'target': 'World'})} # results in CONTENT_FOOTER['en'].format('Hello', target='World'). # WARNING: If you do not use multiple languages with CONTENT_FOOTER, this # still needs to be a dict of this format. (it can be empty if you # do not need formatting) # (translatable) CONTENT_FOOTER_FORMATS = { DEFAULT_LANG: ( (), { "email": BLOG_EMAIL, "author": BLOG_AUTHOR, "date": time.gmtime().tm_year, "license": LICENSE } ) } # To use comments, you can choose between different third party comment # systems. The following comment systems are supported by Nikola: # disqus, facebook, googleplus, intensedebate, isso, livefyre, muut # You can leave this option blank to disable comments. COMMENT_SYSTEM = "" # And you also need to add your COMMENT_SYSTEM_ID which # depends on what comment system you use. The default is # "nikolademo" which is a test account for Disqus. More information # is in the manual. COMMENT_SYSTEM_ID = "" # Enable annotations using annotateit.org? # If set to False, you can still enable them for individual posts and pages # setting the "annotations" metadata. # If set to True, you can disable them for individual posts and pages using # the "noannotations" metadata. # ANNOTATIONS = False # Create index.html for page (story) folders? # WARNING: if a page would conflict with the index file (usually # caused by setting slug to `index`), the STORY_INDEX # will not be generated for that directory. # STORY_INDEX = False # Enable comments on story pages? # COMMENTS_IN_STORIES = False # Enable comments on picture gallery pages? # COMMENTS_IN_GALLERIES = False # What file should be used for directory indexes? # Defaults to index.html # Common other alternatives: default.html for IIS, index.php # INDEX_FILE = "index.html" # If a link ends in /index.html, drop the index.html part. # http://mysite/foo/bar/index.html => http://mysite/foo/bar/ # (Uses the INDEX_FILE setting, so if that is, say, default.html, # it will instead /foo/default.html => /foo) # (Note: This was briefly STRIP_INDEX_HTML in v 5.4.3 and 5.4.4) # Default = False # STRIP_INDEXES = False # Should the sitemap list directories which only include other directories # and no files. # Default to True # If this is False # e.g. /2012 includes only /01, /02, /03, /04, ...: don't add it to the sitemap # if /2012 includes any files (including index.html)... add it to the sitemap # SITEMAP_INCLUDE_FILELESS_DIRS = True # List of files relative to the server root (!) that will be asked to be excluded # from indexing and other robotic spidering. * is supported. Will only be effective # if SITE_URL points to server root. The list is used to exclude resources from # /robots.txt and /sitemap.xml, and to inform search engines about /sitemapindex.xml. # ROBOTS_EXCLUSIONS = ["/archive.html", "/category/*.html"] # Instead of putting files in <slug>.html, put them in <slug>/index.html. # No web server configuration is required. Also enables STRIP_INDEXES. # This can be disabled on a per-page/post basis by adding # .. pretty_url: False # to the metadata. PRETTY_URLS = True # If True, publish future dated posts right away instead of scheduling them. # Defaults to False. # FUTURE_IS_NOW = False # If True, future dated posts are allowed in deployed output # Only the individual posts are published/deployed; not in indexes/sitemap # Generally, you want FUTURE_IS_NOW and DEPLOY_FUTURE to be the same value. # DEPLOY_FUTURE = False # If False, draft posts will not be deployed # DEPLOY_DRAFTS = True # Allows scheduling of posts using the rule specified here (new_post -s) # Specify an iCal Recurrence Rule: http://www.kanzaki.com/docs/ical/rrule.html # SCHEDULE_RULE = '' # If True, use the scheduling rule to all posts by default # SCHEDULE_ALL = False # Do you want a add a Mathjax config file? # MATHJAX_CONFIG = "" # If you are using the compile-ipynb plugin, just add this one: MATHJAX_CONFIG = """ <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: { inlineMath: [ ['$','$'], ["\\\(","\\\)"] ], displayMath: [ ['$$','$$'], ["\\\[","\\\]"] ], processEscapes: true }, displayAlign: 'left', // Change this to 'center' to center equations. "HTML-CSS": { styles: {'.MathJax_Display': {"margin": 0}} } }); </script> """ # EXTRA_HEAD_DATA = """<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.css">""" # USE_KATEX = True # Do you want to customize the nbconversion of your IPython notebook? # IPYNB_CONFIG = {} # With the following example configuration you can use a custom jinja template # called `toggle.tpl` which has to be located in your site/blog main folder: # IPYNB_CONFIG = {'Exporter':{'template_file': 'toggle'}} # What Markdown extensions to enable? # You will also get gist, nikola and podcast because those are # done in the code, hope you don't mind ;-) # Note: most Nikola-specific extensions are done via the Nikola plugin system, # with the MarkdownExtension class and should not be added here. # The default is ['fenced_code', 'codehilite'] MARKDOWN_EXTENSIONS = ['fenced_code', 'codehilite', 'extra'] # Extra options to pass to the pandoc comand. # by default, it's empty, is a list of strings, for example # ['-F', 'pandoc-citeproc', '--bibliography=/Users/foo/references.bib'] # PANDOC_OPTIONS = [] # Social buttons. This is sample code for AddThis (which was the default for a # long time). Insert anything you want here, or even make it empty (which is # the default right now) # (translatable) # SOCIAL_BUTTONS_CODE = """ # <!-- Social buttons --> # <div id="addthisbox" class="addthis_toolbox addthis_peekaboo_style addthis_default_style addthis_label_style addthis_32x32_style"> # <a class="addthis_button_more">Share</a> # <ul><li><a class="addthis_button_facebook"></a> # <li><a class="addthis_button_google_plusone_share"></a> # <li><a class="addthis_button_linkedin"></a> # <li><a class="addthis_button_twitter"></a> # </ul> # </div> # <script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-4f7088a56bb93798"></script> # <!-- End of social buttons --> # """ # Show link to source for the posts? # Formerly known as HIDE_SOURCELINK (inverse) # SHOW_SOURCELINK = True # Copy the source files for your pages? # Setting it to False implies SHOW_SOURCELINK = False # COPY_SOURCES = True # Modify the number of Post per Index Page # Defaults to 10 # INDEX_DISPLAY_POST_COUNT = 10 # By default, Nikola generates RSS files for the website and for tags, and # links to it. Set this to False to disable everything RSS-related. # GENERATE_RSS = True # By default, Nikola does not generates Atom files for indexes and links to # them. Generate Atom for tags by setting TAG_PAGES_ARE_INDEXES to True. # Atom feeds are built based on INDEX_DISPLAY_POST_COUNT and not FEED_LENGTH # Switch between plain-text summaries and full HTML content using the # RSS_TEASER option. RSS_LINKS_APPEND_QUERY is also respected. Atom feeds # are generated even for old indexes and have pagination link relations # between each other. Old Atom feeds with no changes are marked as archived. # GENERATE_ATOM = False # RSS_LINK is a HTML fragment to link the RSS or Atom feeds. If set to None, # the base.tmpl will use the feed Nikola generates. However, you may want to # change it for a FeedBurner feed or something else. # RSS_LINK = None # Show only teasers in the RSS and Atom feeds? Default to True # RSS_TEASERS = True # Strip HTML in the RSS feed? Default to False # RSS_PLAIN = False # A search form to search this site, for the sidebar. You can use a Google # custom search (http://www.google.com/cse/) # Or a DuckDuckGo search: https://duckduckgo.com/search_box.html # Default is no search form. # (translatable) # SEARCH_FORM = "" # # This search form works for any site and looks good in the "site" theme where # it appears on the navigation bar: # # SEARCH_FORM = """ # <!-- Custom search --> # <form method="get" id="search" action="//duckduckgo.com/" # class="navbar-form pull-left"> # <input type="hidden" name="sites" value="%s"/> # <input type="hidden" name="k8" value="#444444"/> # <input type="hidden" name="k9" value="#D51920"/> # <input type="hidden" name="kt" value="h"/> # <input type="text" name="q" maxlength="255" # placeholder="Search&hellip;" class="span2" style="margin-top: 4px;"/> # <input type="submit" value="DuckDuckGo Search" style="visibility: hidden;" /> # </form> # <!-- End of custom search --> # """ % SITE_URL # # If you prefer a Google search form, here's an example that should just work: # SEARCH_FORM = """ # <!-- Custom search with Google--> # <form id="search" action="//www.google.com/search" method="get" class="navbar-form pull-left"> # <input type="hidden" name="q" value="site:%s" /> # <input type="text" name="q" maxlength="255" results="0" placeholder="Search"/> # </form> # <!-- End of custom search --> #""" % SITE_URL # Use content distribution networks for jQuery, twitter-bootstrap css and js, # and html5shiv (for older versions of Internet Explorer) # If this is True, jQuery and html5shiv are served from the Google CDN and # Bootstrap is served from BootstrapCDN (provided by MaxCDN) # Set this to False if you want to host your site without requiring access to # external resources. # USE_CDN = False # Check for USE_CDN compatibility. # If you are using custom themes, have configured the CSS properly and are # receiving warnings about incompatibility but believe they are incorrect, you # can set this to False. # USE_CDN_WARNING = True # Extra things you want in the pages HEAD tag. This will be added right # before </head> # (translatable) # EXTRA_HEAD_DATA = "" # Google Analytics or whatever else you use. Added to the bottom of <body> # in the default template (base.tmpl). # (translatable) # BODY_END = "" # The possibility to extract metadata from the filename by using a # regular expression. # To make it work you need to name parts of your regular expression. # The following names will be used to extract metadata: # - title # - slug # - date # - tags # - link # - description # # An example re is the following: # '(?P<date>\d{4}-\d{2}-\d{2})-(?P<slug>.*)-(?P<title>.*)\.md' # FILE_METADATA_REGEXP = None # If you hate "Filenames with Capital Letters and Spaces.md", you should # set this to true. UNSLUGIFY_TITLES = True # Additional metadata that is added to a post when creating a new_post # ADDITIONAL_METADATA = {} # Nikola supports Open Graph Protocol data for enhancing link sharing and # discoverability of your site on Facebook, Google+, and other services. # Open Graph is enabled by default. # USE_OPEN_GRAPH = True # Nikola supports Twitter Card summaries, but they are disabled by default. # They make it possible for you to attach media to Tweets that link # to your content. # # IMPORTANT: # Please note, that you need to opt-in for using Twitter Cards! # To do this please visit https://cards-dev.twitter.com/validator # # Uncomment and modify to following lines to match your accounts. # Images displayed come from the `previewimage` meta tag. # You can specify the card type by using the `card` parameter in TWITTER_CARD. # TWITTER_CARD = { # # 'use_twitter_cards': True, # enable Twitter Cards # # 'card': 'summary', # Card type, you can also use 'summary_large_image', # # see https://dev.twitter.com/cards/types # # 'site': '@website', # twitter nick for the website # # 'creator': '@username', # Username for the content creator / author. # } # If webassets is installed, bundle JS and CSS into single files to make # site loading faster in a HTTP/1.1 environment but is not recommended for # HTTP/2.0 when caching is used. Defaults to True. USE_BUNDLES = True # Plugins you don't want to use. Be careful :-) # DISABLED_PLUGINS = ["render_galleries"] # Add the absolute paths to directories containing plugins to use them. # For example, the `plugins` directory of your clone of the Nikola plugins # repository. # EXTRA_PLUGINS_DIRS = [] # List of regular expressions, links matching them will always be considered # valid by "nikola check -l" # LINK_CHECK_WHITELIST = [] # If set to True, enable optional hyphenation in your posts (requires pyphen) # HYPHENATE = False # The <hN> tags in HTML generated by certain compilers (reST/Markdown) # will be demoted by that much (1 → h1 will become h2 and so on) # This was a hidden feature of the Markdown and reST compilers in the # past. Useful especially if your post titles are in <h1> tags too, for # example. # (defaults to 1.) # DEMOTE_HEADERS = 1 # If you don’t like slugified file names ([a-z0-9] and a literal dash), # and would prefer to use all the characters your file system allows. # USE WITH CARE! This is also not guaranteed to be perfect, and may # sometimes crash Nikola, your web server, or eat your cat. # USE_SLUGIFY = True # You can configure the logging handlers installed as plugins or change the # log level of the default stderr handler. # WARNING: The stderr handler allows only the loglevels of 'INFO' and 'DEBUG'. # This is done for safety reasons, as blocking out anything other # than 'DEBUG' may hide important information and break the user # experience! LOGGING_HANDLERS = { 'stderr': {'loglevel': 'INFO', 'bubble': True}, # 'smtp': { # 'from_addr': 'test-errors@example.com', # 'recipients': ('test@example.com'), # 'credentials':('testusername', 'password'), # 'server_addr': ('127.0.0.1', 25), # 'secure': (), # 'level': 'DEBUG', # 'bubble': True # } } # Templates will use those filters, along with the defaults. # Consult your engine's documentation on filters if you need help defining # those. # TEMPLATE_FILTERS = {} # Put in global_context things you want available on all your templates. # It can be anything, data, functions, modules, etc. GLOBAL_CONTEXT = {} # Add functions here and they will be called with template # GLOBAL_CONTEXT as parameter when the template is about to be # rendered GLOBAL_CONTEXT_FILLER = []
kastnerkyle/kastnerkyle.github.io-nikola
blogsite/conf.py
Python
bsd-3-clause
41,286
[ "VisIt" ]
7000aab75a32ce9a7413926faa133554e4e75e03ee3144f8e522c6f4bf5132a1
""" ======================================================================== Concentration Prior Type Analysis of Variation Bayesian Gaussian Mixture ======================================================================== This example plots the ellipsoids obtained from a toy dataset (mixture of three Gaussians) fitted by the ``BayesianGaussianMixture`` class models with a Dirichlet distribution prior (``weight_concentration_prior_type='dirichlet_distribution'``) and a Dirichlet process prior (``weight_concentration_prior_type='dirichlet_process'``). On each figure, we plot the results for three different values of the weight concentration prior. The ``BayesianGaussianMixture`` class can adapt its number of mixture componentsautomatically. The parameter ``weight_concentration_prior`` has a direct link with the resulting number of components with non-zero weights. Specifying a low value for the concentration prior will make the model put most of the weight on few components set the remaining components weights very close to zero. High values of the concentration prior will allow a larger number of components to be active in the mixture. The Dirichlet process prior allows to define an infinite number of components and automatically selects the correct number of components: it activates a component only if it is necessary. On the contrary the classical finite mixture model with a Dirichlet distribution prior will favor more uniformly weighted components and therefore tends to divide natural clusters into unnecessary sub-components. """ # Author: Thierry Guillemot <thierry.guillemot.work@gmail.com> # License: BSD 3 clause import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from sklearn.mixture import BayesianGaussianMixture print(__doc__) def plot_ellipses(ax, weights, means, covars): for n in range(means.shape[0]): eig_vals, eig_vecs = np.linalg.eigh(covars[n]) unit_eig_vec = eig_vecs[0] / np.linalg.norm(eig_vecs[0]) angle = np.arctan2(unit_eig_vec[1], unit_eig_vec[0]) # Ellipse needs degrees angle = 180 * angle / np.pi # eigenvector normalization eig_vals = 2 * np.sqrt(2) * np.sqrt(eig_vals) ell = mpl.patches.Ellipse(means[n], eig_vals[0], eig_vals[1], 180 + angle) ell.set_clip_box(ax.bbox) ell.set_alpha(weights[n]) ell.set_facecolor('#56B4E9') ax.add_artist(ell) def plot_results(ax1, ax2, estimator, X, y, title, plot_title=False): ax1.set_title(title) ax1.scatter(X[:, 0], X[:, 1], s=5, marker='o', color=colors[y], alpha=0.8) ax1.set_xlim(-2., 2.) ax1.set_ylim(-3., 3.) ax1.set_xticks(()) ax1.set_yticks(()) plot_ellipses(ax1, estimator.weights_, estimator.means_, estimator.covariances_) ax2.get_xaxis().set_tick_params(direction='out') ax2.yaxis.grid(True, alpha=0.7) for k, w in enumerate(estimator.weights_): ax2.bar(k - .45, w, width=0.9, color='#56B4E9', zorder=3) ax2.text(k, w + 0.007, "%.1f%%" % (w * 100.), horizontalalignment='center') ax2.set_xlim(-.6, 2 * n_components - .4) ax2.set_ylim(0., 1.1) ax2.tick_params(axis='y', which='both', left='off', right='off', labelleft='off') ax2.tick_params(axis='x', which='both', top='off') if plot_title: ax1.set_ylabel('Estimated Mixtures') ax2.set_ylabel('Weight of each component') # Parameters of the dataset random_state, n_components, n_features = 2, 3, 2 colors = np.array(['#0072B2', '#F0E442', '#D55E00']) covars = np.array([[[.7, .0], [.0, .1]], [[.5, .0], [.0, .1]], [[.5, .0], [.0, .1]]]) samples = np.array([200, 500, 200]) means = np.array([[.0, -.70], [.0, .0], [.0, .70]]) # mean_precision_prior= 0.8 to minimize the influence of the prior estimators = [ ("Finite mixture with a Dirichlet distribution\nprior and " r"$\gamma_0=$", BayesianGaussianMixture( weight_concentration_prior_type="dirichlet_distribution", n_components=2 * n_components, reg_covar=0, init_params='random', max_iter=1500, mean_precision_prior=.8, random_state=random_state), [0.001, 1, 1000]), ("Infinite mixture with a Dirichlet process\n prior and" r"$\gamma_0=$", BayesianGaussianMixture( weight_concentration_prior_type="dirichlet_process", n_components=2 * n_components, reg_covar=0, init_params='random', max_iter=1500, mean_precision_prior=.8, random_state=random_state), [1, 1000, 100000])] # Generate data rng = np.random.RandomState(random_state) X = np.vstack([ rng.multivariate_normal(means[j], covars[j], samples[j]) for j in range(n_components)]) y = np.concatenate([j * np.ones(samples[j], dtype=int) for j in range(n_components)]) # Plot results in two different figures for (title, estimator, concentrations_prior) in estimators: plt.figure(figsize=(4.7 * 3, 8)) plt.subplots_adjust(bottom=.04, top=0.90, hspace=.05, wspace=.05, left=.03, right=.99) gs = gridspec.GridSpec(3, len(concentrations_prior)) for k, concentration in enumerate(concentrations_prior): estimator.weight_concentration_prior = concentration estimator.fit(X) plot_results(plt.subplot(gs[0:2, k]), plt.subplot(gs[2, k]), estimator, X, y, r"%s$%.1e$" % (title, concentration), plot_title=k == 0) plt.show()
RPGOne/Skynet
scikit-learn-0.18.1/examples/mixture/plot_concentration_prior.py
Python
bsd-3-clause
5,631
[ "Gaussian" ]
3aab4dc566025395dc01a4c34f9d0e2e1ffa087ff7870b58972f6f5e75cbac4e
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # 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. from __future__ import print_function, division import os,unittest,numpy as np from pyscf.nao import tddft_iter from pyscf import gto, scf, tddft from pyscf.data.nist import HARTREE2EV class KnowValues(unittest.TestCase): def test_134_h2o_rhf_rpa_pb(self): """ This """ mol = gto.M(verbose=1,atom='O 0 0 0; H 0 0.489 1.074; H 0 0.489 -1.074',basis='cc-pvdz') gto_mf = scf.RHF(mol) gto_mf.kernel() nao_mf = tddft_iter(gto=mol, mf=gto_mf, tol_loc=1e-5, tol_biloc=1e-7, xc_code="RPA") comega = np.arange(0.0, 2.0, 0.01) + 1j*0.03 pnonin = -nao_mf.comp_polariz_inter_ave(comega, verbosity=0).imag data = np.array([comega.real*HARTREE2EV, pnonin]) np.savetxt('test_134_h2o_rhf_rpa_pb.txt', data.T, fmt=['%f','%f']) data_ref = np.loadtxt('test_134_h2o_rhf_rpa_pb.txt-ref').T self.assertTrue(np.allclose(data_ref, data, atol=1e-6, rtol=1e-3)) if __name__ == "__main__": unittest.main()
gkc1000/pyscf
pyscf/nao/test/test_0134_h2o_rhf_rpa_pb.py
Python
apache-2.0
1,545
[ "PySCF" ]
1be8a5fbc159d887462037fca60d2eb22cd32657339c1d397350454e4f69123d
def printHSP(hsp, indent=''): for attr in ['bits', 'expect', 'frame', 'query_end', 'query_start', 'sbjct', 'query', 'sbjct_end', 'sbjct_start']: print('%s%s: %s' % (indent, attr, hsp[attr])) def normalizeHSP(hsp, readLen, blastApplication): """ Examine an HSP and return information about where the query and subject match begins and ends. Return a dict with keys that allow the query to be displayed against the subject. The returned readStartInSubject and readEndInSubject indices are offsets into the subject. I.e., they indicate where in the subject the query falls. In the returned object, all indices are suitable for Python string slicing etc. We must be careful to convert from the 1-based offsets found in BLAST output properly. hsp['frame'] is a (query, subject) 2-tuple, with both values coming from {-3, -2, -1, 1, 2, 3}. The sign indicates negative or positive sense (i.e., the direction of reading through the query or subject to get the alignment). The value is the nucleotide match offset modulo 3, plus one (i.e., it tells us which of the 3 possible reading frames is used in the match). The value is redundant because that information could also be obtained from the mod 3 value of the match offset. NOTE: the returned readStartInSubject value may be negative. We consider the hit sequence to start at offset 0. So if the read string has sufficient additional nucleotides before the start of the alignment match, it may protrude to the left of the hit. Similarly, the returned readEndInSubject can be greater than the subjectEnd. @param hsp: an HSP in the form of a C{dict}, built from a BLAST record. All passed hsp offsets are 1-based. @param readLen: the length of the read sequence. @param blastApplication: The C{str} command line program that was run (e.g., 'blastn', 'blastx'). """ def debugPrint(locals, msg=None): """ Print debugging information showing the local variables from a call to normalizeHSP and then raise an C{AssertionError}. @param locals: A C{dict} of local variables. @param msg: A C{str} message to raise C{AssertionError} with. """ print('normalizeHSP error:') print(' readLen: %d' % readLen) for var in sorted(locals): if var in ('debugPrint', 'hsp'): continue print(' %s: %s' % (var, locals[var])) print(' Original HSP:') printHSP(hsp, ' ') if msg: raise AssertionError(msg) else: raise AssertionError() readPositive = hsp['frame'][0] > 0 hitPositive = hsp['frame'][1] > 0 # The following variable names with underscores match the names of # attributes BioPython uses and the values (1-based) match those # reported by BLAST. read_start = hsp['query_start'] read_end = hsp['query_end'] sbjct_start = hsp['sbjct_start'] sbjct_end = hsp['sbjct_end'] # When the read is positive, BLASTN and TBLASTX give read offsets # ascending. # # TBLASTX reports negative read sense with indices ascending. # BLASTN does not report negative read sense. # # In all cases the read offsets should be ascending. if read_start > read_end: debugPrint(locals(), 'Assertion "read_start <= read_end" failed. Read ' 'positive is %s. read_start = %d, read_end = %d' % (readPositive, read_start, read_end)) if hitPositive: # Make sure indices are ascending. if sbjct_start > sbjct_end: debugPrint(locals()) else: # Hit is negative. Its indices will be ascending for TBLASTX # output but descending for BLASTN :-( Make sure we have them # ascending. if sbjct_start > sbjct_end: sbjct_start, sbjct_end = sbjct_end, sbjct_start # Now that we have asserted what we can about the original HSP values # and gotten them into ascending order, make some sane 0-based offsets. readStartInSubject = read_start - 1 readEndInSubject = read_end subjectStart = sbjct_start - 1 subjectEnd = sbjct_end if blastApplication == 'blastx': # In Blastx output, hit offsets are based on protein sequence # length but queries (and the reported offsets) are nucleotide. # Convert the read offsets to protein because we will plot against # the hit (protein). # # Note that readStartInSubject and readEndInSubject may not be 0 mod # 3. They are offsets into the read string giving the position of # the AA, which depends on the translation frame. readStartInSubject = int(readStartInSubject / 3) readEndInSubject = int(readEndInSubject / 3) # No operations on original 1-based HSP variables (with underscores) # should appear beyond this point. subjectLength = subjectEnd - subjectStart readLength = readEndInSubject - readStartInSubject # NOTE: readLength (above) is a really bad name. It's actually going to # hold the length of the match in the query. I don't know why # readEndInSubject - readStartInSubject is used (I mean why those two # variables are not named readEnd and readStart). Maybe someone made a # find and replace editing error which changed their names. Anyway, the # readLength variable is confusingly named because this function is # passed a 'readLen' argument, which does happen to be the full length # of the read. This should be cleaned up. See ../diamond/hsp.py for # something cleaner. hitGaps = hsp['sbjct'].count('-') readGaps = hsp['query'].count('-') # Sanity check that the length of the matches in the hit and read # are identical, taking into account gaps in either (indicated by '-' # characters in the match sequences, as returned by BLAST). subjectLengthWithGaps = subjectLength + hitGaps readLengthWithGaps = readLength + readGaps if subjectLengthWithGaps != readLengthWithGaps: debugPrint(locals(), 'Including gaps, hit match length (%d) != Read match ' 'length (%d)' % (subjectLengthWithGaps, readLengthWithGaps)) # TODO: check the mod 3 value of the start offsets. # Calculate read indices. These are indices relative to the hit! # unmatchedReadLeft is the number of read bases that will be sticking # out to the left of the start of the hit in our plots. if readPositive: unmatchedReadLeft = readStartInSubject else: unmatchedReadLeft = readLen - readEndInSubject # Set the read offsets based on the direction the match with the # hit takes. if hitPositive: readStartInSubject = subjectStart - unmatchedReadLeft readEndInSubject = readStartInSubject + readLen + readGaps else: readEndInSubject = subjectEnd + unmatchedReadLeft readStartInSubject = readEndInSubject - readLen - readGaps # Final sanity checks. if readStartInSubject > subjectStart: debugPrint(locals(), 'readStartInSubject > subjectStart') if readEndInSubject < subjectEnd: debugPrint(locals(), 'readEndInSubject < subjectEnd') return { 'readStart': read_start - 1, 'readEnd': read_end, 'readStartInSubject': readStartInSubject, 'readEndInSubject': readEndInSubject, 'subjectStart': subjectStart, 'subjectEnd': subjectEnd, }
terrycojones/dark-matter
dark/blast/hsp.py
Python
mit
7,637
[ "BLAST", "Biopython" ]
c65f5cb76180d577f38a375e20e1ff4859939f5e661e830edfb0919805cbf9a7
# -*- coding: utf-8 -*- ############################################################################### # # This source file is part of the tomviz project. # # Copyright Kitware, Inc. # # This source code is released under the New BSD License, (the "License"). # # 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. # ############################################################################### from abc import ABCMeta, abstractmethod class FileType(object): """ Container class for file type information. """ def __init__(self, display_name=None, extensions=None): self.display_name = display_name self.extensions = extensions def __str__(self): return "%s (%s)" % (self.display_name, " ".join(["*."+ext for ext in self.extensions])) class IOBase(object, metaclass=ABCMeta): @staticmethod @abstractmethod def file_type(): """ :returns An instance of the FileFormat class. This is used to associate a file type with a reader. :rtype tomviz.io.FileType """ class Reader(IOBase, metaclass=ABCMeta): """ The base reader class from which readers should be derived. """ """ Set to True if reader supports loading image stacks. """ supports_stacks = False @abstractmethod def read(self, file): """ :returns Return a vtkDataObject containing the scalars read. :param file: the path or file object to read from :rtype vtk.vtkDataObject """ class Writer(IOBase, metaclass=ABCMeta): """ The base reader class from which writers should be derived. """ @abstractmethod def write(self, file, data): """ :param file: the path or file object to write to :param data: The data to write to the file. :type data: The vtkDataObject instance. """
mathturtle/tomviz
tomviz/python/tomviz/io/__init__.py
Python
bsd-3-clause
2,175
[ "VTK" ]
de2f571ea4a0d8208607299cb1385d60d3e836862d85be003e60f27417b94643
import types from datetime import datetime import numpy as np import chianti import chianti.data as chdata import chianti.constants as const import chianti.filters as chfilters import chianti.util as util # defaults = chdata.Defaults class spectrum: '''Calculate the emission spectrum as a function of temperature and density. includes elemental abundances and ionization equilibria temperature and density can be arrays but, unless the size of either is one (1), the two must have the same size the returned spectrum will be convolved with a filter of the specified width on the specified wavelength array the default filter is gaussianR with a resolving power of 1000. Other filters, such as gaussian, box and lorentz, are available in chianti.filters. When using the box filter, the width should equal the wavelength interval to keep the units of the continuum and line spectrum the same. A selection of elements can be make with elementList a list containing the names of elements that are desired to be included, e.g., ['fe','ni'] A selection of ions can be make with ionList containing the names of the desired lines in Chianti notation, i.e. C VI = c_6 Both elementList and ionList can not be specified at the same time a minimum abundance can be specified so that the calculation can be speeded up by excluding elements with a low abundance. With solar photospheric abundances - setting minAbund = 1.e-4 will include H, He, C, O, Ne setting minAbund = 2.e-5 adds N, Mg, Si, S, Fe setting minAbund = 1.e-6 adds Na, Al, Ar, Ca, Ni Setting doContinuum =0 will skip the continuum calculation. Setting em will multiply the spectrum at each temperature by the value of em. em [for emission measure], can be a float or an array of the same length as the temperature/density ''' def __init__(self, temperature, density, wavelength, filter=(chfilters.gaussianR, 1000.), elementList = 0, ionList = 0, minAbund=0, doContinuum=1, em = None, verbose=0, allLines=1): t1 = datetime.now() masterlist = chdata.MasterList # use the ionList but make sure the ions are in the database if elementList: for i, one in enumerate(elementList): elementList[i] = one.lower() alist = [] for one in masterlist: stuff = util.convertName(one) if stuff['Element'] in elementList: alist.append(one) masterlist = alist elif ionList: alist=[] for one in ionList: if masterlist.count(one): alist.append(one) else: if verbose: pstring = ' %s not in CHIANTI database'%(one) print('') masterlist = alist self.Defaults=defaults self.Temperature = np.asarray(temperature, 'float64') nTemp = self.Temperature.size self.Density = np.asarray(density, 'float64') nDen = self.Density.size nTempDen = max([nTemp, nDen]) if type(em) != types.NoneType: if type(em) == types.FloatType: if nTempDen > 1: em = np.ones_like(self.Temperature)*em nEm = nTempDen else: nEm = 1 else: em = np.asarray(em, 'float64') nEm = em.size if nEm != nTempDen: print ' the emission measure array must be the same size as the temperature/density array' return self.AbundanceName = defaults['abundfile'] self.AbundanceAll = chdata.AbundanceAll abundAll = self.AbundanceAll['abundance'] nonzed = abundAll > 0. minAbundAll = abundAll[nonzed].min() if minAbund < minAbundAll: minAbund = minAbundAll self.minAbund = minAbund ionInfo = util.masterListInfo() wavelength = np.asarray(wavelength) nWvl = wavelength.size self.Wavelength = wavelength wvlRange = [wavelength.min(), wavelength.max()] # freeFree = np.zeros((nTempDen, nWvl), 'float64').squeeze() freeBound = np.zeros((nTempDen, nWvl), 'float64').squeeze() twoPhoton = np.zeros((nTempDen, nWvl), 'float64').squeeze() lineSpectrum = np.zeros((nTempDen, nWvl), 'float64').squeeze() # ionsCalculated = [] # for iz in range(31): abundance = self.AbundanceAll['abundance'][iz-1] if abundance >= minAbund: print ' %5i %5s abundance = %10.2e '%(iz, const.El[iz-1], abundance) # for ionstage in range(1, iz+2): ionS = util.zion2name(iz, ionstage) # print ' ionS = ', ionS masterListTest = ionS in masterlist masterListInfoTest = ionS in ionInfo.keys() if masterListTest or masterListInfoTest: wvlTestMin = self.Wavelength.min() <= ionInfo[ionS]['wmax'] wvlTestMax = self.Wavelength.max() >= ionInfo[ionS]['wmin'] ioneqTest = (self.Temperature.max() >= ionInfo[ionS]['tmin']) and (self.Temperature.min() <= ionInfo[ionS]['tmax']) # construct similar test for the dielectronic files ionSd = util.zion2name(iz, ionstage, dielectronic=1) masterListTestD = ionSd in masterlist masterListInfoTestD = ionSd in ionInfo.keys() if masterListTestD or masterListInfoTestD: wvlTestMinD = self.Wavelength.min() <= ionInfo[ionSd]['wmax'] wvlTestMaxD = self.Wavelength.max() >= ionInfo[ionSd]['wmin'] ioneqTestD = (self.Temperature.max() >= ionInfo[ionSd]['tmin']) and (self.Temperature.min() <=ionInfo[ionSd]['tmax']) ionstageTest = ionstage > 1 if ionstageTest and ioneqTest and doContinuum: # ionS is the target ion, cannot be the neutral for the continuum print ' calculating continuum for : ', ionS cont = chianti.core.continuum(ionS, temperature) cont.freeFree(wavelength) # print dir(thisIon) # print ' wvl = ', thisIon.FreeFree['wvl'] if nTempDen ==1: freeFree += cont.FreeFree['rate'] else: for iTempDen in range(nTempDen): freeFree[iTempDen] += cont.FreeFree['rate'][iTempDen] # cont.freeBound(wavelength) if 'errorMessage' not in cont.FreeBound.keys(): # an fblvl file exists for this ions if nTempDen == 1: freeBound += cont.FreeBound['rate'] else: for iTempDen in range(nTempDen): freeBound[iTempDen] += cont.FreeBound['rate'][iTempDen] if masterListTest and wvlTestMin and wvlTestMax and ioneqTest: print ' calculating spectrum for : ', ionS thisIon = chianti.core.ion(ionS, temperature, density) ionsCalculated.append(ionS) # print ' dir = ', dir(thisIon) # thisIon.emiss(wvlRange = wvlRange, allLines=allLines) thisIon.intensity(wvlRange = wvlRange, allLines=allLines) # check that there are lines in this wavelength range if 'errorMessage' not in thisIon.Intensity.keys(): thisIon.spectrum(wavelength, filter=filter) # intensity = thisIon.Intensity['intensity'] if nTempDen == 1: lineSpectrum += thisIon.Spectrum['intensity'] else: for iTempDen in range(nTempDen): lineSpectrum[iTempDen] += thisIon.Spectrum['intensity'][iTempDen] # get 2 photon emission for H and He sequences if (iz - ionstage) in [0, 1]: thisIon.twoPhoton(wavelength) twoPhoton += thisIon.TwoPhoton['rate'] # get dielectronic lines if masterListTestD and wvlTestMinD and wvlTestMaxD and ioneqTestD: print ' calculating spectrum for : ', ionSd thisIon = chianti.core.ion(ionSd, temperature, density) ionsCalculated.append(ionSd) # print ' dir = ', dir(thisIon) # have to do all lines for the dielectronic satellites # thisIon.emiss(allLines=1) thisIon.intensity(wvlRange = wvlRange, allLines=allLines) # check that there are lines in this wavelength range - probably not redundant if 'errorMessage' not in thisIon.Intensity.keys(): thisIon.spectrum(wavelength, filter=filter) if nTempDen == 1: lineSpectrum += thisIon.Spectrum['intensity'] else: for iTempDen in range(nTempDen): lineSpectrum[iTempDen] += thisIon.Spectrum['intensity'][iTempDen] self.FreeFree = {'wavelength':wavelength, 'intensity':freeFree.squeeze()} self.FreeBound = {'wavelength':wavelength, 'intensity':freeBound.squeeze()} self.LineSpectrum = {'wavelength':wavelength, 'intensity':lineSpectrum.squeeze()} self.TwoPhoton = {'wavelength':wavelength, 'intensity':twoPhoton.squeeze()} # total = freeFree + freeBound + lineSpectrum + twoPhoton t2 = datetime.now() dt=t2-t1 print ' elapsed seconds = ', dt.seconds if type(em) != types.NoneType: if nEm == 1: integrated = total*em else: integrated = np.zeros_like(wavelength) for iTempDen in range(nTempDen): integrated += total[iTempDen]*em[iTempDen] self.Spectrum ={'wavelength':wavelength, 'intensity':total.squeeze(), 'filter':filter[0].__name__, 'width':filter[1], 'integrated':integrated, 'em':em, 'ions':ionsCalculated} else: self.Spectrum ={'wavelength':wavelength, 'intensity':total.squeeze(), 'filter':filter[0].__name__, 'width':filter[1], 'ions':ionsCalculated} # # ------------------------------------------------------------------------- # def lineSpectrumPlot(self, saveFile=0, plotContinuum=0, linLog = 'lin'): ''' to plot the spectrum as a function of wavelength''' # must follow setting top # pl.figure() ylabel = 'Intensity' # xlabel = 'Wavelength ('+self.Defaults['wavelength'] +')' # # ymin = 10.**(np.log10(emiss.min()).round(0)) # pl.ion() # pl.plot(self.LineSpectrum['wavelength'], self.LineSpectrum['intensity']) pl.xlabel(xlabel) pl.ylabel(ylabel) if saveFile: pl.savefig(saveFile)
wkerzendorf/chiantipy
chiantipy/chianti/core/Spectrum.py
Python
gpl-3.0
11,764
[ "Gaussian" ]
86d9dc2c5ddf34d9027e4bfd090889495f174f44a808abafb664d692d531db19
# Copyright (C) 2014 Karl R. Wurst # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA import unittest import sandbox import os.path from assignment import Assignment class test_Assignment(unittest.TestCase): def setUp(self): self.collector = Collector() def test_each(self): the_assignment = Assignment(sandbox.dir('assignment1.json')) the_assignment.accept(self.collector.visit) self.assertPathsExist() def assertPathsExist(self): self.assertTrue( self.collector.directories, msg="No directories collected.") self.assertTrue(self.collector.files, msg="No files collected.") for d in self.collector.directories: self.assertTrue( d.exists(), msg="Directory does not exist: " + str(d)) self.assertTrue(d.is_dir(), msg="Not a directory: " + str(d)) for f in self.collector.files: self.assertTrue(f.exists(), msg="File does not exist: " + str(f)) self.assertTrue(f.is_file(), msg="Not a file: " + str(f)) class Collector(object): def __init__(self): self.directories = [] self.files = [] def visit(self, submission_directory, files_to_collect): self.directories.append(submission_directory) for file in files_to_collect: self.files.append(file) if __name__ == '__main__': unittest.main()
kwurst/grading-scripts
test_assignment.py
Python
gpl-3.0
2,053
[ "VisIt" ]
44d21728e7aeaedf0d77e5de9781a28cccc35c04131b2b87a341872095fe9bd8
import os import yaml import pytest import moldesign as mdt from moldesign.compute import packages from .molecule_fixtures import * __PYTEST_MARK__ = ['internal', 'config'] # mark all tests in this module with this label (see ./conftest.py) @pytest.fixture(scope='function') def tempconfigfile(tmpdir): tmpdir = str(tmpdir) path = os.path.join(tmpdir, 'moldesign.yml') oldenviron = os.environ.get('MOLDESIGN_CONFIG', None) os.environ['MOLDESIGN_CONFIG'] = path with open(path, 'w') as cfile: cfile.write('devmode: true') yield path if oldenviron is not None: os.environ['MOLDESIGN_CONFIG'] = oldenviron else: os.environ.pop('MOLDESIGN_CONFIG') clean_config() def clean_config(): mdt.compute.config.clear() mdt.compute.init_config() def test_write_conf(tempconfigfile): mdt.compute.update_saved_config(run_local={'nwchem':True, 'opsin':True}) mdt.compute.update_saved_config(run_remote={'openmm':True}, run_local={'nwchem':False}) mdt.compute.update_saved_config(devmode=True) with open(tempconfigfile, 'r') as conffile: data = yaml.load(conffile) assert data['run_local'] == {'nwchem':False, 'opsin':True} assert data['run_remote'] == {'openmm':True} assert data['devmode'] @pytest.fixture def disconnect_docker(): oldhost = mdt.compute.config.default_docker_host mdt.compute.config.default_docker_host = '000.111:333' yield mdt.compute.config.default_docker_host = oldhost mdt.compute.compute.default_engine = None def test_docker_connection_failure(disconnect_docker): with pytest.raises(mdt.exceptions.DockerError): mdt.compute.reset_compute_engine() @pytest.mark.skipif(not packages.openbabel.is_installed(), reason='Only run if openbabel is present locally') def test_set_docker_python(tempconfigfile): njob = mdt._njobs g1 = mdt.from_smiles('CC') assert mdt._njobs == njob mdt.compute.update_saved_config(run_remote={'openbabel':True}) clean_config() g2 = mdt.from_smiles('CC') assert mdt._njobs == njob + 1 def test_docker_image_strings(tempconfigfile): mdt.compute.config.devmode = True assert mdt.compute.get_image_path('blah') == 'blah:dev' assert mdt.compute.get_image_path('a/b') == 'a/b:dev' mdt.compute.config.devmode = False mdt.compute.config.default_repository = 'myrepo/thing:' mdt.compute.config.default_version_tag = 'tagtag' assert mdt.compute.get_image_path('blah') == 'myrepo/thing:blah-tagtag' mdt.compute.config.default_repository = 'myrepo/thing' mdt.compute.config.default_version_tag = 'tagtag' assert mdt.compute.get_image_path('blah') == 'myrepo/thing/blah:tagtag' mdt.compute.config.default_repository = 'myrepo/thing/' assert mdt.compute.get_image_path('blah') == 'myrepo/thing/blah:tagtag' def test_nbmolviz_errors(ethylene): """ These should always raise importerrors because we're not running in Jupyter """ with pytest.raises(ImportError): mdt.widgets.BondSelector() with pytest.raises(ImportError): ethylene.draw()
Autodesk/molecular-design-toolkit
moldesign/_tests/test_config.py
Python
apache-2.0
3,146
[ "NWChem", "OpenMM" ]
ed76d1e1d0801ca6cdc806e739b3f2e3e29f4262af0b682739d21fadba3fe879
# coding: utf-8 # Copyright (c) Henniggroup. # Distributed under the terms of the MIT License. from __future__ import division, print_function, unicode_literals, \ absolute_import """ Defines the Interface(extends class Slab) and Ligand(extends class Molecule) classes """ from six.moves import range import sys import math import copy import numpy as np from pymatgen.core.structure import Structure, Molecule from pymatgen.core.lattice import Lattice from pymatgen.core.surface import Slab, SlabGenerator from pymatgen.core.operations import SymmOp from pymatgen.util.coord import get_angle from mpinterfaces.transformations import reduced_supercell_vectors from mpinterfaces.utils import get_ase_slab from mpinterfaces.default_logger import get_default_logger __author__ = "Kiran Mathew, Joshua J. Gabriel" __copyright__ = "Copyright 2017, Henniggroup" __maintainer__ = "Joshua J. Gabriel" __email__ = "joshgabriel92@gmail.com" __status__ = "Production" __date__ = "March 3, 2017" logger = get_default_logger(__name__) class Interface(Slab): """ Interface = slab + ligand + environment(solvent) Creates a Slab - Ligand Interface of given coverage and given slab-ligand displacement Args: strt: Starting Structure Object for Slab of the Interface hkl: Miller Index of Slab min_thick: Minimum Slab Thickness in Angstroms desired min_vac: Minimum Vacuum Spacing (Padding top and bottom, each) in Angstroms supercell: Trial supercell to start with to enforce coverage, default 1x1x1 name: System name to specify database entry (can be a combination of miller indices of slab and ligand and solvent) eg: "PbS [1,1,1] + Hydrazine in DMF (epsilon = 37.5)" adsorb_on_species: Reference atom on slab to adsorb on adatom_on_lig: bonding atom on ligand ligand: structure object for ligand displacement: initial adsorption distance desired above the adsorb_on_species surface_coverage: Number of ligands desired per surface area of slab, in ligands per square angstroms scell_max: Maximum number of supercells to create (used for finding supercell for the given coverage requirement coverage_tol: Tolerance for coverage calculation in Ligands per square Angstroms solvent: Name of solvent to be added for the run start_from_slab: Whether slab is given as input. Useful when custom reconstructed slabs are to be used validate_proximity: Check whether any atoms are too close (using pymatgen default of 0.01 Angstroms) to_unit_cell: Pymatgen Slab routine to find unit cell coords_are_cartesian: Whether the input coordinates are in cartesian from_ase: Whether to create Slab using python-ase for producing slabs that have orthogonal lattice vectors NOTE: if starting from the bulk structure, create slab note: if the starting structure is a slab, the vaccum extension is not possible """ def __init__(self, strt, hkl=[1, 1, 1], min_thick=10, min_vac=10, supercell=[1, 1, 1], name=None, adsorb_on_species=None, adatom_on_lig=None, ligand=None, displacement=1.0, surface_coverage=None, scell_nmax=10, coverage_tol=0.25, solvent=None, start_from_slab=False, validate_proximity=False, to_unit_cell=False, coords_are_cartesian=False, primitive=True, from_ase=False, lll_reduce=False, center_slab=True, max_normal_search=None, force_normalize=False, x_shift=0, y_shift=0, rot=[0, 0, 0]): self.from_ase = from_ase vac_extension = 0 if ligand is not None: vac_extension = ligand.max_dist if isinstance(strt, Structure) and not isinstance(strt, Slab): self.min_vac = min_vac + vac_extension if self.from_ase: strt = get_ase_slab(strt, hkl=hkl, min_thick=min_thick, min_vac=min_vac + vac_extension) else: slab = SlabGenerator(strt, hkl, min_thick, min_vac + vac_extension, center_slab=center_slab, lll_reduce=lll_reduce, max_normal_search=max_normal_search, primitive=primitive).get_slab() if force_normalize: strt = slab.get_orthogonal_c_slab() else: strt = slab strt.make_supercell(supercell) else: self.min_vac = min_vac Slab.__init__(self, strt.lattice, strt.species_and_occu, strt.frac_coords, miller_index=strt.miller_index, oriented_unit_cell=strt.oriented_unit_cell, shift=strt.shift, scale_factor=strt.scale_factor, validate_proximity=validate_proximity, to_unit_cell=to_unit_cell, coords_are_cartesian=coords_are_cartesian, site_properties=strt.site_properties, energy=strt.energy) self.strt = strt self.name = name self.hkl = hkl self.min_thick = min_thick self.supercell = supercell self.ligand = ligand self.slab = strt self.displacement = displacement self.solvent = solvent self.surface_coverage = surface_coverage self.adsorb_on_species = adsorb_on_species self.adatom_on_lig = adatom_on_lig self.scell_nmax = scell_nmax self.coverage_tol = coverage_tol self.x_shift = x_shift self.y_shift = y_shift self.rot = rot def set_top_atoms(self): """ set the list of top and bottom atoms indices """ n_atoms = len(self.frac_coords[:, 0]) a, b, c = self.oriented_unit_cell.lattice.matrix h = abs(np.dot(self.normal, c)) nlayers_slab = int(math.ceil(self.min_thick / h)) nlayers_vac = int(math.ceil(self.min_vac / h)) nlayers = nlayers_slab + nlayers_vac self.top_atoms = [] self.bottom_atoms = [] for i in range(n_atoms): if np.abs(self.frac_coords[i][2] - max( self.frac_coords[:, 2])) < 1e-6: if self[i].species_string == self.adsorb_on_species: self.top_atoms.append(i) elif np.abs(self.frac_coords[i][2] - min( self.frac_coords[:, 2])) < 1e-6: self.bottom_atoms.append(i) def enforce_coverage(self): """ adjusts the supercell size and the number of adsorbed ligands so as to meet the surface coverage criterion within the given tolerance limit(specified as fraction of the required surface coverage) returns the number of ligands and the supercell size that satisfies the criterion """ n_atoms = len(self.frac_coords[:, 0]) # self.top_bot_dist = np.max(self.distance_matrix.reshape(n_atoms*n_atoms, 1)) self.set_top_atoms() n_top_atoms = len(self.top_atoms) logger.info('number of top atoms = {}'.format(n_top_atoms)) max_coverage = n_top_atoms / self.surface_area m = self.lattice.matrix surface_area_orig = np.linalg.norm(np.cross(m[0], m[1])) logger.info( 'requested surface coverage = {}'.format(self.surface_coverage)) logger.info('maximum possible coverage = {}'.format(max_coverage)) if self.surface_coverage > max_coverage: logger.warn( 'requested surface coverage exceeds the max possible coverage. exiting.') sys.exit() else: for scell in range(1, self.scell_nmax): for nlig in range(1, scell * n_top_atoms + 1): surface_area = scell * surface_area_orig surface_coverage = nlig / surface_area diff_coverage = np.abs( surface_coverage - self.surface_coverage) if diff_coverage <= self.surface_coverage * self.coverage_tol: logger.info( 'tolerance limit = {}'.format(self.coverage_tol)) logger.info( 'possible coverage within the tolerance limit = {}'.format( nlig / surface_area)) logger.info('supercell size = {}'.format(scell)) logger.info('number of ligands = {}'.format(nlig)) return scell, nlig return None, None def get_reduced_scell(self): """ enforces the surface coverage criterion and generates the list all reduced lattice vectors that correspond to the computed supercell size and returns the one with similar lattice vector norms """ scell, nlig = self.enforce_coverage() if scell and nlig: ab = [self.lattice.matrix[0, :], self.lattice.matrix[1, :]] uv_list, _ = reduced_supercell_vectors(ab, scell) norm_list = [] for uv in uv_list: unorm = np.linalg.norm(uv[0]) vnorm = np.linalg.norm(uv[1]) norm_list.append(abs(1. - unorm / vnorm)) return nlig, uv_list[np.argmin(norm_list)] else: logger.warn( "couldn't find supercell and number of ligands that satisfy " "the required surface coverage. exiting.") sys.exit() def cover_surface(self, site_indices): """ puts the ligand molecule on the given list of site indices """ num_atoms = len(self.ligand) normal = self.normal # get a vector that points from one atom in the botton plane # to one atom on the top plane. This is required to make sure # that the surface normal points outwards from the surface on # to which we want to adsorb the ligand vec_vac = self.cart_coords[self.top_atoms[0]] - \ self.cart_coords[self.bottom_atoms[0]] # mov_vec = the vector along which the ligand will be displaced mov_vec = normal * self.displacement angle = get_angle(vec_vac, self.normal) # flip the orientation of normal if it is not pointing in # the right direction. if (angle > 90): normal_frac = self.lattice.get_fractional_coords(normal) normal_frac[2] = -normal_frac[2] normal = self.lattice.get_cartesian_coords(normal_frac) mov_vec = normal * self.displacement # get the index corresponding to the given atomic species in # the ligand that will bond with the surface on which the # ligand will be adsorbed adatom_index = self.get_index(self.adatom_on_lig) adsorbed_ligands_coords = [] # set the ligand coordinates for each adsorption site on # the surface for sindex in site_indices: # align the ligand wrt the site on the surface to which # it will be adsorbed origin = self.cart_coords[sindex] self.ligand.translate_sites(list(range(num_atoms)), origin - self.ligand[ adatom_index].coords) # displace the ligand by the given amount in the direction # normal to surface self.ligand.translate_sites(list(range(num_atoms)), mov_vec) # vector pointing from the adatom_on_lig to the # ligand center of mass vec_adatom_cm = self.ligand.center_of_mass - \ self.ligand[adatom_index].coords # rotate the ligand with respect to a vector that is # normal to the vec_adatom_cm and the normal to the surface # so that the ligand center of mass is aligned along the # outward normal to the surface origin = self.ligand[adatom_index].coords angle = get_angle(vec_adatom_cm, normal) if 1 < abs(angle % 180) < 179: # For angles which are not 0 or 180, # perform a rotation about the origin along an axis # perpendicular to both bonds to align bonds. axis = np.cross(vec_adatom_cm, normal) op = SymmOp.from_origin_axis_angle(origin, axis, angle) self.ligand.apply_operation(op) elif abs(abs(angle) - 180) < 1: # We have a 180 degree angle. # Simply do an inversion about the origin for i in range(len(self.ligand)): self.ligand[i] = (self.ligand[i].species_and_occu, origin - ( self.ligand[i].coords - origin)) # x - y - shifts x = self.x_shift y = self.y_shift rot = self.rot if x: self.ligand.translate_sites(list(range(num_atoms)), np.array([x, 0, 0])) if y: self.ligand.translate_sites(list(range(num_atoms)), np.array([0, y, 0])) if rot: self.ligand.apply_operation( SymmOp.from_axis_angle_and_translation( (1, 0, 0), rot[0], angle_in_radians=False, translation_vec=(0, 0, 0))) self.ligand.apply_operation( SymmOp.from_axis_angle_and_translation( (0, 1, 0), rot[1], angle_in_radians=False, translation_vec=(0, 0, 0))) self.ligand.apply_operation( SymmOp.from_axis_angle_and_translation( (0, 0, 1), rot[2], angle_in_radians=False, translation_vec=(0, 0, 0))) # 3d numpy array adsorbed_ligands_coords.append(self.ligand.cart_coords) # extend the slab structure with the adsorbant atoms adsorbed_ligands_coords = np.array(adsorbed_ligands_coords) for j in range(len(site_indices)): [self.append(self.ligand.species_and_occu[i], adsorbed_ligands_coords[j, i, :], coords_are_cartesian=True) for i in range(num_atoms)] def get_index(self, species_string): """ get the first site index of the atomic species """ for i in range(len(self.ligand)): if self.ligand[i].species_string == species_string: return i def create_interface(self): """ creates the interface i.e creates a slab of given thicknes and vacuum space. It ensures that the cell is big enough and have enough ligands to satify the surface coverage criterion also sets the slab on which the ligand is adsorbed """ if self.ligand: nlig, uv = self.get_reduced_scell() self.n_ligands = nlig logger.info( 'using {0} ligands on a supercell with in-plane lattice vectors\n{1}' .format(self.n_ligands, uv)) new_latt_matrix = [uv[0][:], uv[1][:], self.lattice.matrix[2, :]] new_latt = Lattice(new_latt_matrix) _, __, scell = self.lattice.find_mapping(new_latt) # self.scell = self.possible_scells[opt_lig_scell_index] self.make_supercell(scell) self.set_slab() self.set_top_atoms() self.adsorb_sites = [self.top_atoms[i] for i in range(self.n_ligands)] logger.info( 'ligands will be adsorbed on these sites on the slab {}'.format( self.adsorb_sites)) self.cover_surface(self.adsorb_sites) else: logger.info('no ligands. just the bare slab') def set_slab(self): """ set the slab on to which the ligand is adsorbed""" self.slab = Slab.from_dict(super(Interface, self).as_dict()) def as_dict(self): d = super(Interface, self).as_dict() d["@module"] = self.__class__.__module__ d["@class"] = self.__class__.__name__ d['hkl'] = list(self.miller_index) d['ligand'] = None if self.ligand: d['ligand'] = self.ligand.as_dict() if d.get('ligand'): d['num_ligands'] = self.n_ligands else: d['num_ligands'] = 0 return d def calc_energy(self, model='Coulomb'): """ calculates energy of the interface according to a defined energy model, useful for pre-screening candidate structures, returns 5 lowest energy structures Args: model: energy model to compute according to, default is Coulomb Returns: energy of structure according to model """ energy = 0 for i, sitei in enumerate(self): for j, sitej in enumerate(self): if i != j: dij = self.get_distance(i, j) Zi = list(sitei.species_and_occu.items())[0][0].Z Zj = list(sitej.species_and_occu.items())[0][0].Z energy += 0.5 * Zi * Zj / dij return energy class Ligand(Molecule): """ Construct ligand from molecules """ def __init__(self, mols, cm_dist=[], angle={}, link={}, remove=[], charge=0, spin_multiplicity=None, validate_proximity=False): Molecule.__init__(self, mols[0].species_and_occu, mols[0].cart_coords, charge=charge, spin_multiplicity=spin_multiplicity, validate_proximity=validate_proximity, site_properties=mols[0].site_properties) self._sites = list(self._sites) self.mols = mols self.cm_dist = cm_dist self.angle = angle self.link = link self.remove = remove if len(self.mols) == 1: self.set_distance_matrix(self.mols[0]) def get_perp_vec(self, vec1, vec2): """ returns the vector that is perpendicular to the vec1 and vec2 if the vectors are parllel, then perp_vec = (0, -z, y) """ if np.abs(np.dot(vec1, vec2) - np.linalg.norm(vec1) ** 2) < 1e-6: perp_vec = np.array([0, -vec1[2], vec1[1]]) else: perp_vec = np.cross(vec1, vec2) return perp_vec def set_distance_matrix(self, mol): """ sets the distance matrix for the molecule """ nsites = len(mol.sites) self.d_mat = np.array([mol.get_distance(i, j) for i in range(nsites) for j in range(nsites)]).reshape(nsites, nsites) self.max_dist = np.max(self.d_mat.reshape(nsites * nsites, 1)) def set_mol_vecs(self): """ get the start and end indices to define the vector that defines the molecule sets the vectors that point from the start index atom to the farthest atom for each molecule """ self.vec_indices = [] for mol in self.mols: nsites = len(mol.sites) self.set_distance_matrix(mol) temp = [] for i in range(nsites): if i not in temp: [temp.append([i, j]) for j in range(nsites) if np.abs(self.max_dist - self.d_mat[i, j]) < 1e-6] self.vec_indices.append(temp[0]) self.mol_vecs = [] for mol, vind in enumerate(self.vec_indices): self.mol_vecs.append(self.mols[mol].cart_coords[vind[1]] - self.mols[mol].cart_coords[vind[0]]) def position_mols(self): """ position the center of masses of the molecules wrt each other first movement is in the x direction """ new_mol = self.mols[0] mov_vec = np.array([1, 0, 0]) for i in range(len(self.mols) - 1): # cm1 = new_mol.center_of_mass new_cm = new_mol.center_of_mass # cm2 = self.mols[i+1].center_of_mass new_cm = new_cm + self.cm_dist[i] * mov_vec mov_vec = self.get_perp_vec(self.mol_vecs[i], mov_vec) mov_vec = mov_vec / np.linalg.norm(mov_vec) new_coords = self.mols[i + 1].cart_coords + new_cm self.mols[i + 1] = Molecule( self.mols[i + 1].species_and_occu, new_coords, charge=self.mols[i + 1]._charge, spin_multiplicity=self.mols[i + 1]._spin_multiplicity, site_properties=self.mols[i + 1].site_properties) new_mol = Molecule.from_sites( self.mols[i].sites + self.mols[i + 1].sites, validate_proximity=True) def rotate_mols(self): """ rotate the molecules wrt each other using the provided info """ # rotate the molecules around an axis that is # perpendicular to the molecular axes if self.angle: for mol in range(len(self.mols)): for ind_key, rot in self.angle[str(mol)].items(): perp_vec = np.cross(self.mol_vecs[int(ind_key)], self.mol_vecs[mol]) # if the vectors are parllel, # then perp_vec = (-y, x, 0) if np.abs(np.dot(self.mol_vecs[int(ind_key)], self.mol_vecs[mol]) - np.linalg.norm(self.mol_vecs[ mol]) ** 2) < 1e-6: perp_vec = np.array([-self.mol_vecs[mol][1], self.mol_vecs[mol][0], 0]) org_pt = self.vec_indices[mol][0] op = SymmOp.from_origin_axis_angle( self.mols[mol].cart_coords[org_pt], axis=perp_vec, angle=rot) self.mols[mol].apply_operation(op) def link_mols(self): """ link the molecules together connect the specified atoms of mol to the atoms of other molecules in the list connection means putting the atomm of the mol at a position that is the average of the position of the atoms of the molecules given in the list """ new_coords = np.array([0, 0, 0]) displacement = np.array([0, 0, 0]) if self.link: for mol in range(len(self.mols)): new_coords = copy.deepcopy(self.mols[mol].cart_coords) if link[str(mol)]: for ind_key, conn in self.link[str(mol)].items(): ind = int(ind_key) logger.info( 'connection list for atom of index {0} of molecule {1} : {2}'.format( ind, mol, conn)) coord = np.array([0, 0, 0]) # if connecting the molecule mol to only one atom of # just one another molecule # then move the atom close to the atom in mol and # shift the whole molecule non_neg = np.extract(np.array(conn) > 0, conn) if len(non_neg) == 1 and len(link[str(mol)]) == 1: for j, k in enumerate(conn): coord = self.mols[j].cart_coords[non_neg[0]] + \ np.random.rand(1, 3) + 1.0 displacement = coord - self.mols[mol].cart_coords[ ind] else: for j, k in enumerate(conn): if k >= 0: coord = coord + self.mols[j].cart_coords[k] coord = coord / len(conn) new_coords[ind, 0] = coord[0] new_coords[ind, 1] = coord[1] new_coords[ind, 2] = coord[2] new_coords = new_coords + displacement self.mols[mol] = Molecule( self.mols[mol].species_and_occu, new_coords, charge=self.mols[mol]._charge, spin_multiplicity=self.mols[mol]._spin_multiplicity, site_properties=self.mols[mol].site_properties) def create_ligand(self): """ create the ligand by assembling the provided individual molecules and removeing the specified atoms from the molecules """ self.set_mol_vecs() self.position_mols() self.rotate_mols() self.link_mols() for i in range(len(self.mols)): if self.remove[i]: self.mols[i].remove_sites(self.remove[i]) combine_mol_sites = self.mols[0].sites for j in range(1, len(self.mols)): combine_mol_sites = combine_mol_sites + self.mols[j].sites self._sites = combine_mol_sites self.set_distance_matrix(self) def as_dict(self): d = super(Ligand, self).as_dict() d["@module"] = self.__class__.__module__ d["@class"] = self.__class__.__name__ d['name'] = self.composition.formula return d def copy(self): return Structure.from_sites(self) # test if __name__ == '__main__': # the following example require: # acetic_acid.xyz and POSCAR.mp-21276_PbS # create lead acetate ligand # from 3 molecules: 2 acetic acid + 1 Pb import os PACKAGE_PATH = os.path.dirname(__file__) mol0 = Molecule.from_file( os.path.join(PACKAGE_PATH, "test_files", "acetic_acid.xyz")) mol1 = Molecule.from_file( os.path.join(PACKAGE_PATH, "test_files", "acetic_acid.xyz")) mol2 = Molecule(["Pb"], [[0, 0, 0]]) mols = [mol0, mol1, mol2] # center of mass distances in angstrom # example: 3 molecules and cm_dist = [4,2], # center of mass of mol1 is moved from mol0 in 1,0,0 direction by 4 A # mol2 is moved from the center of mass of the combined mol0+mol1 molecule by 2 A # in a direction that is perpendicular to the first moving direction and the # molecule vector of one of the molecules # for n molecules the size of cm_dist must be n-1 cm_dist = [1, 2] # optional parmater # example: angle={'0':{}, '1':{'0':90}, '2':{} } # rotate mol1 with respect to mol0 by 90 degreeen around and axis that is normal # to the plane containing the molecule vectors of mol0 and mol1 angle = {'0': {}, '1': {'0': 90}, '2': {}} # optional paramter # a dictionary describing the connection between the molecules, used if the # relative movemnet of the molecules throught the center of mass shift is not enough # the key is the index for the molecules # the value for each key is a list of lists wiht each list # indicating how the atom of index # corresponding to the list index in the molecule # coresponding to key should be connectd to the atoms # in the list # if not connecting to any atom of the molecule set that index for that molecule to -1 # example:- link = {'0':{}, '1':{}, '2':{'0':[6,2, -1]} } # the 0th atom of the third molecule,'2', is connected to the 6th # and 2nd atoms of molecules # '0' and '1' respectively and no coonection to the molecule'2' (indicated by -1) # if not connecting a single atom of one molecule to another atom # of one another molecule, connection basically means # putting the atom at a halfway distance between other atoms link = {'0': {}, '1': {}, '2': {'0': [6, 2, -1]}} # list of indices of atoms to be removed from each molecule remove = [[7], [7], []] # combined_mol = combine_mols(mols, cm_dist, angle, link=link, remove=remove) lead_acetate = Ligand(mols, cm_dist, angle=angle, link={}, remove=remove) lead_acetate.create_ligand() lead_acetate.to('xyz', 'lead_acetate.xyz') # put the ligand in a box boxed_lead_acetate = lead_acetate.get_boxed_structure(13, 13, 13) boxed_lead_acetate.to(fmt="poscar", filename="POSCAR_diacetate_boxed.vasp") # bulk PbS strt_pbs = Structure.from_file( os.path.join(PACKAGE_PATH, "test_files", "POSCAR_PbS")) # intital supercell, this wont be the final supercell if surface # coverage is specified supercell = [1, 1, 1] # miller index hkl = [1, 0, 0] # minimum slab thickness in Angstroms min_thick = 21 # minimum vacuum thickness in Angstroms # the maximum distance in the lignad will be added to this value min_vac = 10 # surface coverage in the units of lig/ang^2 # mind: exact coverage as provided cannot be guaranteed, # the slab will be constructed # with a coverage value thats close to the requested one # note: maximum supercell size possible is 10 x 10 # note: 1 lig/nm^2 = 0.01 lig/ang^2 surface_coverage = 0.001 # atom on the slab surface on which the ligand will be attached, # no need to specify if the slab is made of only a single species adsorb_on_species = 'Pb' # atom on ligand that will be attached to the slab surface adatom_on_lig = 'O' # ligand displacement from the slab surface along the surface normal # i.e adatom_on_lig will be displced by this amount from the # adsorb_on_species atom # on the slab # in Angstrom displacement = 2.0 # here we create the interface iface = Interface(strt_pbs, hkl=hkl, min_thick=min_thick, min_vac=min_vac, supercell=supercell, surface_coverage=surface_coverage, ligand=lead_acetate, displacement=displacement, adsorb_on_species=adsorb_on_species, adatom_on_lig=adatom_on_lig, primitive=False, scell_nmax=30) iface.create_interface() iface.sort() iface.to('poscar', 'POSCAR_interface.vasp') iface.slab.sort() iface.slab.to('poscar', 'POSCAR_slab.vasp') # H2O ligand # PBEPBE/aug-cc-pVQZ , from cccbdb # adatoms = ['O','H', 'H'] # adatoms_coords = np.array([ [0,0,0], # [0, 0.77, 0.60], # [0, -0.77, 0.60]]) # mol = Molecule(adatoms, adatoms_coords) # h2o = Ligand([mol])
henniggroup/MPInterfaces
mpinterfaces/interface.py
Python
mit
31,649
[ "ASE", "VASP", "pymatgen" ]
fbc4dfcf5065a0281cbe73f83bd6b0ad13db35d6e2002cb4f94ac00750a28c4d
import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from keras.datasets import mnist from keras.optimizers import RMSprop from vae import VariationalAutoEncoder # set parameters batch_size = 100 latent_dim = 2 nr_epochs = 30 layers = [256, 128] optimizer = RMSprop(lr=1e-3) # get MNIST digits (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:]))) x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:]))) # Train model original_dim = x_train.shape[1] vae_obj = VariationalAutoEncoder(original_dim, layers, activation='relu', optimizer=optimizer, dropout=0.25) vae = vae_obj.compile() vae.summary() vae.fit(x_train, x_train, shuffle=True, epochs=nr_epochs, batch_size=batch_size, validation_data=(x_test, x_test), verbose=2) # get the model that projects inputs on the latent space encoder = vae_obj.encoder # display a 2D plot of the digit classes in the latent space x_test_encoded = encoder.predict(x_test, batch_size=batch_size) plt.figure(figsize=(6, 6)) plt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], c=y_test) plt.colorbar() plt.show() # get a digit generator that can sample from the learned distribution generator = vae_obj.decoder # display a 2D manifold of the digits n = 15 # figure with 15x15 digits digit_size = 28 figure = np.zeros((digit_size * n, digit_size * n)) # linearly spaced coordinates on the unit square were transformed through the inverse CDF (ppf) of the Gaussian # to produce values of the latent variables z, since the prior of the latent space is Gaussian grid_x = norm.ppf(np.linspace(0.05, 0.95, n)) grid_y = norm.ppf(np.linspace(0.05, 0.95, n)) for i, yi in enumerate(grid_x): for j, xi in enumerate(grid_y): z_sample = np.array([[xi, yi]]) x_decoded = generator.predict(z_sample) digit = x_decoded[0].reshape(digit_size, digit_size) figure[i * digit_size: (i + 1) * digit_size, j * digit_size: (j + 1) * digit_size] = digit plt.figure(figsize=(10, 10)) plt.imshow(figure, cmap='Greys_r') plt.show()
DKaravolos/variational_autoencoder
train_vae_mnist.py
Python
mit
2,230
[ "Gaussian" ]
b6c489c86167c842a04b81b756c16e9a185dba72b01bc2a250a2d54eb050e045
# Global settings for core project. import os # PATH CONFIGURATION PROJECT_DIR = os.path.dirname(os.path.dirname(__file__)) PUBLIC_DIR = os.path.join(PROJECT_DIR, 'public') # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'plugin_manager.core.wsgi.application' # END PATH CONFIGURATION # DEBUG CONFIGURATION DEBUG = False TEMPLATE_DEBUG = True # END DEBUG CONFIGURATION # PAGINATION DEFAULT VALUE CONFIG NUM_RESULTS_PER_PAGE = 20 # END PAGINATION DEFAULT VALUE CONFIG # MANAGER CONFIGURATION ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS # END MANAGER CONFIGURATION # URL CONFIGURATION ROOT_URLCONF = 'plugin_manager.core.urls' # END URL CONFIGURATION # GENERAL CONFIGURATION TEST_RUNNER = 'django.test.runner.DiscoverRunner' # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'UTC' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Location of fixtures for the project FIXTURE_DIRS = ( os.path.join(PROJECT_DIR, 'fixtures'), ) # END GENERAL CONFIGURATION # MEDIA CONFIGURATION # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PUBLIC_DIR, 'media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # END MEDIA CONFIGURATION # STATIC FILE CONFIGURATION # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = os.path.join(PUBLIC_DIR, 'static') # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(PROJECT_DIR, 'static'), ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) # END STATIC FILE CONFIGURATION SOCKETIO_ENABLED = False # TEMPLATE CONFIGURATION GRAPPELLI_ADMIN_TITLE = 'Admin' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or # "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(PROJECT_DIR, 'templates'), ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.request', 'plugin_manager.core.context_processors.sidebar_lists', 'sekizai.context_processors.sekizai', ) # END TEMPLATE CONFIGURATION # MIDDLEWARE CONFIGURATION MIDDLEWARE_CLASSES = ( 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'stronghold.middleware.LoginRequiredMiddleware', ) # END MIDDLEWARE CONFIGURATION AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', # default ) ANONYMOUS_USER_ID = -1 # APP CONFIGURATION INSTALLED_APPS = ( # Django Core 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django_extensions', 'django.contrib.admin', # 3rd Party 'corsheaders', 'grappelli', 'djcelery', 'sekizai', 'crispy_forms', 'stronghold', 'django_tables2', 'bootstrapform', # Project 'plugin_manager.accounts', 'plugin_manager.hosts', 'plugin_manager.launch_window', ) # END APP CONFIGURATION FABFILE_PATH = os.path.join(os.path.dirname(PROJECT_DIR), 'fabfile.py') # STRONGHOLD CONFIGURATION LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/' STRONGHOLD_PUBLIC_NAMED_URLS = ( 'password_reset', 'password_reset_done', 'password_reset_complete', 'business_redirect_setup', ) STRONGHOLD_PUBLIC_URLS = ( r'^/reset/[0-9A-Za-z_\-]+/[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20}/', r'^/api/v1/.*', r'^/hosts/logs/elk*', ) # END STRONGHOLD CONFIGURATION # CRISPY CONFIGURATION CRISPY_TEMPLATE_PACK = "bootstrap3" # END CRISPY CONFIGURATION # EMAIL CONFIGURATION AUTH_USER_MODEL = 'accounts.DeployUser' # END EMAIL CONFIGURATION # EMAIL CONFIGURATION EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # EMAIL_HOST = 'localhost' # EMAIL_PORT = 25 # EMAIL_USE_TLS = False EMAIL_FROM = 'deploy@deploy.com' # END EMAIL CONFIGURATION # LOGGING CONFIGURATION # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } # END LOGGING CONFIGURATION CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': os.path.join(PUBLIC_DIR, '.django_cache'), } } FABRIC_TASK_CACHE_TIMEOUT = 60 * 60 * 24 # one day # celery CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' CELERY_TIMEZONE = 'UTC' # elasticsearch ELK_URL = "http://localhost" ELK_PORT = '9200' # cors #TODO enable white list CORS_ORIGIN_ALLOW_ALL = True
ahharu/plugin-manager
plugin_manager/core/settings/base.py
Python
mit
7,856
[ "Elk" ]
1abc41f3d5ba012cc6c20c855d62343c761801c015c1b1df5983a0cb6e025c1c
''' ResourceManagementHandler Module that allows users to access the ResourceManagementDB remotely. ''' from DIRAC import gConfig, S_OK, gLogger from DIRAC.Core.DISET.RequestHandler import RequestHandler from DIRAC.ResourceStatusSystem.Utilities import Synchronizer from DIRAC.ResourceStatusSystem.Service.ResourceStatusHandler import convert from DIRAC.ResourceStatusSystem.DB.ResourceManagementDB import ResourceManagementDB __RCSID__ = '$Id: $' def initializeResourceManagementHandler(_serviceInfo): ''' Handler initialization, where we set the ResourceManagementDB as global db. ''' global db db = ResourceManagementDB() syncObject = Synchronizer.Synchronizer() gConfig.addListenerToNewVersionEvent(syncObject.sync) return S_OK() ################################################################################ class ResourceManagementHandler(RequestHandler): ''' The ResourceManagementHandler exposes the DB front-end functions through a XML-RPC server, functionalities inherited from :class:`DIRAC.Core.DISET.Reques\ tHandler.RequestHandler` According to the ResourceManagementDB philosophy, only functions of the type: - insert - select - delete - addOrModify are exposed. If you need anything more complicated, either look for it on the :class:`ResourceManagementClient`, or code it yourself. This way the DB and the Service are kept clean and tidied. To can use this service on this way, but you MUST NOT DO IT. Use it through the :class:`ResourceManagementClient`. If offers in the worst case as good perfor\ mance as the :class:`ResourceManagementHandler`, if not better. >>> from DIRAC.Core.DISET.RPCClient import RPCCLient >>> server = RPCCLient("ResourceStatus/ResourceManagement") ''' def __init__(self, *args, **kwargs): super(ResourceManagementHandler, self).__init__(*args, **kwargs) @staticmethod def __logResult(methodName, result): ''' Method that writes to log error messages ''' if not result['OK']: gLogger.error('%s : %s' % (methodName, result['Message'])) @staticmethod def setDatabase(database): ''' This method let us inherit from this class and overwrite the database object without having problems with the global variables. :Parameters: **database** - `MySQL` database used by this handler :return: None ''' global db db = database types_insert = [basestring, dict] def export_insert(self, table, params): ''' This method is a bridge to access :class:`ResourceManagementDB` remotely. It does not add neither processing nor validation. If you need to know more about this method, you must keep reading on the database documentation. :Parameters: **table** - `string` or `dict` should contain the table from which querying if it's a `dict` the query comes from a client prior to v6r18 **params** - `dict` arguments for the mysql query. Currently it is being used only for column selection. For example: meta = { 'columns' : [ 'Name' ] } will return only the 'Name' column. :return: S_OK() || S_ERROR() ''' if isinstance(table, dict): # for backward compatibility: conversion is needed params, table = convert(table, params) gLogger.info('insert: %s %s' % (table, params)) # remove unnecessary key generated by locals() del params['self'] res = db.insert(table, params) self.__logResult('insert', res) return res types_select = [[basestring, dict], dict] def export_select(self, table, params): ''' This method is a bridge to access :class:`ResourceManagementDB` remotely. It does not add neither processing nor validation. If you need to know more\ about this method, you must keep reading on the database documentation. :Parameters: **table** - `string` or `dict` should contain the table from which querying if it's a `dict` the query comes from a client prior to v6r18 **params** - `dict` arguments for the mysql query. Currently it is being used only for column selection. For example: meta = { 'columns' : [ 'Name' ] } will return only the 'Name' column. :return: S_OK() || S_ERROR() ''' if isinstance(table, dict): # for backward compatibility: conversion is needed params, table = convert(table, params) gLogger.info('select: %s %s' % (table, params)) res = db.select(table, params) self.__logResult('select', res) return res types_delete = [[basestring, dict], dict] def export_delete(self, table, params): ''' This method is a bridge to access :class:`ResourceManagementDB` remotely.\ It does not add neither processing nor validation. If you need to know more \ about this method, you must keep reading on the database documentation. :Parameters: **table** - `string` or `dict` should contain the table from which querying if it's a `dict` the query comes from a client prior to v6r18 **params** - `dict` arguments for the mysql query. Currently it is being used only for column selection. For example: meta = { 'columns' : [ 'Name' ] } will return only the 'Name' column. :return: S_OK() || S_ERROR() ''' if isinstance(table, dict): # for backward compatibility: conversion is needed params, table = convert(table, params) gLogger.info('delete: %s %s' % (table, params)) res = db.delete(table, params) self.__logResult('delete', res) return res types_addOrModify = [[basestring, dict], dict] def export_addOrModify(self, table, params): ''' This method is a bridge to access :class:`ResourceManagementDB` remotely. It does not add neither processing nor validation. If you need to know more about this method, you must keep reading on the database documentation. :Parameters: **table** - `string` or `dict` should contain the table from which querying if it's a `dict` the query comes from a client prior to v6r18 **params** - `dict` arguments for the mysql query. Currently it is being used only for column selection. For example: meta = { 'columns' : [ 'Name' ] } will return only the 'Name' column. :return: S_OK() || S_ERROR() ''' if isinstance(table, dict): # for backward compatibility: conversion is needed params, table = convert(table, params) gLogger.info('addOrModify: %s %s' % (table, params)) res = db.addOrModify(table, params) self.__logResult('addOrModify', res) return res ################################################################################ # EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF
andresailer/DIRAC
ResourceStatusSystem/Service/ResourceManagementHandler.py
Python
gpl-3.0
6,815
[ "DIRAC" ]
f7bc62e9ff68b245251a7fa7c09f9a1f39b100914ed7a8a6884d9f409f99fa8c
#! /usr/bin/env python # # see also http://docs.openstack.org/cli/quick-start/content/nova-cli-reference.html # from __future__ import print_function import inspect import requests from datetime import datetime, timedelta import iso8601 import base64 import httplib import json import os import ast from pprint import pprint from urlparse import urlparse import copy from cloudmesh.config.cm_config import cm_config from cloudmesh.config.cm_config import cm_config_server from cloudmesh.config.cm_config import cm_config_flavor from cloudmesh.iaas.ComputeBaseType import ComputeBaseType from cloudmesh_base.logger import LOGGER # import novaclient # from novaclient.openstack.common import strutils def lineno(): """Returns the current line number in our program.""" return inspect.currentframe().f_back.f_lineno log = LOGGER(__file__) def donotchange(fn): return fn class openstack(ComputeBaseType): # : the type of the cloud. It is "openstack" type = "openstack" # global var # : a dict with the images images = {} # global var # : a dict with the flavors flavors = {} # global var # : a dict with the servers servers = {} # global var # : a dict with the users # users = {} # global var # : a dict containing the credentionls read with cm_config # credential = None # global var user_credential = None # global var admin_credential = None with_admin_credential = None user_token = None admin_token = None # : a unique label for the clous label = None # global var # cm_type = "openstack" # name = "undefined" # : This is the cloud, should be internal though with _ cloud = None # internal var for the cloud client in openstack keystone = None # : The user id user_id = None # internal var # _nova = nova def _load_admin_credential(self): isproduction = cm_config_server().get('cloudmesh.server.production') if isproduction: if self.admin_credential is None: if 'keystone' in cm_config_server().get('cloudmesh.server'): self.idp_clouds = cm_config_server().get( "cloudmesh.server.keystone").keys() self.with_admin_credential = self.label in self.idp_clouds if self.with_admin_credential: try: self.admin_credential = cm_config_server().get( "cloudmesh.server.keystone.{0}".format(self.label)) except: log.error(str( lineno()) + " No admin credential found! Please check your cloudmesh_server.yaml file.") else: self.admin_credential = None log.info( str(lineno()) + ": The cloud {0} has no admin credential".format(self.label)) return self.admin_credential else: return None # # initialize # # possibly make connext seperate def __init__(self, label, credential=None, admin_credential=None, service_url_type='publicURL'): """ initializes the openstack cloud from a file located at cloudmesh.yaml. However if a credential dict is used it is used instead """ self.clear() self.label = label user_credential = credential # HACK to avoid changes in older code self.user_credential = user_credential self.admin_credential = admin_credential self.service_url_type = service_url_type if user_credential is None: try: self.compute_config = cm_config() self.user_credential = self.compute_config.credential(label) except: log.error(str( lineno()) + ": No user credentail found! Please check your cloudmesh.yaml file.") # sys.exit(1) self._load_admin_credential() self.connect() def clear(self): """ clears the data of this openstack instance, a new connection including reading the credentials and a refresh needs to be called to obtain again data. """ # Todo: we may just use the name of the class instead as the type self._clear() self.user_token = None self.admin_token = None self.user_credentials = None self.admin_credentials = None self.type = "openstack" def connect(self): """ creates tokens for a connection """ log.info(str(lineno()) + ": Loading User Credentials") if self.user_credential is None: log.error( str(lineno()) + ": error connecting to openstack compute, credential is None") elif not self.user_token: self.user_token = self.get_token(self.user_credentials) # check if keystone is defined, and if failed print log msg # log.info(str(lineno()) + ": Loading Admin Credentials") if (self.admin_credential is None) and (self.with_admin_credential): log.error( str(lineno()) + ":error connecting to openstack compute, credential is None") else: try: if self.with_admin_credential and (not self.admin_token): self.admin_token = self.get_token(self.admin_credential) except: log.error(str(lineno()) + ": error connecting to openstack " + "keystone, credential or server name is invalid") def DEBUG(self, msg, line_number=None): if line_number is None: line_number = "" if msg == "credential": debug_dict = dict(self.user_credential) debug_dict['OS_PASSWORD'] = "********" log.debug( "{1} - GET CRED {0}".format(debug_dict, str(line_number))) else: log.debug("{0} - {1}".format(str(line_number), str(msg))) def auth(self): # DEBUG try: _args = locals() if 'self' in _args: del (_args['self']) log.debug("[{0}()] called with [{1}]".format(sys._getframe().f_code.co_name, str(_args))) log.debug("user_token:{0}".format(str(self.user_token))) except: pass return 'access' in self.user_token def get_token(self, credential=None): # DEBUG try: import sys _args = locals() if 'self' in _args: del (_args['self']) log.debug("[{0}()] called with [{1}]".format(sys._getframe().f_code.co_name, str(_args))) except: pass if credential is None: credential = self.user_credential self.DEBUG("credential", lineno()) param = None if 'OS_TENANT_NAME' in credential: param = {"auth": {"passwordCredentials": { "username": credential['OS_USERNAME'], "password": credential['OS_PASSWORD'], }, "tenantName": credential['OS_TENANT_NAME'] } } elif 'OS_TENANT_ID' in credential: param = {"auth": {"passwordCredentials": { "username": credential['OS_USERNAME'], "password": credential['OS_PASSWORD'], }, "tenantId": credential['OS_TENANT_ID'] } } url = "{0}/tokens".format(credential['OS_AUTH_URL']) log.debug(str(lineno()) + ": URL {0}".format(url)) headers = {'content-type': 'application/json'} verify = self._get_cacert(credential) print_param = copy.deepcopy(param) print_param["auth"]["passwordCredentials"]["password"] = "********" log.debug(str(lineno()) + ":PARAM {0}".format(json.dumps(print_param))) log.debug(str(lineno()) + ":HEADER {0}".format(headers)) log.debug(str(lineno()) + ":VERIFY {0}".format(verify)) r = requests.post(url, data=json.dumps(param), headers=headers, verify=verify) # pprint (r.json()) try: sanitized_r = copy.deepcopy(r.json()) if 'access' in sanitized_r: if 'token' in sanitized_r['access']: if 'id' in sanitized_r['access']['token']: sanitized_r['access']['token']['id'] = '******' log.debug("{0}".format(str(sanitized_r))) except: pass return r.json() # # FIND USER ID # def find_user_id(self, force=False): """ this method returns the user id and stores it for later use. """ config = cm_config() if not force: try: self.user_id = self.user_credential['OS_USER_ID'] return self.user_id except: self.user_id = None log.error("OS_USER_ID not set") self.user_token = self.get_token() self.user_id = self.user_token['access']['user']['id'] return self.user_id # not working yet # user role is disalowed to execute this by policy setting # admin role gives uninformative error def get_server_usage(self, serverid): apiurl = "servers/%s/diagnostics" % serverid return self._get(msg=apiurl, kind='admin', urltype='adminURL') def _get_service(self, type="compute", kind="user"): token = self.user_token # print token if kind == "admin": token = self.admin_token for service in token['access']['serviceCatalog']: if service['type'] == type: break return service def _get_compute_service(self, token=None): return self._get_service("compute") def _get_cacert(self, credential=None): if credential is None: credential = self.user_credential verify = False if 'OS_CACERT' in credential: if credential['OS_CACERT'] is not None and \ credential['OS_CACERT'] != "None" and \ os.path.isfile(credential['OS_CACERT']): verify = credential['OS_CACERT'] return verify def _post(self, posturl, params=None, credential=None): # print posturl # print self.config if credential is None: credential = self.user_credential conf = self._get_service_endpoint("compute") headers = {'content-type': 'application/json', 'X-Auth-Token': '%s' % conf['token']} # print headers # print self._get_cacert(credential) r = requests.post(posturl, headers=headers, data=json.dumps(params), verify=self._get_cacert(credential)) ret = {"msg": "success"} if r.text: try: ret = r.json() except: pass return ret def _put(self, posturl, credential=None, params=None): # print self.config if credential is None: credential = self.user_credential conf = self._get_service_endpoint("compute") headers = {'content-type': 'application/json', 'X-Auth-Token': '%s' % conf['token']} # print headers r = requests.put(posturl, headers=headers, data=json.dumps(params), verify=self._get_cacert(credential)) ret = {"msg": "success"} if r.text: try: ret = r.json() except: pass return ret # def ks_get_extensions(self): pass # conf = self._get_service_endpoint("identity") def keypair_list(self): apiurl = "os-keypairs" return self._get(msg=apiurl, urltype=self.service_url_type) def keypair_add(self, keyname, keycontent): log.debug(str(lineno()) + ":adding a keypair in cm_compute...") # keysnow = self.keypair_list() url = self._get_service_endpoint("compute")[self.service_url_type] posturl = "%s/os-keypairs" % url params = {"keypair": {"name": "%s" % keyname, "public_key": "%s" % keycontent } } # print params return self._post(posturl, params) def keypair_remove(self, keyname): log.debug(str(lineno()) + ":removing a keypair in cm_compute...") conf = self._get_service_endpoint("compute") url = conf[self.service_url_type] url = "%s/os-keypairs/%s" % (url, keyname) headers = {'content-type': 'application/json', 'X-Auth-Token': '%s' % conf['token']} r = requests.delete(url, headers=headers, verify=self._get_cacert()) ret = {"msg": "success"} if r.text: try: ret = r.json() except: pass return ret def vm_create(self, name, flavor_name, image_id, security_groups=None, key_name=None, meta={}, userdata=None): """ start a vm via rest api call """ # # TODO: add logic for getting default image # if image_id is None: # get image id from profile information (default image for that cloud) # TODO: add logic for getting label of machine # # if flavor_name is None: # get flavorname from profile information (ther is a get label function # ...) # if keyname is None: # get the default key from the profile information url = self._get_service_endpoint("compute")[self.service_url_type] posturl = "%s/servers" % url # print posturl # keycontent = base64.b64encode(key_name) secgroups = [] if security_groups: for secgroup in security_groups: secgroups.append({"name": secgroup}) else: secgroups = [{"name": "default"}] params = { "server": { "name": "%s" % name, "imageRef": "%s" % image_id, "flavorRef": "%s" % flavor_name, # max_count is the number of instances to launch # If 3 specified, three vm instances will be launched # "max_count": 1, # "min_count": 1, "security_groups": secgroups, "metadata": meta, } } if key_name: params["server"]["key_name"] = key_name if userdata: # # TODO: strutils not defined # # safe_userdata = strutils.safe_encode(userdata) # params["server"]["user_data"] = base64.b64encode(safe_userdata) safe_userdata = None log.debug(str(lineno()) + ":POST PARAMS {0}".format(params)) return self._post(posturl, params) def vm_delete(self, id): """ delete a single vm and returns the id """ conf = self._get_service_endpoint("compute") url = conf[self.service_url_type] url = "%s/servers/%s" % (url, id) headers = {'content-type': 'application/json', 'X-Auth-Token': '%s' % conf['token']} # print headers # no return from http delete via rest api r = requests.delete(url, headers=headers, verify=self._get_cacert()) ret = {"msg": "success"} if r.text: try: ret = r.json() except: pass return ret def stack_create(self, name, template_url, parameters, timeout_mins=60): """ Create a stack by OpenStack Heat Orchestration ref: http://developer.openstack.org/api-ref-orchestration-v1.html """ url = self._get_service_endpoint("orchestration")[self.service_url_type] posturl = "%s/stacks" % url try: param = ast.literal_eval(parameters) except ValueError: param = parameters params = { "stack_name": "%s" % name, "template_url": "%s" % template_url, "parameters": param, "timeout_mins": "%s" % timeout_mins } log.debug(str(lineno()) + ":POST PARAMS {0}".format(params)) return self._post(posturl, params) def stack_delete(self, stack_name): """ delete a specified stack and returns the id ref: http://developer.openstack.org/api-ref-orchestration-v1.html """ conf = self._get_service_endpoint("orchestration") url = conf[self.service_url_type] headers = {'content-type': 'application/json', 'X-Auth-Token': '%s' % conf['token']} # Find stacks msg = "stacks/%s" % stack_name service = "orchestration" r1 = self._get(msg, service=service, urltype=self.service_url_type) try: stack_id = r1['stack']['id'] except KeyError: log.warning("stack does not exist ({0})".format(stack_name)) ret = {"msg": "failed"} return ret url = "%s/stacks/%s/%s" % (url, stack_name, stack_id) # no return from http delete via rest api r = requests.delete(url, headers=headers, verify=self._get_cacert()) ret = {"msg": "success"} if r.text: try: ret = r.json() except: pass return ret # possibly for future use in network management via Neuron # currently is not being used def get_network_id(self): """ Obtaining router/expertnal gateway info via the rest api call """ ret = {"msg": "failed"} r = self._get('v2.0/routers', service='network', urltype=self.service_url_type) if "floating_ip" in r: ret = r["floating_ip"]["ip"] return r def get_public_ip(self): """ Obtaining a floating ip from the pool via the rest api call """ url = self._get_service_endpoint("compute")[self.service_url_type] posturl = "%s/os-floating-ips" % url ret = {"msg": "failed"} # Default to the default pool, possibly 'nova' # Before the juno deployment, this always worked r = self._post(posturl) # Since Juno deployment, the pool name was changed if 'itemNotFound' in r: if 'message' in r['itemNotFound'] and r['itemNotFound']['message'] == 'Floating ip pool not found.': # get floating ip pool name first r = self._get('os-floating-ip-pools') if 'floating_ip_pools' in r: # use the first pool pool = r['floating_ip_pools'][0]['name'] params = {'pool': pool} # reissue the request with returned pool name r = self._post(posturl, params) if "floating_ip" in r: ret = r["floating_ip"]["ip"] # # currently not being used # Nureon related operations # else: # gatewayinfo = self.get_network_id() # url = self._get_service_endpoint("network")[self.service_url_type] # posturl = '%s/v2.0/floatingips' % url # tenant_id = self.user_token['access']['token']['tenant']['id'] # params = {"floatingip":{"floating_network_id":<UUID from gatewayinfo>}} # r = self._post(posturl) # #r = self._get('/v2.0/floatingips',service='network') # print (r) return ret def assign_public_ip(self, serverid, ip): """ assigning public ip to an instance """ url = self._get_service_endpoint("compute")[self.service_url_type] posturl = "%s/servers/%s/action" % (url, serverid) params = {"addFloatingIp": { "address": "%s" % ip } } log.debug("POST PARAMS {0}".format(params)) return self._post(posturl, params) def delete_public_ip(self, idofip): """ delete a public ip that is assigned but not currently being used """ conf = self._get_service_endpoint("compute") url = conf[self.service_url_type] url = "%s/os-floating-ips/%s" % (url, idofip) headers = {'content-type': 'application/json', 'X-Auth-Token': '%s' % conf['token']} r = requests.delete(url, headers=headers, verify=self._get_cacert()) ret = {"msg": "success"} if r.text: try: ret = r.json() except: pass return ret def list_allocated_ips(self): """ return list of ips allocated to current account """ conf = self._get_service_endpoint("compute") url = conf[self.service_url_type] url = "%s/os-floating-ips" % url headers = {'content-type': 'application/json', 'X-Auth-Token': '%s' % conf['token']} r = requests.get(url, headers=headers, verify=self._get_cacert()) return r.json()["floating_ips"] def release_unused_public_ips(self): ips = self.list_allocated_ips() ips_id_to_instance = {} for ip in ips: ips_id_to_instance[ip['id']] = ip['instance_id'] for id, instance in ips_id_to_instance.iteritems(): if instance is None: self.delete_public_ip(id) return True def _get(self, msg, kind="user", service="compute", urltype="publicURL", payload=None, json=True): # kind = "admin", "user" # service = "publicURL, adminURL" # service= "compute", "identity", .... # token=None, url=None, kind=None, urltype=None, json=True): credential = self.user_credential token = self.user_token if kind is "admin": credential = self.admin_credential token = self.admin_token conf = self._get_service_endpoint(service) url = conf[urltype] url = "{0}/{1}".format(url, msg) log.debug(str(lineno()) + ": AUTH URL {0}".format(url)) headers = {'X-Auth-Token': token['access']['token']['id']} r = requests.get( url, headers=headers, verify=self._get_cacert(credential), params=payload) log.debug(str(lineno()) + ": Response {0}".format(r)) if json: return r.json() else: return r # http def _get_service_endpoint(self, type=None): """what example %/servers""" if type is None: type = "compute" compute_service = self._get_service(type) # pprint(compute_service) credential = self.user_credential # print credential conf = {} credential = self.user_credential conf['publicURL'] = str(compute_service['endpoints'][0]['publicURL']) # some cloud does not have this, e.g. HP cloud if 'internalURL' in compute_service['endpoints'][0]: conf['internalURL'] = str(compute_service['endpoints'][0]['internalURL']) if 'OS_REGION' in credential: for endpoint in compute_service['endpoints']: if endpoint['region'] == credential['OS_REGION']: conf['publicURL'] = endpoint['publicURL'] break conf['adminURL'] = None if 'adminURL' in compute_service['endpoints'][0]: conf['adminURL'] = str(compute_service['endpoints'][0]['adminURL']) conf['token'] = str(self.user_token['access']['token']['id']) return conf # new def _now(self): return datetime.now().strftime('%Y-%m-%dT%H-%M-%SZ') # new def _list_to_dict(self, list, id, type, time_stamp): d = {} # cm_type_version = self.compute_config.get('cloudmesh.clouds.{0}.cm_type_version'.format(self.label)) # log.debug ("CM TYPE VERSION {0}".format(cm_type_version)) for element in list: element['cm_type'] = type element['cm_cloud'] = self.label element['cm_cloud_type'] = self.type # element['cm_cloud_version'] = cm_type_version element['cm_refresh'] = time_stamp d[str(element[id])] = dict(element) return d # new def get_extensions(self): time_stamp = self._now() msg = "extensons" # list = self._get(msg)['extensions'] result = self._get(msg, urltype=self.service_url_type, json=False) if result.status_code == 404: log.error("extensions not available") return {} else: list = result.json() return self._list_to_dict(list, 'name', "extensions", time_stamp) def get_limits(self): '''Gets absolute and rate limit information, including information on currently used absolute limits.''' time_stamp = self._now() msg = "limits" _dict = self._get(msg, urltype=self.service_url_type)['limits'] return _dict def get_absolute_limits(self, view="original"): '''Gets absolute limit information Args: view (str) : two types of output available * original - returns integer value in a key and value pair * fraction - returns xx / xx fraction value ''' limits = self.get_limits() if view == "fraction": new_limits = {"Cores": None, "Instances": None, "RAM": None, "SecurityGroups": None, "FloatingIps": None} new_limits['Cores'] = str(limits['absolute']['totalCoresUsed']) + \ " / " + str(limits['absolute']['maxTotalCores']) new_limits['Instances'] = \ str(limits['absolute']['totalInstancesUsed']) + " / " + \ str(limits['absolute']['maxTotalInstances']) new_limits['RAM'] = str(limits['absolute']['totalRAMUsed']) + \ " / " + str(limits['absolute']['maxTotalRAMSize']) new_limits['SecurityGroups'] = \ str(limits['absolute']['totalSecurityGroupsUsed']) + " / " + \ str(limits['absolute']['maxSecurityGroups']) new_limits['FloatingIps'] = \ str(limits['absolute']['totalFloatingIpsUsed']) + " / " + \ str(limits['absolute']['maxTotalFloatingIps']) return new_limits else: return limits['absolute'] # new def get_servers(self): time_stamp = self._now() msg = "servers/detail" list = self._get(msg, urltype=self.service_url_type)['servers'] self.servers = self._list_to_dict(list, 'id', "server", time_stamp) # # hack for the hp cloud west # for server in self.servers: self.servers[server]['id'] = str(self.servers[server]['id']) return self.servers # new def get_flavors(self): time_stamp = self._now() msg = "flavors/detail" list = self._get(msg, urltype=self.service_url_type)['flavors'] self.flavors = self._list_to_dict(list, 'name', "flavor", time_stamp) # # hack for the hp cloud west # for flavor in self.flavors: self.flavors[flavor]['id'] = str(self.flavors[flavor]['id']) return self.flavors def flavorid(self, name): for key in self.flavors: if self.flavors[key]['name'] == name: return key def flavor(self, id_or_name): keys = self.flavors.keys() if id_or_name not in keys: key = self.flavorid(id_or_name) return self.flavors[key] # new def get_images(self): '''List images''' time_stamp = self._now() msg = "images/detail" list = self._get(msg, urltype=self.service_url_type)['images'] self.images = self._list_to_dict(list, 'id', "image", time_stamp) return self.images def get_security_groups(self): '''Lists security groups. ''' time_stamp = self._now() list = self.list_security_groups()['security_groups'] self.security_groups = self._list_to_dict(list, 'id', 'security_group', time_stamp) return self.security_groups def get_stacks(self): '''Lists active stacks.''' time_stamp = self._now() msg = "stacks" service = "orchestration" list = self._get(msg, service=service, urltype=self.service_url_type)['stacks'] self.stacks = self._list_to_dict(list, 'id', 'stacks', time_stamp) return self.stacks def get_usage(self): '''Report usage statistics on compute and storage resources.''' time_stamp = self._now() tenant_id = self.user_token['access']['token']['tenant']['id'] msg = "os-simple-tenant-usage/{0}".format(tenant_id) param = {"start": datetime.now() - timedelta(hours=24), "end": datetime.now()} _dict = self._get(msg, urltype=self.service_url_type, payload=param)['tenant_usage'] log.debug(_dict) self.usage = _dict return _dict def get_quota(self): ''' View quotas for a tenant (project). Administrators only, depending on policy settings. ''' time_stamp = self._now() tenant_id = self.user_token['access']['token']['tenant']['id'] msg = "os-quota-sets/{0}".format(tenant_id) _dict = self._get(msg, urltype=self.service_url_type)['quota_set'] log.debug(_dict) return _dict # new """ def get_tenants(self, credential=None): time_stamp = self._now() #get the tenants dict for the vm with the given id if credential is None: p = cm_profile() name = self.label credential = p.server.get("cloudmesh.server.keystone")[name] msg = "tenants" list = self._get(msg, kind="admin")['tenants'] return self._list_to_dict(list, 'id', "tenants", time_stamp) # new def get_users(self, credential=None): time_stamp = self._now() #get the tenants dict for the vm with the given id if credential is None: p = cm_profile() name = self.label idp_clouds = p.server.get("cloudmesh.server.keystone").keys() if name in idp_clouds: credential = p.server.get("cloudmesh.server.keystone")[name] else: log.error("The cloud {0} does not have keyston access".format(name)) return dict({}) cloud = openstack(name, credential=credential) msg = "users" list = cloud._get(msg, kind="admin", service="identity", urltype='adminURL')['users'] return self._list_to_dict(list, 'id', "users", time_stamp) """ def get_meta(self, id): """get the metadata dict for the vm with the given id""" msg = "/servers/%s/metadata" % id return self._get(msg, urltype=self.service_url_type) def set_meta(self, id, metadata, replace=False): """set the metadata for the given vm with the id""" conf = self._get_service_endpoint() conf['serverid'] = id if replace: conf['set'] = "PUT" else: conf['set'] = "POST" apiurlt = urlparse(conf[self.service_url_type]) url2 = apiurlt[1] params2 = '{"metadata":' + str(metadata).replace("'", '"') + '}' headers2 = {"X-Auth-Token": conf[ 'token'], "Accept": "application/json", "Content-type": "application/json"} print("%%%%%%%%%%%%%%%%%%") pprint(conf) print("%%%%%%%%%%%%%%%%%%") print("PARAMS", params2) print("HEADERS", headers2) print("API2", apiurlt[2]) print("API1", apiurlt[1]) print("ACTIVITY", conf['set']) print("ID", conf['serverid']) print("####################") conn2 = httplib.HTTPConnection(url2) conn2.request(conf['set'], "%s/servers/%s/metadata" % (apiurlt[2], conf['serverid']), params2, headers2) response2 = conn2.getresponse() data2 = response2.read() dd2 = json.loads(data2) conn2.close() return dd2 # # refresh # # identity management moved to its dedicated class """ def _get_users_dict(self): result = self.get_users() return result def _get_tenants_dict(self): result = self.get_tenants() return result """ def _get_images_dict(self): result = self.get_images() return result def _get_flavors_dict(self): try: result = self.get_flavors_from_yaml() except: result = None if not result: return self.get_flavors() self.flavors = result return self.flavors def get_flavors_from_yaml(self): obj = cm_config_flavor() flavors = obj.get('cloudmesh.flavor') return flavors.get(self.label) def _get_servers_dict(self): result = self.get_servers() return result def _get_security_groups_dict(self): result = self.get_security_groups() return result def _get_stacks_dict(self): result = self.get_stacks() return result def _get_usage_dict(self): result = self.get_usage() return result def limits(self): """ returns the limits of a tenant""" list = [] info = self.get_limits() for rate in info['rate']: limit_set = rate['limit'] print(limit_set) for limit in limit_set: list.append(limit) print(list) return list # return the security groups for the current authenticated tenant, in dict # format def list_security_groups(self): apiurl = "os-security-groups" return self._get(apiurl, urltype=self.service_url_type) # return the security group id given a name, if it's defined in the current tenant # The id is used to identify a group when adding more rules to it def find_security_groupid_by_name(self, name): groupid = None secgroups = self.list_security_groups() for secgroup in secgroups["security_groups"]: if secgroup["name"] == name: groupid = secgroup["id"] break return groupid # creating a security group, and optionally add rules to it # for the current TENANT that it authenticated as # This implementation is based on the rest api def create_security_group(self, secgroup, rules=[]): url = self._get_service_endpoint("compute")[self.service_url_type] posturl = "%s/os-security-groups" % url params = {"security_group": { "name": secgroup.name, "description": secgroup.description } } # log.debug ("POST PARAMS {0}".format(params)) ret = self._post(posturl, params) groupid = None # upon successful, it returns a dict keyed by 'security_group', # otherwide may have failed due to some reason if "security_group" in ret: groupid = ret["security_group"]["id"] # if the security group object has rules included, add them first if len(secgroup.rules) > 0: self.add_security_group_rules(groupid, secgroup.rules) # only trying to add the additional rules if the empty group has been # created successfully if not groupid: log.error( "Failed to create security group. Error message: '%s'" % ret) else: self.add_security_group_rules(groupid, rules) # return the groupid of the newly created group, or None if failed return groupid # add rules to an existing security group def add_security_group_rules(self, groupid, rules): url = self._get_service_endpoint("compute")[self.service_url_type] posturl = "%s/os-security-group-rules" % url ret = None for rule in rules: params = {"security_group_rule": { "ip_protocol": rule.ip_protocol, "from_port": rule.from_port, "to_port": rule.to_port, "cidr": rule.cidr, "parent_group_id": groupid } } # log.debug ("POST PARAMS {0}".format(params)) ret = self._post(posturl, params) if "security_group_rule" not in ret: if 'badRequest' in ret and ret['badRequest']['message'].startswith('This rule already exists'): log.warning("The rule already exists") else: log.error( "Failed to create security group rule(s). Error message: '%s'" % ret) break return ret # # security Groups of VMS # # GVL: review # how does this look for azure and euca? Should there be a general framework for this in the BaseCloud class # based on that analysis? # # comments of wht these things do and how they work are missing # ''' def createSecurityGroup(self, default_security_group, description="no-description"): """ comment is missing """ protocol = "" ipaddress = "" max_port = "" min_port = "" default_security_group_id = self.cloud.security_groups.create( default_security_group, description) default_security_group_id = default_security_group_id.id config_security = cm_config() yamlFile = config_security.get() ruleNames = yamlFile['security'][ 'security_groups'][default_security_group] for ruleName in ruleNames: rules = yamlFile['security']['rules'][ruleName] for key, value in rules.iteritems(): if 'protocol' in key: protocol = value elif 'max_port' in key: max_port = value elif 'min_port' in key: min_port = value else: ip_address = value self.cloud.security_group_rules.create( default_security_group_id, protocol, min_port, max_port, ip_address) return default_security_group # GVL: review # how does this look for azure and euca? Should there be a general framework for this in the BaseCloud class # based on that analysis? # # comments of wht these things do and how they work are missing def checkSecurityGroups(self): """ TODO: comment is missing """ config_security = cm_config() names = {} securityGroups = self.cloud.security_groups.list() for securityGroup in securityGroups: names[securityGroup.name] = securityGroup.id yamlFile = config_security.get() if yamlFile.has_key('security'): default_security_group = yamlFile['security']['default'] else: return None # default_security_group_id=names[default_security_group] if default_security_group in names: return default_security_group else: return self.createSecurityGroup(default_security_group) # GVL: review # how does this look for azure and euca? Should there be a general framework for this in the BaseCloud class # based on that analysis? # # comments of wht these things do and how they work are missing # def get_public_ip(self): """ TODO: comment is missing """ return self.cloud.floating_ips.create() # GVL: review # how does this look for azure and euca? Should there be a general framework for this in the BaseCloud class # based on that analysis? # # comments of wht these things do and how they work are missing # def assign_public_ip(self, serverid, ip): """ comment is missing """ self.cloud.servers.add_floating_ip(serverid, ip) # # set vm meta # def vm_set_meta(self, vm_id, metadata): """an experimental class to set the metadata""" print metadata is_set = 0 # serverid = self.servers[id]['manager'] while not is_set: try: print "set ", vm_id, "to set", metadata result = self.cloud.servers.set_meta(vm_id, metadata) # body = {'metadata': metadata} # print body # result = self.cloud.servers._create("/servers/%s/metadata" % # vm_id, body, "metadata") print result is_set = 1 except Exception, e: print "ERROR", e time.sleep(2) print result # # create a vm # def vm_create(self, name=None, flavor_name=None, image_id=None, security_groups=None, key_name=None, meta=None): """ create a vm with the given parameters """ if not key_name is None: if not self.check_key_pairs(key_name): config = cm_config() dict_t = config.get() key = dict_t['keys']['keylist'][key_name] if not 'ssh-rsa' in key and not 'ssh-dss' in key: key = open(key, "r").read() self.upload_key_pair(key, key_name) config = cm_config() if flavor_name is None: flavor_name = config.default(self.label)['flavor'] if image_id is None: image_id = config.default(self.label)['image'] # print "CREATE>>>>>>>>>>>>>>>>" # print image_id # print flavor_name vm_flavor = self.cloud.images.find(name=flavor_name) vm_image = self.cloud.images.find(id=image_id) if key_name is None: vm = self.cloud.servers.create(name, flavor=vm_flavor, image=vm_image, security_groups=security_groups, meta=meta ) else: # bug would passing None just work? vm = self.cloud.servers.create(name, flavor=vm_flavor, image=vm_image, key_name=key_name, security_groups=security_groups, meta=meta ) delay = vm.user_id # trick to hopefully get all fields data = vm.__dict__ del data['manager'] # data['cm_name'] = name # data['cm_flavor'] = flavor_name # data['cm_image'] = image_id # return {str(data['id']): data} # should probably just be return data # # delete vm(s) # def vm_delete(self, id): """ delete a single vm and returns the id """ vm = self.cloud.servers.delete(id) # return just the id or None if its deleted return vm @donotchange def vms_delete(self, ids): """ delete many vms by id. ids is an array """ for id in ids: print "Deleting %s" % self.servers[id]['name'] vm = self.vm_delete(id) return ids # # list user images # ''' @donotchange def vms_user(self, refresh=False): """ find my vms """ user_id = self.find_user_id() time_stamp = datetime.now().strftime('%Y-%m-%dT%H-%M-%SZ') if refresh: self.refresh("servers") result = {} for (key, vm) in self.servers.items(): if vm['user_id'] == self.user_id: result[key] = vm return result # # list project vms # def vms_project(self, refresh=False): """ find my vms that arein this project. this method was needed for openstack essex deployment on fg """ user_id = self.find_user_id() time_stamp = datetime.now().strftime('%Y-%m-%dT%H-%M-%SZ') if refresh: self.refresh("images") result = {} for (key, vm) in self.servers.items(): result[key] = vm return result # # delete images from a user # @donotchange def vms_delete_user(self): """ find my vms and delete them """ user_id = self.find_user_id() vms = self.find('user_id', user_id) self.vms_delete(vms) return # # find # @donotchange def find(self, key, value=None): """find my vms""" ids = [] if key == 'user_id' and value is None: value = self.user_id for (id, vm) in self.servers.items(): if vm[str(key)] == value: ids.append(str(vm['id'])) return ids # # rename # ''' def rename(self, old, new, id=None): """rename the vm with the given name old to new. If more than one exist with the same name only the first one will be renamed. consider moving the code to the baseclass.""" all = self.find('name', old) print all if len(all) > 0: id = all[0] vm = self.cloud.servers.update(id, new) return # TODO: BUG WHY ARE TGERE TWO REINDEX FUNCTIONS? @donotchange def reindex(self, prefixold, prefix, index_format): all = self.find('user_id') counter = 1 for id in all: old = self.servers[id]['name'] new = prefix + index_format % counter print "Rename %s -> %s, %s" % (old, new, self.servers[id]['key_name']) if old != new: vm = self.cloud.servers.update(id, new) counter += 1 ''' # # TODO # """ refresh just a specific VM delete all images that follow a regualr expression in name look into sort of images, images, vms """ # # EXTRA # # will be moved into one class @donotchange def table_col_to_dict(self, body): """converts a given list of rows to a dict""" result = {} for element in body: key = element[0] value = element[1] result[key] = value return result @donotchange def table_matrix(self, text, format=None): """converts a given pretty table to a list of rows or a dict. The format can be specified with 'dict' to return a dict. otherwise it returns an array""" lines = text.splitlines() headline = lines[0].split("|") headline = headline[1:-1] for i in range(0, len(headline)): headline[i] = str(headline[i]).strip() lines = lines[1:] body = [] for l in lines: line = l.split("|") line = line[1:-1] entry = {} for i in range(0, len(line)): line[i] = str(line[i]).strip() if format == "dict": key = headline[i] entry[key] = line[i] if format == "dict": body.append(entry) else: body.append(line) if format == 'dict': return body else: return (headline, body) # # CLI call of ussage # # will be moved into utils @donotchange def parse_isotime(self, timestr): """Parse time from ISO 8601 format""" try: return iso8601.parse_date(timestr) except iso8601.ParseError as e: raise ValueError(e.message) except TypeError as e: raise ValueError(e.message) def usage(self, tenant_id=None, serverid=None, start=None, end=None, format='dict'): """ returns the usage information of the tennant""" DEFAULT_STAT_DURATION = 30 if not tenant_id: url = self._get_service_endpoint("compute")[self.service_url_type] urlsplit = url.split("/") tenant_id = urlsplit[len(urlsplit) - 1] # print 70 * "-" # print self.cloud.certs.__dict__.get() # print 70 * "-" # tenantid = "member" # not sure how to get that if not end: end = datetime.now() # end = self._now() if not start: start = end - timedelta(days=DEFAULT_STAT_DURATION) # start = start.strftime('%Y-%m-%dT%H-%M-%SZ') # iso_start = self.parse_isotime(start) # iso_end = self.parse_isotime(end) # print ">>>>>", iso_start, iso_end # info = self.cloud.usage.get(tenantid, iso_start, iso_end) # print info.__dict__ # sys.exit() # (start, rest) = start.split("T") # ignore time for now # (end, rest) = end.split("T") # ignore time for now apiurl = "os-simple-tenant-usage/%s" % tenant_id payload = {'start': start, 'end': end} result = self._get(apiurl, payload=payload, urltype=self.service_url_type)['tenant_usage'] instances = result['server_usages'] numInstances = len(instances) ramhours = result['total_memory_mb_usage'] cpuhours = result['total_hours'] vcpuhours = result['total_vcpus_usage'] diskhours = result['total_local_gb_usage'] # if serverid provided, only return the server specific data ret = None if serverid: for instance in instances: if instance["instance_id"] == serverid: ret = instance break # else return tenant usage info else: ret = {'tenant_id': tenant_id, 'start': start.strftime('%Y-%m-%dT%H-%M-%SZ'), 'end': end.strftime('%Y-%m-%dT%H-%M-%SZ'), 'instances': numInstances, 'cpuHours': cpuhours, 'vcpuHours': vcpuhours, 'ramMBHours': ramhours, 'diskGBHours': diskhours} return ret # (headline, matrix) = self.table_matrix(result) # headline.append("Start") # headline.append("End") # matrix[0].append(start) # matrix[0].append(end) # if format == 'dict': # result = {} # for i in range(0, len(headline)): # result[headline[i]] = matrix[0][i] # return result # else: # return (headline, matrix[0]) # # CLI call of absolute-limits # # def limits(self): # conf = get_conf() # return _get(conf, "%s/limits") ''' def check_key_pairs(self, key_name): """simple check to see if a keyname is in the keypair list""" allKeys = self.cloud.keypairs.list() for key in allKeys: if key.name in key_name: return True return False # # Upload Key Pair # def upload_key_pair(self, publickey, name): """ Uploads key pair """ try: self.cloud.keypairs.create(name, publickey) except Exception, e: return 1, e return (0, 'Key added successfully') # # Delete Key Pair # def delete_key(self, name): """ delets key pair """ try: self.cloud.keypairs.delete(name) except Exception, e: return (1, e) return (0, 'Key deleted successfully') # # List Security Group # def sec_grp_list(self): """ lists all security groups """ try: return self.cloud.security_groups.list() except Exception, e: print e states = [ "ACTIVE", "ERROR", "BUILDING", "PAUSED", "SUSPENDED", "STOPPED", "DELETED", "RESCUED", "RESIZED", "SOFT_DELETED" ] def display(self, states, userid): """ simple or on states and check if userid. If userid is None all users will be marked. A new variable cm_display is introduced manageing if a VM should be printed or not""" for (id, vm) in self.servers.items(): vm['cm_display'] = vm['status'] in states if userid is not None: vm['cm_display'] = vm['cm_display'] and ( vm['user_id'] == userid) ''' def display_regex(self, state_check, userid): print(state_check) for (id, vm) in self.servers.items(): vm['cm_display'] = eval(state_check) # vm['cm_display'] = vm['status'] in states if userid is not None: vm['cm_display'] = vm['cm_display'] and ( vm['user_id'] == userid) # # MAIN FOR TESTING # if __name__ == "__main__": """ cloud = openstack("india-openstack") name ="%s-%04d" % (cloud.credential["OS_USERNAME"], 1) out = cloud.vm_create(name, "m1.tiny", "6d2bca76-8fff-4d57-9f29-50378539b4fa") pprint(out) """ # cloud = openstack("india") # flavors = cloud.get_flavors() # for flavor in flavors: # print(flavor) # keys = cloud.list_key_pairs() # for key in keys: # print key.name """ print cloud.find_user_id() """ """ for i in range (1,3): name ="%s-%04d" % (cloud.credential["OS_USERNAME"], i) out = cloud.vm_create(name, "m1.tiny", "6d2bca76-8fff-4d57-9f29-50378539b4fa") <pprint(out) """ """ print cloud.find('name', name) """ # cloud.rename("gvonlasz-0001","gregor")
rajpushkar83/cloudmesh
cloudmesh/iaas/openstack/cm_compute.py
Python
apache-2.0
55,386
[ "NEURON" ]
5375520e70a6c4549edfb2140408bc7862bf19aefc7aff641f0c86331146226b
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * import os class Ferret(Package): """Ferret is an interactive computer visualization and analysis environment designed to meet the needs of oceanographers and meteorologists analyzing large and complex gridded data sets.""" homepage = "http://ferret.pmel.noaa.gov/Ferret/home" url = "ftp://ftp.pmel.noaa.gov/ferret/pub/source/fer_source.v696.tar.gz" version('6.96', '51722027c864369f41bab5751dfff8cc') depends_on("hdf5~mpi~fortran") depends_on("netcdf~mpi") depends_on("netcdf-fortran") depends_on("readline") depends_on("zlib") def url_for_version(self, version): return "ftp://ftp.pmel.noaa.gov/ferret/pub/source/fer_source.v{0}.tar.gz".format( version.joined) def patch(self): hdf5_prefix = self.spec['hdf5'].prefix netcdff_prefix = self.spec['netcdf-fortran'].prefix readline_prefix = self.spec['readline'].prefix libz_prefix = self.spec['zlib'].prefix filter_file(r'^BUILDTYPE.+', 'BUILDTYPE = x86_64-linux', 'FERRET/site_specific.mk') filter_file(r'^INSTALL_FER_DIR.+', 'INSTALL_FER_DIR = %s' % self.spec.prefix, 'FERRET/site_specific.mk') filter_file(r'^HDF5_DIR.+', 'HDF5_DIR = %s' % hdf5_prefix, 'FERRET/site_specific.mk') filter_file(r'^NETCDF4_DIR.+', 'NETCDF4_DIR = %s' % netcdff_prefix, 'FERRET/site_specific.mk') filter_file(r'^READLINE_DIR.+', 'READLINE_DIR = %s' % readline_prefix, 'FERRET/site_specific.mk') filter_file(r'^LIBZ_DIR.+', 'LIBZ_DIR = %s' % libz_prefix, 'FERRET/site_specific.mk') filter_file(r'^JAVA_HOME.+', ' ', 'FERRET/site_specific.mk') filter_file(r'-lm', '-lgfortran -lm', 'FERRET/platform_specific.mk.x86_64-linux') def install(self, spec, prefix): hdf5_prefix = spec['hdf5'].prefix netcdff_prefix = spec['netcdf-fortran'].prefix netcdf_prefix = spec['netcdf'].prefix libz_prefix = spec['zlib'].prefix ln = which('ln') ln('-sf', hdf5_prefix + '/lib', hdf5_prefix + '/lib64') ln('-sf', netcdff_prefix + '/lib', netcdff_prefix + '/lib64') ln('-sf', netcdf_prefix + '/lib/libnetcdf.a', netcdff_prefix + '/lib/libnetcdf.a') ln('-sf', netcdf_prefix + '/lib/libnetcdf.la', netcdff_prefix + '/lib/libnetcdf.la') ln('-sf', libz_prefix + '/lib', libz_prefix + '/lib64') if 'LDFLAGS' in env and env['LDFLAGS']: env['LDFLAGS'] += ' ' + '-lquadmath' else: env['LDFLAGS'] = '-lquadmath' with working_dir('FERRET', create=False): os.environ['LD_X11'] = '-L/usr/lib/X11 -lX11' os.environ['HOSTTYPE'] = 'x86_64-linux' make(parallel=False) make("install")
wscullin/spack
var/spack/repos/builtin/packages/ferret/package.py
Python
lgpl-2.1
4,430
[ "NetCDF" ]
250923c45c52a41da6d87ca7f3649144fe8884194aa3ec9c3c37644cedc002a7
import logging import os import shutil import tempfile import unittest from Bio import SeqIO from phylotyper.config import PhylotyperOptions from phylotyper.run import build_pipeline, check_gene_names from phylotyper.subtypes_index import SubtypeConfig from phylotyper.tree.seq import SeqDict from phylotyper.tree.seqaligner import SeqAligner class NewTests(unittest.TestCase): def setUp(self): # Create temporary directory sandbox = os.path.abspath(os.path.join(os.path.dirname(__file__),'sandbox')) self.test_dir = os.path.abspath(tempfile.mkdtemp(dir=sandbox)) # Create temporary yaml file for testing self.yamlfile = os.path.join(self.test_dir,'test_index.yaml') output = '# Phylotyper filepaths and options for pre-built subtyping schemes\n\nroot_dir: {}\n\nsubtypes: {{}}\n'.format( self.test_dir) with open(self.yamlfile, 'w') as w: w.write(output) # Inputs self.data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'data')) def tearDown(self): # Remove previous directories created shutil.rmtree(self.test_dir) def setUpPhylotyper(self, aa=False): # Initialize phylotyper arguments for new builds # Test inputs suffix = 'a' if aa else 'n' inpu = os.path.join(self.data_dir, 'stx2.ff'+suffix) subt = os.path.join(self.data_dir, 'stx2_subtypes.csv') scheme = 'test_gene' config_file = None if os.environ.get('PHYLOTYPER_CONFIG'): config_file = os.environ.get('PHYLOTYPER_CONFIG') # Parse .ini config file config = PhylotyperOptions(config_file) # Load subtype options stConfig = SubtypeConfig(self.yamlfile) # Check input file exists if not os.path.isfile(inpu): msg = 'Invalid/missing input file argument.' raise Exception(msg) # Check subtype file exists if not os.path.isfile(subt): msg = 'Invalid/missing subtype file argument.' raise Exception(msg) # Create subtype directory & file names subtype_options = stConfig.create_subtype(scheme, 1, aa) # Save additional build options subtype_options['input'] = [os.path.abspath(inpu)] subtype_options['subtype_orig'] = os.path.abspath(subt) subtype_options['output_directory'] = self.test_dir subtype_options['nloci'] = 1 subtype_options['fast'] = False self.configObj = config self.subtype_options = subtype_options self.subtypeOptionsObj = stConfig self.scheme = scheme def test_SeqDict_oneloci(self): self.setUpPhylotyper(aa=False) tmpfile = os.path.join(self.test_dir, 'tmp.fasta') fasta_file = os.path.join(self.data_dir, 'test_stx2.ffn') presd = SeqDict() presd.build(self.subtype_options['input'], self.subtype_options['subtype_orig']) # Output unique set presd.write(tmpfile, self.subtype_options['subtype']) # Save lookup object presd.store(self.subtype_options['lookup']) # Load output postsd = SeqDict() postsd.load(self.subtype_options['lookup']) # Test against identical/non-identcal sequence fasta_sequences = SeqIO.parse(open(fasta_file, 'r'),'fasta') results = [] expected = [True, False] for fasta in fasta_sequences: rs = True if postsd.find(str(fasta.seq)) else False results.append(rs) self.assertEqual(results, expected) def testNewAminoAcid(self): self.setUpPhylotyper(aa=True) # Set up subtype files build_pipeline(self.subtype_options, self.configObj) # Save setup self.subtypeOptionsObj.save() # Check output files filepaths = self.subtypeOptionsObj.get_subtype_config(self.scheme) fasta = SeqIO.index(filepaths['alignment'][0], 'fasta') with open(filepaths['subtype']) as f: for i, l in enumerate(f): pass sd = SeqDict() sd.load(filepaths['lookup']) n = 91 self.assertTrue(all([len(fasta) == n, i+1 == n, len(sd.seqs) == n])) def testNewDNA(self): self.setUpPhylotyper(aa=False) # Set up subtype files build_pipeline(self.subtype_options, self.configObj) # Save setup self.subtypeOptionsObj.save() # Check output files filepaths = self.subtypeOptionsObj.get_subtype_config(self.scheme) fasta = SeqIO.index(filepaths['alignment'][0], 'fasta') with open(filepaths['subtype']) as f: for i, l in enumerate(f): pass sd = SeqDict() sd.load(filepaths['lookup']) n = 120 self.assertTrue(all([len(fasta) == n, i+1 == n, len(sd.seqs) == n])) class NewTestsMultiLoci(unittest.TestCase): def setUp(self): # Create temporary directory sandbox = os.path.abspath(os.path.join(os.path.dirname(__file__),'sandbox')) self.test_dir = os.path.abspath(tempfile.mkdtemp(dir=sandbox)) # Create temporary yaml file for testing self.yamlfile = os.path.join(self.test_dir,'test_index.yaml') output = '# Phylotyper filepaths and options for pre-built subtyping schemes\n\nroot_dir: {}\n\nsubtypes: {{}}\n'.format( self.test_dir) with open(self.yamlfile, 'w') as w: w.write(output) # Inputs self.data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'data')) def tearDown(self): # Remove previous directories created shutil.rmtree(self.test_dir) def setUpPhylotyper(self, aa=False): # Initialize phylotyper arguments for new builds # Test inputs suffix = 'a' if aa else 'n' inpu = [ os.path.join(self.data_dir, 'stx2a.ff'+suffix), os.path.join(self.data_dir, 'stx2b.ff'+suffix) ] subt = os.path.join(self.data_dir, 'stx2_subtypes.csv') scheme = 'test_gene' config_file = None if os.environ.get('PHYLOTYPER_CONFIG'): config_file = os.environ.get('PHYLOTYPER_CONFIG') # Parse .ini config file config = PhylotyperOptions(config_file) # Load subtype options stConfig = SubtypeConfig(self.yamlfile) # Check input file exists if not os.path.isfile(inpu[1]): msg = 'Invalid/missing input file argument.' raise Exception(msg) # Check subtype file exists if not os.path.isfile(subt): msg = 'Invalid/missing subtype file argument.' raise Exception(msg) # Create subtype directory & file names subtype_options = stConfig.create_subtype(scheme, 2, aa) # Save additional build options subtype_options['input'] = [ os.path.abspath(i) for i in inpu ] subtype_options['subtype_orig'] = os.path.abspath(subt) subtype_options['output_directory'] = self.test_dir subtype_options['nloci'] = 2 subtype_options['fast'] = False self.configObj = config self.subtype_options = subtype_options self.subtypeOptionsObj = stConfig self.scheme = scheme def test_SeqDict_twoloci(self): self.setUpPhylotyper(aa=False) tmpfile = [ os.path.join(self.test_dir, 'tmp1.fasta'), os.path.join(self.test_dir, 'tmp2.fasta') ] fasta_file = os.path.join(self.data_dir, 'test_stx2.ffn') presd = SeqDict(2) presd.build(self.subtype_options['input'], self.subtype_options['subtype_orig']) # Output unique set presd.write(tmpfile, self.subtype_options['subtype']) # Save lookup object presd.store(self.subtype_options['lookup']) # Load output postsd = SeqDict(2) postsd.load(self.subtype_options['lookup']) # Test against identical/non-identcal sequence fasta_sequences = SeqIO.parse(open(fasta_file, 'r'),'fasta') results = [] expected = [True, False] for fasta in fasta_sequences: rs = True if postsd.find(str(fasta.seq)) else False results.append(rs) self.assertEqual(results, expected) def test_malign(self): self.setUpPhylotyper(aa=False) tmpfiles = [ os.path.join(self.test_dir, 'tmp1.fasta'), os.path.join(self.test_dir, 'tmp2.fasta') ] tmpfile = os.path.join(self.test_dir, 'tmp_saln.fasta') aln = SeqAligner(self.configObj) aln.malign(self.subtype_options['input'], tmpfiles, tmpfile) lengths = [] tmpfiles.append(tmpfile) for f in tmpfiles: seqs = SeqIO.parse(open(f, 'r'),'fasta') lengths.append(len(str(seqs.next().seq))) self.assertEqual(lengths[0]+lengths[1], lengths[2]) ## TODO Add test for new multi amino acid/dna class SubtypeIndexTests(unittest.TestCase): def setUp(self): # Create temporary directory sandbox = os.path.abspath(os.path.join(os.path.dirname(__file__),'sandbox')) self.root_dir = os.path.abspath(tempfile.mkdtemp(dir=sandbox)) # Create temporary yaml file for testing self.yamlfile = os.path.join(self.root_dir,'test_index.yaml') output = '# Phylotyper filepaths and options for pre-built subtyping schemes\n\nroot_dir: {}\n\nsubtypes: {{}}\n'.format( self.root_dir) with open(self.yamlfile, 'w') as w: w.write(output) def tearDown(self): # Remove previous directories created shutil.rmtree(self.root_dir) def testCreate1(self): # Test creation of options for new subtype scheme sc = SubtypeConfig(self.yamlfile) options = sc.create_subtype('test_gene',1,False) keys = ['rate_matrix','search_database', 'alignment','subtype','lookup','seq'] self.assertTrue(all(k in options for k in keys)) def testCreate2(self): def touch(path): with open(path, 'a'): os.utime(path, None) # Test creation of directory for new subtype scheme scheme = 'test_gene' pre = SubtypeConfig(self.yamlfile) pre_options = pre.create_subtype(scheme,1,False) pre.save() # Create files paths = ['rate_matrix','subtype','lookup'] for p in paths: touch(os.path.join(self.root_dir, pre_options[p])) # Multiple alignment files for f in pre_options['alignment']: touch(os.path.join(self.root_dir, f)) # Blast files touch(os.path.join(self.root_dir, pre_options['search_database']+'.nsq')) post = SubtypeConfig(self.yamlfile) post_options = post.get_subtype_config(scheme) self.assertEqual(pre_options, post_options) class PipelineTests(unittest.TestCase): def setUp(self): # Create temporary directory sandbox = os.path.abspath(os.path.join(os.path.dirname(__file__),'sandbox')) self.root_dir = os.path.abspath(tempfile.mkdtemp(dir=sandbox)) # Set up logger logging.basicConfig(level=logging.DEBUG) def tearDown(self): # Remove previous directories created shutil.rmtree(self.root_dir) def testCheckNames1(self): # Write input files for check options = { 'subtype_orig': os.path.join(self.root_dir, 'test_subtype.csv'), 'input': [os.path.join(self.root_dir, 'test_input1.fasta'), os.path.join(self.root_dir, 'test_input2.fasta')] } with open(options['subtype_orig'], 'w') as outfh: outfh.write('genome1\tsubtype1\n') outfh.write('genome2\tsubtype1') with open(options['input'][0], 'w') as outfh: outfh.write('>lcl|genome1|allele1\nACGT\n'); outfh.write('>lcl|genome1|allele2\nACGT\n'); outfh.write('>genome2\nACGT\n'); with open(options['input'][1], 'w') as outfh: outfh.write('>genome1|allele1\nACGT\n'); outfh.write('>genome2\nACGT\n'); self.assertTrue(check_gene_names(options)) def testCheckNames2(self): # Write input files for check options = { 'subtype_orig': os.path.join(self.root_dir, 'test_subtype.csv'), 'input': [os.path.join(self.root_dir, 'test_input1.fasta'), os.path.join(self.root_dir, 'test_input2.fasta')] } with open(options['subtype_orig'], 'w') as outfh: outfh.write('genome1\tsubtype1\n') with open(options['input'][0], 'w') as outfh: outfh.write('>lcl|genome1|allele1\nACGT\n'); outfh.write('>lcl|genome1|allele2\nACGT\n'); outfh.write('>genome2\nACGT\n'); with open(options['input'][1], 'w') as outfh: outfh.write('>genome1|allele1\nACGT\n'); outfh.write('>genome2\nACGT\n'); with self.assertRaises(Exception) as context: check_gene_names(options) errmsg = 'missing genome {} in subtype file'.format('genome2') self.assertTrue(errmsg in str(context.exception)) def testCheckNames3(self): # Write input files for check options = { 'subtype_orig': os.path.join(self.root_dir, 'test_subtype.csv'), 'input': [os.path.join(self.root_dir, 'test_input1.fasta'), os.path.join(self.root_dir, 'test_input2.fasta')] } with open(options['subtype_orig'], 'w') as outfh: outfh.write('genome1\tsubtype1\n') outfh.write('genome2\tsubtype2\n') outfh.write('genome3\tsubtype2\n') with open(options['input'][0], 'w') as outfh: outfh.write('>lcl|genome1|allele1\nACGT\n'); outfh.write('>lcl|genome1|allele2\nACGT\n'); outfh.write('>genome2\nACGT\n'); outfh.write('>genome3|allele\nAAA\n'); with open(options['input'][1], 'w') as outfh: outfh.write('>genome1|allele1\nACGT\n'); outfh.write('>genome2\nACGT\n'); with self.assertRaises(Exception) as context: check_gene_names(options) errmsg = 'missing genome entry {}'.format('genome3') self.assertTrue(errmsg in str(context.exception)) def testCheckNames4(self): # Write input files for check options = { 'subtype_orig': os.path.join(self.root_dir, 'test_subtype.csv'), 'input': [os.path.join(self.root_dir, 'test_input1.fasta'), os.path.join(self.root_dir, 'test_input2.fasta')] } with open(options['subtype_orig'], 'w') as outfh: outfh.write('genome1\tsubtype1\n') outfh.write('genome2\tsubtype2\n') outfh.write('genome3\tsubtype2\n') with open(options['input'][0], 'w') as outfh: outfh.write('>lcl|genome1|allele1\nACGT\n'); outfh.write('>lcl|genome1|allele2\nACGT\n'); outfh.write('>genome2\nACGT\n'); outfh.write('>genome2\nAAA\n'); with open(options['input'][1], 'w') as outfh: outfh.write('>genome1|allele1\nACGT\n'); outfh.write('>genome2\nACGT\n'); with self.assertRaises(Exception) as context: check_gene_names(options) errmsg = 'is not unique' self.assertTrue(errmsg in str(context.exception)) def main(): unittest.main() if __name__ == '__main__': main()
superphy/insilico-subtyping
phylotyper/test/test_new.py
Python
apache-2.0
15,768
[ "BLAST" ]
931c87385d09dfead16002e834a63daaba4e940212eedf6ea6b660192bde0798
# # Copyright (c) 2017 nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB Inc. # # You may not use this software except in compliance with the License. # You may obtain a copy of the License at: http://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. # # When you publish or redistribute any data created with ScanCode or any ScanCode # derivative work, you must accompany this data with the following acknowledgment: # # Generated with ScanCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. No content created from # ScanCode should be considered or used as legal advice. Consult an Attorney # for any legal advice. # ScanCode is a free software code scanning tool from nexB Inc. and others. # Visit https://github.com/nexB/scancode-toolkit/ for support and download. from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals from collections import OrderedDict import os from os.path import abspath from formattedcode.format import as_template from formattedcode.format import as_html_app from formattedcode.format import create_html_app_assets from formattedcode.format import HtmlAppAssetCopyWarning from formattedcode.format import HtmlAppAssetCopyError def write_formatted_output(scanners, files_count, version, notice, scanned_files, format, options, input, output_file, _echo): """ Save scan results to file or screen. """ if format == 'html': for template_chunk in as_template(scanned_files): try: output_file.write(template_chunk) except Exception as e: extra_context = 'ERROR: Failed to write output to HTML for: ' + repr(template_chunk) _echo(extra_context, fg='red') e.args += (extra_context,) raise e elif format == 'html-app': output_file.write(as_html_app(input, output_file)) try: create_html_app_assets(scanned_files, output_file) except HtmlAppAssetCopyWarning: _echo('\nHTML app creation skipped when printing to stdout.', fg='yellow') except HtmlAppAssetCopyError: _echo('\nFailed to create HTML app.', fg='red') elif format == 'json' or format == 'json-pp': import simplejson as json meta = OrderedDict() meta['scancode_notice'] = notice meta['scancode_version'] = version meta['scancode_options'] = options meta['files_count'] = files_count meta['files'] = scanned_files if format == 'json-pp': output_file.write(unicode(json.dumps(meta, indent=2 * ' ', iterable_as_array=True, encoding='utf-8'))) else: output_file.write(unicode(json.dumps(meta, separators=(',', ':'), iterable_as_array=True, encoding='utf-8'))) output_file.write('\n') elif format in ('spdx-tv', 'spdx-rdf'): from spdx.checksum import Algorithm from spdx.creationinfo import Tool from spdx.document import Document, License from spdx.file import File from spdx.package import Package from spdx.utils import NoAssert from spdx.utils import SPDXNone from spdx.version import Version input = abspath(input) if os.path.isdir(input): input_path = input else: input_path = os.path.dirname(input) doc = Document(Version(2, 1), License.from_identifier('CC0-1.0')) doc.creation_info.add_creator(Tool('ScanCode ' + version)) doc.creation_info.set_created_now() doc.package = Package(os.path.basename(input_path), NoAssert()) # Use a set of unique copyrights for the package. doc.package.cr_text = set() all_files_have_no_license = True all_files_have_no_copyright = True for file_data in scanned_files: # Construct the absolute path in case we need to access the file # to calculate its SHA1. file_entry = File(os.path.join(input_path, file_data.get('path'))) file_sha1 = file_data.get('sha1') if not file_sha1: if os.path.isfile(file_entry.name): # Calculate the SHA1 in case it is missing, e.g. for empty files. file_sha1 = file_entry.calc_chksum() else: # Skip directories. continue # Restore the relative file name as that is what we want in # SPDX output (with explicit leading './'). file_entry.name = './' + file_data.get('path') file_entry.chk_sum = Algorithm('SHA1', file_sha1) file_licenses = file_data.get('licenses') if file_licenses: all_files_have_no_license = False for file_license in file_licenses: spdx_id = file_license.get('spdx_license_key') if spdx_id: spdx_license = License.from_identifier(spdx_id) else: license_key = 'LicenseRef-' + file_license.get('key') spdx_license = License(file_license.get('short_name'), license_key) # Add licenses in the order they appear in the file. Maintaining the order # might be useful for provenance purposes. file_entry.add_lics(spdx_license) doc.package.add_lics_from_file(spdx_license) else: if file_licenses == None: all_files_have_no_license = False spdx_license = NoAssert() else: spdx_license = SPDXNone() file_entry.add_lics(spdx_license) file_entry.conc_lics = NoAssert() file_copyrights = file_data.get('copyrights') if file_copyrights: all_files_have_no_copyright = False file_entry.copyright = [] for file_copyright in file_copyrights: file_entry.copyright.extend(file_copyright.get('statements')) doc.package.cr_text.update(file_entry.copyright) # Create a text of copyright statements in the order they appear in the file. # Maintaining the order might be useful for provenance purposes. file_entry.copyright = '\n'.join(file_entry.copyright) + '\n' else: if file_copyrights == None: all_files_have_no_copyright = False spdx_copyright = NoAssert() else: spdx_copyright = SPDXNone() file_entry.copyright = spdx_copyright doc.package.add_file(file_entry) if len(doc.package.files) == 0: if format == 'spdx-tv': output_file.write("# No results for package '{}'.\n".format(doc.package.name)) else: output_file.write("<!-- No results for package '{}'. -->\n".format(doc.package.name)) return # Remove duplicate licenses from the list for the package. unique_licenses = set(doc.package.licenses_from_files) if len(doc.package.licenses_from_files) == 0: if all_files_have_no_license: doc.package.licenses_from_files = [SPDXNone()] else: doc.package.licenses_from_files = [NoAssert()] else: # List license identifiers alphabetically for the package. doc.package.licenses_from_files = sorted(unique_licenses, key=lambda x: x.identifier) if len(doc.package.cr_text) == 0: if all_files_have_no_copyright: doc.package.cr_text = SPDXNone() else: doc.package.cr_text = NoAssert() else: # Create a text of alphabetically sorted copyright statements for the package. doc.package.cr_text = '\n'.join(sorted(doc.package.cr_text)) + '\n' doc.package.verif_code = doc.package.calc_verif_code() doc.package.license_declared = NoAssert() doc.package.conc_lics = NoAssert() # As the spdx-tools package can only write the document to a "str" file but ScanCode provides a "unicode" file, # write to a "str" buffer first and then manually write the value to a "unicode" file. from StringIO import StringIO str_buffer = StringIO() if format == 'spdx-tv': from spdx.writers.tagvalue import write_document write_document(doc, str_buffer) else: from spdx.writers.rdf import write_document write_document(doc, str_buffer) output_file.write(str_buffer.getvalue()) else: raise Exception('Unknown format')
yasharmaster/scancode-toolkit
src/formattedcode/writers.py
Python
apache-2.0
9,472
[ "VisIt" ]
23cb831b0c8baee93c88dae7b7e4e3fe1c4f5e4a49c34b0205841a145655e364
"""Rewrite assertion AST to produce nice error messages""" from __future__ import absolute_import, division, print_function import ast import errno import itertools import imp import marshal import os import re import six import string import struct import sys import types import atomicwrites import py from _pytest.assertion import util from _pytest.compat import PurePath, spec_from_file_location from _pytest.paths import fnmatch_ex # pytest caches rewritten pycs in __pycache__. if hasattr(imp, "get_tag"): PYTEST_TAG = imp.get_tag() + "-PYTEST" else: if hasattr(sys, "pypy_version_info"): impl = "pypy" elif sys.platform == "java": impl = "jython" else: impl = "cpython" ver = sys.version_info PYTEST_TAG = "%s-%s%s-PYTEST" % (impl, ver[0], ver[1]) del ver, impl PYC_EXT = ".py" + (__debug__ and "c" or "o") PYC_TAIL = "." + PYTEST_TAG + PYC_EXT ASCII_IS_DEFAULT_ENCODING = sys.version_info[0] < 3 if sys.version_info >= (3, 5): ast_Call = ast.Call else: def ast_Call(a, b, c): return ast.Call(a, b, c, None, None) class AssertionRewritingHook(object): """PEP302 Import hook which rewrites asserts.""" def __init__(self, config): self.config = config self.fnpats = config.getini("python_files") self.session = None self.modules = {} self._rewritten_names = set() self._register_with_pkg_resources() self._must_rewrite = set() # flag to guard against trying to rewrite a pyc file while we are already writing another pyc file, # which might result in infinite recursion (#3506) self._writing_pyc = False self._basenames_to_check_rewrite = {"conftest"} self._marked_for_rewrite_cache = {} self._session_paths_checked = False def set_session(self, session): self.session = session self._session_paths_checked = False def _imp_find_module(self, name, path=None): """Indirection so we can mock calls to find_module originated from the hook during testing""" return imp.find_module(name, path) def find_module(self, name, path=None): if self._writing_pyc: return None state = self.config._assertstate if self._early_rewrite_bailout(name, state): return None state.trace("find_module called for: %s" % name) names = name.rsplit(".", 1) lastname = names[-1] pth = None if path is not None: # Starting with Python 3.3, path is a _NamespacePath(), which # causes problems if not converted to list. path = list(path) if len(path) == 1: pth = path[0] if pth is None: try: fd, fn, desc = self._imp_find_module(lastname, path) except ImportError: return None if fd is not None: fd.close() tp = desc[2] if tp == imp.PY_COMPILED: if hasattr(imp, "source_from_cache"): try: fn = imp.source_from_cache(fn) except ValueError: # Python 3 doesn't like orphaned but still-importable # .pyc files. fn = fn[:-1] else: fn = fn[:-1] elif tp != imp.PY_SOURCE: # Don't know what this is. return None else: fn = os.path.join(pth, name.rpartition(".")[2] + ".py") fn_pypath = py.path.local(fn) if not self._should_rewrite(name, fn_pypath, state): return None self._rewritten_names.add(name) # The requested module looks like a test file, so rewrite it. This is # the most magical part of the process: load the source, rewrite the # asserts, and load the rewritten source. We also cache the rewritten # module code in a special pyc. We must be aware of the possibility of # concurrent pytest processes rewriting and loading pycs. To avoid # tricky race conditions, we maintain the following invariant: The # cached pyc is always a complete, valid pyc. Operations on it must be # atomic. POSIX's atomic rename comes in handy. write = not sys.dont_write_bytecode cache_dir = os.path.join(fn_pypath.dirname, "__pycache__") if write: try: os.mkdir(cache_dir) except OSError: e = sys.exc_info()[1].errno if e == errno.EEXIST: # Either the __pycache__ directory already exists (the # common case) or it's blocked by a non-dir node. In the # latter case, we'll ignore it in _write_pyc. pass elif e in [errno.ENOENT, errno.ENOTDIR]: # One of the path components was not a directory, likely # because we're in a zip file. write = False elif e in [errno.EACCES, errno.EROFS, errno.EPERM]: state.trace("read only directory: %r" % fn_pypath.dirname) write = False else: raise cache_name = fn_pypath.basename[:-3] + PYC_TAIL pyc = os.path.join(cache_dir, cache_name) # Notice that even if we're in a read-only directory, I'm going # to check for a cached pyc. This may not be optimal... co = _read_pyc(fn_pypath, pyc, state.trace) if co is None: state.trace("rewriting %r" % (fn,)) source_stat, co = _rewrite_test(self.config, fn_pypath) if co is None: # Probably a SyntaxError in the test. return None if write: self._writing_pyc = True try: _write_pyc(state, co, source_stat, pyc) finally: self._writing_pyc = False else: state.trace("found cached rewritten pyc for %r" % (fn,)) self.modules[name] = co, pyc return self def _early_rewrite_bailout(self, name, state): """ This is a fast way to get out of rewriting modules. Profiling has shown that the call to imp.find_module (inside of the find_module from this class) is a major slowdown, so, this method tries to filter what we're sure won't be rewritten before getting to it. """ if self.session is not None and not self._session_paths_checked: self._session_paths_checked = True for path in self.session._initialpaths: # Make something as c:/projects/my_project/path.py -> # ['c:', 'projects', 'my_project', 'path.py'] parts = str(path).split(os.path.sep) # add 'path' to basenames to be checked. self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0]) # Note: conftest already by default in _basenames_to_check_rewrite. parts = name.split(".") if parts[-1] in self._basenames_to_check_rewrite: return False # For matching the name it must be as if it was a filename. path = PurePath(os.path.sep.join(parts) + ".py") for pat in self.fnpats: # if the pattern contains subdirectories ("tests/**.py" for example) we can't bail out based # on the name alone because we need to match against the full path if os.path.dirname(pat): return False if fnmatch_ex(pat, path): return False if self._is_marked_for_rewrite(name, state): return False state.trace("early skip of rewriting module: %s" % (name,)) return True def _should_rewrite(self, name, fn_pypath, state): # always rewrite conftest files fn = str(fn_pypath) if fn_pypath.basename == "conftest.py": state.trace("rewriting conftest file: %r" % (fn,)) return True if self.session is not None: if self.session.isinitpath(fn): state.trace("matched test file (was specified on cmdline): %r" % (fn,)) return True # modules not passed explicitly on the command line are only # rewritten if they match the naming convention for test files for pat in self.fnpats: if fn_pypath.fnmatch(pat): state.trace("matched test file %r" % (fn,)) return True return self._is_marked_for_rewrite(name, state) def _is_marked_for_rewrite(self, name, state): try: return self._marked_for_rewrite_cache[name] except KeyError: for marked in self._must_rewrite: if name == marked or name.startswith(marked + "."): state.trace("matched marked file %r (from %r)" % (name, marked)) self._marked_for_rewrite_cache[name] = True return True self._marked_for_rewrite_cache[name] = False return False def mark_rewrite(self, *names): """Mark import names as needing to be rewritten. The named module or package as well as any nested modules will be rewritten on import. """ already_imported = ( set(names).intersection(sys.modules).difference(self._rewritten_names) ) for name in already_imported: if not AssertionRewriter.is_rewrite_disabled( sys.modules[name].__doc__ or "" ): self._warn_already_imported(name) self._must_rewrite.update(names) self._marked_for_rewrite_cache.clear() def _warn_already_imported(self, name): from _pytest.warning_types import PytestWarning from _pytest.warnings import _issue_config_warning _issue_config_warning( PytestWarning("Module already imported so cannot be rewritten: %s" % name), self.config, ) def load_module(self, name): co, pyc = self.modules.pop(name) if name in sys.modules: # If there is an existing module object named 'fullname' in # sys.modules, the loader must use that existing module. (Otherwise, # the reload() builtin will not work correctly.) mod = sys.modules[name] else: # I wish I could just call imp.load_compiled here, but __file__ has to # be set properly. In Python 3.2+, this all would be handled correctly # by load_compiled. mod = sys.modules[name] = imp.new_module(name) try: mod.__file__ = co.co_filename # Normally, this attribute is 3.2+. mod.__cached__ = pyc mod.__loader__ = self # Normally, this attribute is 3.4+ mod.__spec__ = spec_from_file_location(name, co.co_filename, loader=self) six.exec_(co, mod.__dict__) except: # noqa if name in sys.modules: del sys.modules[name] raise return sys.modules[name] def is_package(self, name): try: fd, fn, desc = self._imp_find_module(name) except ImportError: return False if fd is not None: fd.close() tp = desc[2] return tp == imp.PKG_DIRECTORY @classmethod def _register_with_pkg_resources(cls): """ Ensure package resources can be loaded from this loader. May be called multiple times, as the operation is idempotent. """ try: import pkg_resources # access an attribute in case a deferred importer is present pkg_resources.__name__ except ImportError: return # Since pytest tests are always located in the file system, the # DefaultProvider is appropriate. pkg_resources.register_loader_type(cls, pkg_resources.DefaultProvider) def get_data(self, pathname): """Optional PEP302 get_data API. """ with open(pathname, "rb") as f: return f.read() def _write_pyc(state, co, source_stat, pyc): # Technically, we don't have to have the same pyc format as # (C)Python, since these "pycs" should never be seen by builtin # import. However, there's little reason deviate, and I hope # sometime to be able to use imp.load_compiled to load them. (See # the comment in load_module above.) try: with atomicwrites.atomic_write(pyc, mode="wb", overwrite=True) as fp: fp.write(imp.get_magic()) mtime = int(source_stat.mtime) size = source_stat.size & 0xFFFFFFFF fp.write(struct.pack("<ll", mtime, size)) fp.write(marshal.dumps(co)) except EnvironmentError as e: state.trace("error writing pyc file at %s: errno=%s" % (pyc, e.errno)) # we ignore any failure to write the cache file # there are many reasons, permission-denied, __pycache__ being a # file etc. return False return True RN = "\r\n".encode("utf-8") N = "\n".encode("utf-8") cookie_re = re.compile(r"^[ \t\f]*#.*coding[:=][ \t]*[-\w.]+") BOM_UTF8 = "\xef\xbb\xbf" def _rewrite_test(config, fn): """Try to read and rewrite *fn* and return the code object.""" state = config._assertstate try: stat = fn.stat() source = fn.read("rb") except EnvironmentError: return None, None if ASCII_IS_DEFAULT_ENCODING: # ASCII is the default encoding in Python 2. Without a coding # declaration, Python 2 will complain about any bytes in the file # outside the ASCII range. Sadly, this behavior does not extend to # compile() or ast.parse(), which prefer to interpret the bytes as # latin-1. (At least they properly handle explicit coding cookies.) To # preserve this error behavior, we could force ast.parse() to use ASCII # as the encoding by inserting a coding cookie. Unfortunately, that # messes up line numbers. Thus, we have to check ourselves if anything # is outside the ASCII range in the case no encoding is explicitly # declared. For more context, see issue #269. Yay for Python 3 which # gets this right. end1 = source.find("\n") end2 = source.find("\n", end1 + 1) if ( not source.startswith(BOM_UTF8) and cookie_re.match(source[0:end1]) is None and cookie_re.match(source[end1 + 1 : end2]) is None ): if hasattr(state, "_indecode"): # encodings imported us again, so don't rewrite. return None, None state._indecode = True try: try: source.decode("ascii") except UnicodeDecodeError: # Let it fail in real import. return None, None finally: del state._indecode try: tree = ast.parse(source) except SyntaxError: # Let this pop up again in the real import. state.trace("failed to parse: %r" % (fn,)) return None, None rewrite_asserts(tree, fn, config) try: co = compile(tree, fn.strpath, "exec", dont_inherit=True) except SyntaxError: # It's possible that this error is from some bug in the # assertion rewriting, but I don't know of a fast way to tell. state.trace("failed to compile: %r" % (fn,)) return None, None return stat, co def _read_pyc(source, pyc, trace=lambda x: None): """Possibly read a pytest pyc containing rewritten code. Return rewritten code if successful or None if not. """ try: fp = open(pyc, "rb") except IOError: return None with fp: try: mtime = int(source.mtime()) size = source.size() data = fp.read(12) except EnvironmentError as e: trace("_read_pyc(%s): EnvironmentError %s" % (source, e)) return None # Check for invalid or out of date pyc file. if ( len(data) != 12 or data[:4] != imp.get_magic() or struct.unpack("<ll", data[4:]) != (mtime, size) ): trace("_read_pyc(%s): invalid or out of date pyc" % source) return None try: co = marshal.load(fp) except Exception as e: trace("_read_pyc(%s): marshal.load error %s" % (source, e)) return None if not isinstance(co, types.CodeType): trace("_read_pyc(%s): not a code object" % source) return None return co def rewrite_asserts(mod, module_path=None, config=None): """Rewrite the assert statements in mod.""" AssertionRewriter(module_path, config).run(mod) def _saferepr(obj): """Get a safe repr of an object for assertion error messages. The assertion formatting (util.format_explanation()) requires newlines to be escaped since they are a special character for it. Normally assertion.util.format_explanation() does this but for a custom repr it is possible to contain one of the special escape sequences, especially '\n{' and '\n}' are likely to be present in JSON reprs. """ r = py.io.saferepr(obj) # only occurs in python2.x, repr must return text in python3+ if isinstance(r, bytes): # Represent unprintable bytes as `\x##` r = u"".join( u"\\x{:x}".format(ord(c)) if c not in string.printable else c.decode() for c in r ) return r.replace(u"\n", u"\\n") from _pytest.assertion.util import format_explanation as _format_explanation # noqa def _format_assertmsg(obj): """Format the custom assertion message given. For strings this simply replaces newlines with '\n~' so that util.format_explanation() will preserve them instead of escaping newlines. For other objects py.io.saferepr() is used first. """ # reprlib appears to have a bug which means that if a string # contains a newline it gets escaped, however if an object has a # .__repr__() which contains newlines it does not get escaped. # However in either case we want to preserve the newline. replaces = [(u"\n", u"\n~"), (u"%", u"%%")] if not isinstance(obj, six.string_types): obj = py.io.saferepr(obj) replaces.append((u"\\n", u"\n~")) if isinstance(obj, bytes): replaces = [(r1.encode(), r2.encode()) for r1, r2 in replaces] for r1, r2 in replaces: obj = obj.replace(r1, r2) return obj def _should_repr_global_name(obj): return not hasattr(obj, "__name__") and not callable(obj) def _format_boolop(explanations, is_or): explanation = "(" + (is_or and " or " or " and ").join(explanations) + ")" if isinstance(explanation, six.text_type): return explanation.replace(u"%", u"%%") else: return explanation.replace(b"%", b"%%") def _call_reprcompare(ops, results, expls, each_obj): for i, res, expl in zip(range(len(ops)), results, expls): try: done = not res except Exception: done = True if done: break if util._reprcompare is not None: custom = util._reprcompare(ops[i], each_obj[i], each_obj[i + 1]) if custom is not None: return custom return expl unary_map = {ast.Not: "not %s", ast.Invert: "~%s", ast.USub: "-%s", ast.UAdd: "+%s"} binop_map = { ast.BitOr: "|", ast.BitXor: "^", ast.BitAnd: "&", ast.LShift: "<<", ast.RShift: ">>", ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.FloorDiv: "//", ast.Mod: "%%", # escaped for string formatting ast.Eq: "==", ast.NotEq: "!=", ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">=", ast.Pow: "**", ast.Is: "is", ast.IsNot: "is not", ast.In: "in", ast.NotIn: "not in", } # Python 3.5+ compatibility try: binop_map[ast.MatMult] = "@" except AttributeError: pass # Python 3.4+ compatibility if hasattr(ast, "NameConstant"): _NameConstant = ast.NameConstant else: def _NameConstant(c): return ast.Name(str(c), ast.Load()) def set_location(node, lineno, col_offset): """Set node location information recursively.""" def _fix(node, lineno, col_offset): if "lineno" in node._attributes: node.lineno = lineno if "col_offset" in node._attributes: node.col_offset = col_offset for child in ast.iter_child_nodes(node): _fix(child, lineno, col_offset) _fix(node, lineno, col_offset) return node class AssertionRewriter(ast.NodeVisitor): """Assertion rewriting implementation. The main entrypoint is to call .run() with an ast.Module instance, this will then find all the assert statements and rewrite them to provide intermediate values and a detailed assertion error. See http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html for an overview of how this works. The entry point here is .run() which will iterate over all the statements in an ast.Module and for each ast.Assert statement it finds call .visit() with it. Then .visit_Assert() takes over and is responsible for creating new ast statements to replace the original assert statement: it rewrites the test of an assertion to provide intermediate values and replace it with an if statement which raises an assertion error with a detailed explanation in case the expression is false. For this .visit_Assert() uses the visitor pattern to visit all the AST nodes of the ast.Assert.test field, each visit call returning an AST node and the corresponding explanation string. During this state is kept in several instance attributes: :statements: All the AST statements which will replace the assert statement. :variables: This is populated by .variable() with each variable used by the statements so that they can all be set to None at the end of the statements. :variable_counter: Counter to create new unique variables needed by statements. Variables are created using .variable() and have the form of "@py_assert0". :on_failure: The AST statements which will be executed if the assertion test fails. This is the code which will construct the failure message and raises the AssertionError. :explanation_specifiers: A dict filled by .explanation_param() with %-formatting placeholders and their corresponding expressions to use in the building of an assertion message. This is used by .pop_format_context() to build a message. :stack: A stack of the explanation_specifiers dicts maintained by .push_format_context() and .pop_format_context() which allows to build another %-formatted string while already building one. This state is reset on every new assert statement visited and used by the other visitors. """ def __init__(self, module_path, config): super(AssertionRewriter, self).__init__() self.module_path = module_path self.config = config def run(self, mod): """Find all assert statements in *mod* and rewrite them.""" if not mod.body: # Nothing to do. return # Insert some special imports at the top of the module but after any # docstrings and __future__ imports. aliases = [ ast.alias(py.builtin.builtins.__name__, "@py_builtins"), ast.alias("_pytest.assertion.rewrite", "@pytest_ar"), ] doc = getattr(mod, "docstring", None) expect_docstring = doc is None if doc is not None and self.is_rewrite_disabled(doc): return pos = 0 lineno = 1 for item in mod.body: if ( expect_docstring and isinstance(item, ast.Expr) and isinstance(item.value, ast.Str) ): doc = item.value.s if self.is_rewrite_disabled(doc): return expect_docstring = False elif ( not isinstance(item, ast.ImportFrom) or item.level > 0 or item.module != "__future__" ): lineno = item.lineno break pos += 1 else: lineno = item.lineno imports = [ ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases ] mod.body[pos:pos] = imports # Collect asserts. nodes = [mod] while nodes: node = nodes.pop() for name, field in ast.iter_fields(node): if isinstance(field, list): new = [] for i, child in enumerate(field): if isinstance(child, ast.Assert): # Transform assert. new.extend(self.visit(child)) else: new.append(child) if isinstance(child, ast.AST): nodes.append(child) setattr(node, name, new) elif ( isinstance(field, ast.AST) and # Don't recurse into expressions as they can't contain # asserts. not isinstance(field, ast.expr) ): nodes.append(field) @staticmethod def is_rewrite_disabled(docstring): return "PYTEST_DONT_REWRITE" in docstring def variable(self): """Get a new variable.""" # Use a character invalid in python identifiers to avoid clashing. name = "@py_assert" + str(next(self.variable_counter)) self.variables.append(name) return name def assign(self, expr): """Give *expr* a name.""" name = self.variable() self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr)) return ast.Name(name, ast.Load()) def display(self, expr): """Call py.io.saferepr on the expression.""" return self.helper("saferepr", expr) def helper(self, name, *args): """Call a helper in this module.""" py_name = ast.Name("@pytest_ar", ast.Load()) attr = ast.Attribute(py_name, "_" + name, ast.Load()) return ast_Call(attr, list(args), []) def builtin(self, name): """Return the builtin called *name*.""" builtin_name = ast.Name("@py_builtins", ast.Load()) return ast.Attribute(builtin_name, name, ast.Load()) def explanation_param(self, expr): """Return a new named %-formatting placeholder for expr. This creates a %-formatting placeholder for expr in the current formatting context, e.g. ``%(py0)s``. The placeholder and expr are placed in the current format context so that it can be used on the next call to .pop_format_context(). """ specifier = "py" + str(next(self.variable_counter)) self.explanation_specifiers[specifier] = expr return "%(" + specifier + ")s" def push_format_context(self): """Create a new formatting context. The format context is used for when an explanation wants to have a variable value formatted in the assertion message. In this case the value required can be added using .explanation_param(). Finally .pop_format_context() is used to format a string of %-formatted values as added by .explanation_param(). """ self.explanation_specifiers = {} self.stack.append(self.explanation_specifiers) def pop_format_context(self, expl_expr): """Format the %-formatted string with current format context. The expl_expr should be an ast.Str instance constructed from the %-placeholders created by .explanation_param(). This will add the required code to format said string to .on_failure and return the ast.Name instance of the formatted string. """ current = self.stack.pop() if self.stack: self.explanation_specifiers = self.stack[-1] keys = [ast.Str(key) for key in current.keys()] format_dict = ast.Dict(keys, list(current.values())) form = ast.BinOp(expl_expr, ast.Mod(), format_dict) name = "@py_format" + str(next(self.variable_counter)) self.on_failure.append(ast.Assign([ast.Name(name, ast.Store())], form)) return ast.Name(name, ast.Load()) def generic_visit(self, node): """Handle expressions we don't have custom code for.""" assert isinstance(node, ast.expr) res = self.assign(node) return res, self.explanation_param(self.display(res)) def visit_Assert(self, assert_): """Return the AST statements to replace the ast.Assert instance. This rewrites the test of an assertion to provide intermediate values and replace it with an if statement which raises an assertion error with a detailed explanation in case the expression is false. """ if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1: from _pytest.warning_types import PytestWarning import warnings warnings.warn_explicit( PytestWarning("assertion is always true, perhaps remove parentheses?"), category=None, filename=str(self.module_path), lineno=assert_.lineno, ) self.statements = [] self.variables = [] self.variable_counter = itertools.count() self.stack = [] self.on_failure = [] self.push_format_context() # Rewrite assert into a bunch of statements. top_condition, explanation = self.visit(assert_.test) # Create failure message. body = self.on_failure negation = ast.UnaryOp(ast.Not(), top_condition) self.statements.append(ast.If(negation, body, [])) if assert_.msg: assertmsg = self.helper("format_assertmsg", assert_.msg) explanation = "\n>assert " + explanation else: assertmsg = ast.Str("") explanation = "assert " + explanation template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation)) msg = self.pop_format_context(template) fmt = self.helper("format_explanation", msg) err_name = ast.Name("AssertionError", ast.Load()) exc = ast_Call(err_name, [fmt], []) if sys.version_info[0] >= 3: raise_ = ast.Raise(exc, None) else: raise_ = ast.Raise(exc, None, None) body.append(raise_) # Clear temporary variables by setting them to None. if self.variables: variables = [ast.Name(name, ast.Store()) for name in self.variables] clear = ast.Assign(variables, _NameConstant(None)) self.statements.append(clear) # Fix line numbers. for stmt in self.statements: set_location(stmt, assert_.lineno, assert_.col_offset) return self.statements def visit_Name(self, name): # Display the repr of the name if it's a local variable or # _should_repr_global_name() thinks it's acceptable. locs = ast_Call(self.builtin("locals"), [], []) inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs]) dorepr = self.helper("should_repr_global_name", name) test = ast.BoolOp(ast.Or(), [inlocs, dorepr]) expr = ast.IfExp(test, self.display(name), ast.Str(name.id)) return name, self.explanation_param(expr) def visit_BoolOp(self, boolop): res_var = self.variable() expl_list = self.assign(ast.List([], ast.Load())) app = ast.Attribute(expl_list, "append", ast.Load()) is_or = int(isinstance(boolop.op, ast.Or)) body = save = self.statements fail_save = self.on_failure levels = len(boolop.values) - 1 self.push_format_context() # Process each operand, short-circuting if needed. for i, v in enumerate(boolop.values): if i: fail_inner = [] # cond is set in a prior loop iteration below self.on_failure.append(ast.If(cond, fail_inner, [])) # noqa self.on_failure = fail_inner self.push_format_context() res, expl = self.visit(v) body.append(ast.Assign([ast.Name(res_var, ast.Store())], res)) expl_format = self.pop_format_context(ast.Str(expl)) call = ast_Call(app, [expl_format], []) self.on_failure.append(ast.Expr(call)) if i < levels: cond = res if is_or: cond = ast.UnaryOp(ast.Not(), cond) inner = [] self.statements.append(ast.If(cond, inner, [])) self.statements = body = inner self.statements = save self.on_failure = fail_save expl_template = self.helper("format_boolop", expl_list, ast.Num(is_or)) expl = self.pop_format_context(expl_template) return ast.Name(res_var, ast.Load()), self.explanation_param(expl) def visit_UnaryOp(self, unary): pattern = unary_map[unary.op.__class__] operand_res, operand_expl = self.visit(unary.operand) res = self.assign(ast.UnaryOp(unary.op, operand_res)) return res, pattern % (operand_expl,) def visit_BinOp(self, binop): symbol = binop_map[binop.op.__class__] left_expr, left_expl = self.visit(binop.left) right_expr, right_expl = self.visit(binop.right) explanation = "(%s %s %s)" % (left_expl, symbol, right_expl) res = self.assign(ast.BinOp(left_expr, binop.op, right_expr)) return res, explanation def visit_Call_35(self, call): """ visit `ast.Call` nodes on Python3.5 and after """ new_func, func_expl = self.visit(call.func) arg_expls = [] new_args = [] new_kwargs = [] for arg in call.args: res, expl = self.visit(arg) arg_expls.append(expl) new_args.append(res) for keyword in call.keywords: res, expl = self.visit(keyword.value) new_kwargs.append(ast.keyword(keyword.arg, res)) if keyword.arg: arg_expls.append(keyword.arg + "=" + expl) else: # **args have `arg` keywords with an .arg of None arg_expls.append("**" + expl) expl = "%s(%s)" % (func_expl, ", ".join(arg_expls)) new_call = ast.Call(new_func, new_args, new_kwargs) res = self.assign(new_call) res_expl = self.explanation_param(self.display(res)) outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl) return res, outer_expl def visit_Starred(self, starred): # From Python 3.5, a Starred node can appear in a function call res, expl = self.visit(starred.value) return starred, "*" + expl def visit_Call_legacy(self, call): """ visit `ast.Call nodes on 3.4 and below` """ new_func, func_expl = self.visit(call.func) arg_expls = [] new_args = [] new_kwargs = [] new_star = new_kwarg = None for arg in call.args: res, expl = self.visit(arg) new_args.append(res) arg_expls.append(expl) for keyword in call.keywords: res, expl = self.visit(keyword.value) new_kwargs.append(ast.keyword(keyword.arg, res)) arg_expls.append(keyword.arg + "=" + expl) if call.starargs: new_star, expl = self.visit(call.starargs) arg_expls.append("*" + expl) if call.kwargs: new_kwarg, expl = self.visit(call.kwargs) arg_expls.append("**" + expl) expl = "%s(%s)" % (func_expl, ", ".join(arg_expls)) new_call = ast.Call(new_func, new_args, new_kwargs, new_star, new_kwarg) res = self.assign(new_call) res_expl = self.explanation_param(self.display(res)) outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl) return res, outer_expl # ast.Call signature changed on 3.5, # conditionally change which methods is named # visit_Call depending on Python version if sys.version_info >= (3, 5): visit_Call = visit_Call_35 else: visit_Call = visit_Call_legacy def visit_Attribute(self, attr): if not isinstance(attr.ctx, ast.Load): return self.generic_visit(attr) value, value_expl = self.visit(attr.value) res = self.assign(ast.Attribute(value, attr.attr, ast.Load())) res_expl = self.explanation_param(self.display(res)) pat = "%s\n{%s = %s.%s\n}" expl = pat % (res_expl, res_expl, value_expl, attr.attr) return res, expl def visit_Compare(self, comp): self.push_format_context() left_res, left_expl = self.visit(comp.left) if isinstance(comp.left, (ast.Compare, ast.BoolOp)): left_expl = "({})".format(left_expl) res_variables = [self.variable() for i in range(len(comp.ops))] load_names = [ast.Name(v, ast.Load()) for v in res_variables] store_names = [ast.Name(v, ast.Store()) for v in res_variables] it = zip(range(len(comp.ops)), comp.ops, comp.comparators) expls = [] syms = [] results = [left_res] for i, op, next_operand in it: next_res, next_expl = self.visit(next_operand) if isinstance(next_operand, (ast.Compare, ast.BoolOp)): next_expl = "({})".format(next_expl) results.append(next_res) sym = binop_map[op.__class__] syms.append(ast.Str(sym)) expl = "%s %s %s" % (left_expl, sym, next_expl) expls.append(ast.Str(expl)) res_expr = ast.Compare(left_res, [op], [next_res]) self.statements.append(ast.Assign([store_names[i]], res_expr)) left_res, left_expl = next_res, next_expl # Use pytest.assertion.util._reprcompare if that's available. expl_call = self.helper( "call_reprcompare", ast.Tuple(syms, ast.Load()), ast.Tuple(load_names, ast.Load()), ast.Tuple(expls, ast.Load()), ast.Tuple(results, ast.Load()), ) if len(comp.ops) > 1: res = ast.BoolOp(ast.And(), load_names) else: res = load_names[0] return res, self.explanation_param(self.pop_format_context(expl_call))
davidszotten/pytest
src/_pytest/assertion/rewrite.py
Python
mit
39,382
[ "VisIt" ]
7febd236b550bd5edef6b093e121e68e3620405490db486209632806d2f46692
# ====================================================================== # Given vtu/pvtu file(s) resulting from an MVR elasticity simulation # (the solution files hence contain three scalar valued arrays named # 'u0', 'u1' and 'u2' as PointData), this vtk-based python script # warps the initial/original mesh geometry by means of the displacement # vector, and computes the Cauchy strain tensor and the von Mises stress. # # The script's output is the following: # - vtu file that contains all the data of the # original file with modified coordinates of the points and the # displacement vector as additional PointData and the strain tensor # along with the von Mises stress (w.r.t. the Lame parameters # lambda = 28466, mu = 700 for mitral valve tissue, according to # [Mansi-2012]) as additional CellData. # # How to run the script: # python calculator.py ./input/myInput.(p)vtu ./output/myOutput.vtu # # Author: Nicolai Schoch, EMCL; 2015-04-12. # ====================================================================== __author__ = 'schoch' import sys import vtk #from .msmlvtk import * # NEEDED?! def compute_vonMisesStress_for_MV(inputfilename, outputfilename): # ====================================================================== # get system arguments ------------------------------------------------- # Path to input file and name of the output file #inputfilename = sys.argv[1] #outputfilename = sys.argv[2] print " " print "==================================================================================================" print "=== Execute Python script to analyze MV geometry in order for the HiFlow3-based MVR-Simulation ===" print "==================================================================================================" print " " # ====================================================================== # Read file if inputfilename[-4] == 'p': reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(inputfilename) reader.Update() else: reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(inputfilename) reader.Update() print "Reading input files: DONE." # ====================================================================== # Compute displacement vector calc = vtk.vtkArrayCalculator() calc.SetInput(reader.GetOutput()) calc.SetAttributeModeToUsePointData() calc.AddScalarVariable('x', 'u0', 0) calc.AddScalarVariable('y', 'u1', 0) calc.AddScalarVariable('z', 'u2', 0) calc.SetFunction('x*iHat+y*jHat+z*kHat') calc.SetResultArrayName('DisplacementSolutionVector') calc.Update() # ====================================================================== # Compute strain tensor derivative = vtk.vtkCellDerivatives() derivative.SetInput(calc.GetOutput()) derivative.SetTensorModeToComputeStrain() derivative.Update() # ====================================================================== # Compute von Mises stress calc = vtk.vtkArrayCalculator() calc.SetInput(derivative.GetOutput()) calc.SetAttributeModeToUseCellData() calc.AddScalarVariable('Strain_0', 'Strain', 0) calc.AddScalarVariable('Strain_1', 'Strain', 1) calc.AddScalarVariable('Strain_2', 'Strain', 2) calc.AddScalarVariable('Strain_3', 'Strain', 3) calc.AddScalarVariable('Strain_4', 'Strain', 4) calc.AddScalarVariable('Strain_5', 'Strain', 5) calc.AddScalarVariable('Strain_6', 'Strain', 6) calc.AddScalarVariable('Strain_7', 'Strain', 7) calc.AddScalarVariable('Strain_8', 'Strain', 8) calc.SetFunction('sqrt( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))^2 + (2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8))^2 + (2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8))^2 - ( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8)) ) - ( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8)) ) - ( (2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8)) ) + 3 * ((2*700*Strain_3)^2 + (2*700*Strain_6)^2 + (2*700*Strain_7)^2) )') calc.SetResultArrayName('vonMisesStress_forMV_mu700_lambda28466') calc.Update() print "Computation of displacement vectors, Cauchy strain and vom Mises stress: DONE." # ====================================================================== # Define dummy variable; get output of calc filter dummy = calc.GetOutput() # Get point data arrays u0, u1 and u2 pointData_u0 = dummy.GetPointData().GetArray('u0') pointData_u1 = dummy.GetPointData().GetArray('u1') pointData_u2 = dummy.GetPointData().GetArray('u2') # Set scalars dummy.GetPointData().SetScalars(pointData_u0) # ====================================================================== # Warp by scalar u0 warpScalar = vtk.vtkWarpScalar() warpScalar.SetInput(dummy) warpScalar.SetNormal(1.0,0.0,0.0) warpScalar.SetScaleFactor(1.0) warpScalar.SetUseNormal(1) warpScalar.Update() # Get output and set scalars dummy = warpScalar.GetOutput() dummy.GetPointData().SetScalars(pointData_u1) # ====================================================================== # Warp by scalar u1 warpScalar = vtk.vtkWarpScalar() warpScalar.SetInput(dummy) warpScalar.SetNormal(0.0,1.0,0.0) warpScalar.SetScaleFactor(1.0) warpScalar.SetUseNormal(1) warpScalar.Update() # Get output and set scalars dummy = warpScalar.GetOutput() dummy.GetPointData().SetScalars(pointData_u2) # ====================================================================== # Warp by scalar u2 warpScalar = vtk.vtkWarpScalar() warpScalar.SetInput(dummy) warpScalar.SetNormal(0.0,0.0,1.0) warpScalar.SetScaleFactor(1.0) warpScalar.SetUseNormal(1) warpScalar.Update() # Get ouput and add point data arrays that got deleted earlier dummy = warpScalar.GetOutput() dummy.GetPointData().AddArray(pointData_u0) dummy.GetPointData().AddArray(pointData_u1) # ====================================================================== # Write output to vtu writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetDataModeToAscii() writer.SetFileName(outputfilename) writer.SetInput(dummy) writer.Write() # ====================================================================== print "Writing Extended VTU incl. von Mises Stress information: DONE." print "==============================================================" print " "
CognitionGuidedSurgery/msml
src/msml/ext/vonMisesStressComputation_mvrPostProcessingAnalytics.py
Python
gpl-3.0
6,424
[ "VTK" ]
afb050edb8f1f534c9bfa52ee1303345771ed429f6958b84f36dd1a5f5470c67
import unittest from emmail.objects.clusterer import Clusterer from emmail.tests.test_data import * # Single BLAST output file clusterer = Clusterer(blastOutputFile=test_blast_product, output_stream="stdout", output_type="short", header=False, distance=800) clusterer_verbose = Clusterer(blastOutputFile=test_blast_product, output_stream="stdout", output_type="verbose", header=True, distance=800) class testClusterer(unittest.TestCase): def test_null(self): self.assertEqual(test_null, "this is a null test") def test_is_clusterer(self): self.assertIs(type(clusterer), Clusterer) self.assertIs(type(clusterer_verbose), Clusterer) def test_repr_short(self): self.assertEqual(repr(clusterer), clusterer_repr_short) self.assertEqual(repr(clusterer_verbose), clusterer_repr_verbose) def test_run_short(self): self.assertEqual(clusterer.main(), clusterer_result_short) def test_run_verbose(self): self.assertEqual(clusterer_verbose.main(), clusterer_result_verbose) if __name__ == "__main__": unittest.main()
Andre-Tan/EmMAIL
emmail/tests/test_clusterer.py
Python
gpl-3.0
1,404
[ "BLAST" ]
22bebebca564e0d663dcf660906d4cc9460ea75d041346b53c1f374235742fc4
# -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 msto <mstone5@mgh.harvard.edu> # # Distributed under terms of the MIT license. """ Simple venn diagrams. """ import matplotlib.pyplot as plt import matplotlib.patches as patches def venn4(subsets, set_labels=('A', 'B', 'C', 'D'), # set_colors=['#8f1402', '#0485d1', '#feb308', '#8eab12'], set_colors=['#8eab12', '#feb308', '#8f1402', '#0485d1'], alpha=0.4, ax=None, set_label_fontsize=18, subset_label_fontsize=14, rotate_labels=True): """ Plot a four-way venn diagram. Parameters ---------- subsets : list Values for each subset of Venn. May be int, float, or string. Use strings for any custom formatting [A, B, C, D, AB, AC, AD, BC, BD, CD, ABC, ABD, ACD, BCD, ABCD] set_labels : list of str, optional Labels around ellipses' exterior set_colors : list, optional Colors of Venn ellipses. Defaults to xkcd's [pea green, amber, brick red, cerulean] alpha : float, optional Alpha of Venn ellipses ax : AxesSubplot Axis to draw Venn on set_label_fontsize : int, optional Fontsize of exterior set labels. Default=18pt, optimized for 8in by 8in figure subset_label_fontsize : int, optional Fontsize of interior count labels Default=14pt, optimized for 8in by 8in figure rotate_labels : bool, optional When true, rotate count labels to fit larger numbers. When false, count labels are horizontal with rotation=0. Returns ------- ax : AxesSubplot """ if len(subsets) != 15: raise Exception('Must provide exactly 15 subset values') if ax is None: ax = plt.gca() width = 0.75 height = 0.5 alpha = 0.4 # Draw ellipses ellipse_coords = [ ((0.50, 0.60), -45), # A (top left) ((0.50, 0.60), 45), # B (top right) ((0.65, 0.40), 45), # C (bottom right) ((0.35, 0.40), -45), # D (bottom left) ] for (coord, angle), color in zip(ellipse_coords, set_colors): e = patches.Ellipse(coord, width, height, angle, alpha=alpha, facecolor=color) ax.add_patch(e) # Add exterior set labels set_label_positions = [ (0.22, 0.91, 45), # A (top left) (0.78, 0.91, -45), # B (top right) (0.12, 0.22, -45), # C (bottom right) (0.88, 0.22, 45), # D (bottom left) ] for label, (x, y, rotation) in zip(set_labels, set_label_positions): ax.text(x, y, label, rotation=rotation, ha='center', va='center', fontsize=set_label_fontsize) # Add subset count labels subsets = [str(s) for s in subsets] subset_positions = [ (0.30, 0.83, 45), # A (0.70, 0.83, -45), # B (0.18, 0.30, -45), # C (0.83, 0.30, 45), # D (0.50, 0.77, 0), # AB (0.22, 0.68, 55), # AC (0.75, 0.40, 45), # AD (0.25, 0.40, -45), # BC (0.78, 0.68, -55), # BD (0.50, 0.18, 0), # CD (0.33, 0.58, 0), # ABC (0.66, 0.58, 0), # ABD (0.60, 0.32, 10), # ACD (0.40, 0.32, -10), # BCD (0.50, 0.45, 0), # ABCD ] for label, (x, y, rotation) in zip(subsets, subset_positions): ax.text(x, y, label, rotation=rotation, ha='center', va='center', fontsize=subset_label_fontsize) # Remove borders ax.set_xticklabels('') ax.set_yticklabels('') ax.axis('off') ax.set_aspect('equal') return ax def venn3(subsets, set_labels=('A', 'B', 'C'), set_colors=['#feb308', '#8f1402', '#0485d1'], alpha=0.4, ax=None, set_label_fontsize=18, subset_label_fontsize=14): """ Plot a three-way venn diagram. Parameters ---------- subsets : list Values for each subset of Venn. May be int, float, or string. Use strings for any custom formatting [A, B, C, AB, AC, BC, ABC] set_labels : list of str, optional Labels around ellipses' exterior set_colors : list, optional Colors of Venn ellipses. Defaults to xkcd's [amber, brick red, cerulean] alpha : float, optional Alpha of Venn ellipses ax : AxesSubplot Axis to draw Venn on set_label_fontsize : int, optional Fontsize of exterior set labels. Default=18pt, optimized for 8in by 8in figure subset_label_fontsize : int, optional Fontsize of interior count labels Default=14pt, optimized for 8in by 8in figure Returns ------- ax : AxesSubplot """ if len(subsets) != 7: raise Exception('Must provide exactly 7 subset values') if ax is None: ax = plt.gca() width = 0.6 height = 0.6 alpha = 0.4 # Draw ellipses ellipse_coords = [ (0.50, 0.63), # A (top) (0.63, 0.37), # B (bottom right) (0.37, 0.37), # C (bottom left) ] for color, coord in zip(set_colors, ellipse_coords): e = patches.Ellipse(coord, width, height, alpha=alpha, facecolor=color) ax.add_patch(e) # Add exterior set labels set_label_positions = [ (0.50, 0.97, 0), # A (top) (0.88, 0.14, 45), # B (bottom right) (0.12, 0.14, -45), # C (bottom left) ] for label, (x, y, rotation) in zip(set_labels, set_label_positions): ax.text(x, y, label, rotation=rotation, ha='center', va='center', fontsize=set_label_fontsize) # Add subset count labels subsets = [str(s) for s in subsets] subset_positions = [ (0.5, 0.77), # A (0.77, 0.3), # B (0.23, 0.3), # C (0.7, 0.55), # AB (0.3, 0.55), # AC (0.5, 0.24), # BC (0.5, 0.47) # ABC ] for label, (x, y) in zip(subsets, subset_positions): ax.text(x, y, label, rotation=0, ha='center', va='center', fontsize=subset_label_fontsize) # Remove borders ax.set_xticklabels('') ax.set_yticklabels('') ax.axis('off') ax.set_aspect('equal') return ax def venn2(subsets, set_labels=('A', 'B'), set_colors=['#0485d1', '#8f1402'], alpha=0.4, ax=None, set_label_fontsize=18, subset_label_fontsize=14): """ Plot a two-way venn diagram. Parameters ---------- subsets : list Values for each subset of Venn. May be int, float, or string. Use strings for any custom formatting [A, B, AB] set_labels : list of str, optional Labels around ellipses' exterior set_colors : list, optional Colors of Venn ellipses. Defaults to xkcd's [cerulean, brick red] alpha : float, optional Alpha of Venn ellipses ax : AxesSubplot Axis to draw Venn on set_label_fontsize : int, optional Fontsize of exterior set labels. Default=18pt, optimized for 8in by 8in figure subset_label_fontsize : int, optional Fontsize of interior count labels Default=14pt, optimized for 8in by 8in figure Returns ------- ax : AxesSubplot """ if len(subsets) != 3: raise Exception('Must provide exactly 3 subset values') if ax is None: ax = plt.gca() # Circle shape and coloring width = 0.65 height = 0.65 alpha = 0.4 # Draw ellipses ellipse_coords = [ (0.37, 0.5), # A (left) (0.63, 0.5), # B (right) ] for color, coord in zip(set_colors, ellipse_coords): e = patches.Ellipse(coord, width, height, alpha=alpha, facecolor=color) ax.add_patch(e) # Add exterior set labels set_label_positions = [ (0.18, 0.82, 30), # A (left) (0.82, 0.82, -30), # B (right) ] for label, (x, y, rotation) in zip(set_labels, set_label_positions): ax.text(x, y, label, rotation=rotation, ha='center', va='center', fontsize=set_label_fontsize) # Add subset count labels subsets = [str(s) for s in subsets] subset_positions = [ (0.2, 0.5), # A (0.8, 0.5), # B (0.5, 0.5), # AB ] for label, (x, y) in zip(subsets, subset_positions): ax.text(x, y, label, rotation=0, ha='center', va='center', fontsize=subset_label_fontsize) # Remove borders ax.set_xticklabels('') ax.set_yticklabels('') ax.axis('off') ax.set_aspect('equal') return ax
msto/svplot
svplot/venn.py
Python
mit
8,650
[ "Amber" ]
017345cfde78f401a370fdd7bf707945aea5d981027c84fab36416efcd643b2d
#http://www.netinstructions.com/how-to-make-a-web-crawler-in-under-50-lines-of-python-code/ from html.parser import HTMLParser from urllib.request import urlopen from urllib import parse # We are going to create a class called LinkParser that inherits some # methods from HTMLParser which is why it is passed into the definition class LinkParser(HTMLParser): # This is a function that HTMLParser normally has # but we are adding some functionality to it def handle_starttag(self, tag, attrs): # We are looking for the begining of a link. Links normally look # like <a href="www.someurl.com"></a> if tag 'a': for (key, value) in attrs: if key 'href': # We are grabbing the new URL. We are also adding the # base URL to it. For example: # www.netinstructions.com is the base and # somepage.html is the new URL (a relative URL) # # We combine a relative URL with the base URL to create # an absolute URL like: # www.netinstructions.com/somepage.html newUrl = parse.urljoin(self.baseUrl, value) # And add it to our colection of links: self.links = self.links + [newUrl] # This is a new function that we are creating to get links # that our spider() function will call def getLinks(self, url): self.links = [] # Remember the base URL which will be important when creating # absolute URLs self.baseUrl = url # Use the urlopen function from the standard Python 3 library response = urlopen(url) # Make sure that we are looking at HTML and not other things that # are floating around on the internet (such as # JavaScript files, CSS, or .PDFs for example) if response.getheader('Content-Type')=='text/html': htmlBytes = response.read() # Note that feed() handles Strings well, but not bytes # (A change from Python 2.x to Python 3.x) htmlString = htmlBytes.decode("utf-8") self.feed(htmlString) return htmlString, self.links else: return "",[] # And finally here is our spider. It takes in an URL, a word to find, # and the number of pages to search through before giving up def spider(url, word, maxPages): pagesToVisit = [url] numberVisited = 0 foundWord = False # The main loop. Create a LinkParser and get all the links on the page. # Also search the page for the word or string # In our getLinks function we return the web page # (this is useful for searching for the word) # and we return a set of links from that web page # (this is useful for where to go next) while numberVisited < maxPages and pagesToVisit != [] and not foundWord: numberVisited = numberVisited +1 # Start from the beginning of our collection of pages to visit: url = pagesToVisit[0] pagesToVisit = pagesToVisit[1:] try: print(numberVisited, "Visiting:", url) parser = LinkParser() data, links = parser.getLinks(url) if data.find(word)>-1: foundWord = True # Add the pages that we visited to the end of our collection # of pages to visit: pagesToVisit = pagesToVisit + links print(" **Success!**") except: print(" **Failed!**") if foundWord: print("The word", word, "was found at", url) else: print("Word never found")
HeyIamJames/Crawlers
crawler.py
Python
mit
3,721
[ "VisIt" ]
3cbb41dd97fa3b6b87f4afedd0e64a65c5b938b34d0bcd06558f7186f6d1e987