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
|
|---|---|---|---|---|---|---|---|
"""
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
"""
# pre-order, in-order, and post-order tree traversal are called Depth First Search (DFS),
# since they visit the tree by proceeding deeper and deeper until it reaches the leaf nodes.
# Usually use recursion, or use _stack_ to simulate recursion by using iterative methods
# level-order traversal is Breadth First Search (BFS), since it visits the nodes level by level.
#++++++++++++++++++\
# Find the maximum height (depth) of a Binary Tree
def maxHeight(node):
if node is None:
return 0
left_height = maxHeight(node.left)
right_height = maxHeight(node.right)
if left_height > right_height:
return left_height + 1
else:
return right_height + 1
def max_iterative(node):
# Any DFS could be modified to solve this problem
# Or use BFS, record how many levels
stack = []
height = 0
while node or stack:
if node:
stack.append(node)
if len(stack) > height:
height = len(stack)
node = node.left
else:
node = stack.pop()
node = node.right
return height
# Find longest path of two leaves (diameter)
def diameter(node):
if node is None:
return 0
lheight = maxHeight(node.left)
rheight = manHeight(node.right)
ldiameter = diameter(node.left)
rdiameter = diameter(node.right)
return max(lheight+rheight+1, max(ldiameter, rdiameter))
# Serialize and Deserialize (a preorder way)
def serialize(node):
if node == None:
return
visit(node.value)
serialize(node.left)
serialize(node.right)
def deserialize(a):
if a is None:
return
if a[0] is None:
return None
node = Node(a[0])
a = a[1:] # Since list has no has_next function
node.left = deserialize(a)
node.right = deserialize(a)
return node
|
armsky/Algorithms
|
Data Structure/tree.py
|
Python
|
apache-2.0
| 2,141
|
[
"VisIt"
] |
5b416c2ecad46d7d40d43f33cd855724490b1df7827972506c0bcddb3de42ebb
|
#!/usr/bin/env python3
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
import sys, os
if len(sys.argv) < 2:
print('Usage: generate_input_syntax.py app_path app_name')
exit(1)
app_path = sys.argv[1]
app_name = sys.argv[2]
MOOSE_DIR = os.path.abspath(os.path.join(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../../..'))))
FRAMEWORK_DIR = os.path.abspath(os.path.join(MOOSE_DIR, 'framework'))
#### See if MOOSE_DIR is already in the environment instead
if "MOOSE_DIR" in os.environ:
MOOSE_DIR = os.environ['MOOSE_DIR']
FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework')
if "FRAMEWORK_DIR" in os.environ:
FRAMEWORK_DIR = os.environ['FRAMEWORK_DIR']
sys.path.append(MOOSE_DIR + '/framework/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR)
|
nuclear-wizard/moose
|
framework/scripts/syntaxHTML/generate_input_syntax.py
|
Python
|
lgpl-2.1
| 1,221
|
[
"MOOSE"
] |
f3962144f42ccf68a3f913c39f7fbef61fab438a33b19adbd946d31f5f28c30d
|
from copy import deepcopy
import logging
from math import floor
import os
from os.path import join as pjoin
import warnings
from warnings import warn
import numpy as np
import nibabel as nib
from mayavi import mlab
from mayavi.tools.mlab_scene_model import MlabSceneModel
from mayavi.core import lut_manager
from mayavi.core.scene import Scene
from mayavi.core.ui.api import SceneEditor
from mayavi.core.ui.mayavi_scene import MayaviScene
from traits.api import (HasTraits, Range, Int, Float,
Bool, Enum, on_trait_change, Instance)
from tvtk.api import tvtk
from pyface.api import GUI
from traitsui.api import View, Item, Group, VGroup, HGroup, VSplit, HSplit
from . import utils, io
from .utils import (Surface, verbose, create_color_lut, _get_subjects_dir,
string_types, threshold_filter, _check_units)
logger = logging.getLogger('surfer')
lh_viewdict = {'lateral': {'v': (180., 90.), 'r': 90.},
'medial': {'v': (0., 90.), 'r': -90.},
'rostral': {'v': (90., 90.), 'r': -180.},
'caudal': {'v': (270., 90.), 'r': 0.},
'dorsal': {'v': (180., 0.), 'r': 90.},
'ventral': {'v': (180., 180.), 'r': 90.},
'frontal': {'v': (120., 80.), 'r': 106.739},
'parietal': {'v': (-120., 60.), 'r': 49.106}}
rh_viewdict = {'lateral': {'v': (180., -90.), 'r': -90.},
'medial': {'v': (0., -90.), 'r': 90.},
'rostral': {'v': (-90., -90.), 'r': 180.},
'caudal': {'v': (90., -90.), 'r': 0.},
'dorsal': {'v': (180., 0.), 'r': 90.},
'ventral': {'v': (180., 180.), 'r': 90.},
'frontal': {'v': (60., 80.), 'r': -106.739},
'parietal': {'v': (-60., 60.), 'r': -49.106}}
viewdicts = dict(lh=lh_viewdict, rh=rh_viewdict)
def make_montage(filename, fnames, orientation='h', colorbar=None,
border_size=15):
"""Save montage of current figure
Parameters
----------
filename : str
The name of the file, e.g, 'montage.png'. If None, the image
will not be saved.
fnames : list of str | list of array
The images to make the montage of. Can be a list of filenames
or a list of image data arrays.
orientation : 'h' | 'v' | list
The orientation of the montage: horizontal, vertical, or a nested
list of int (indexes into fnames).
colorbar : None | list of int
If None remove colorbars, else keep the ones whose index
is present.
border_size : int
The size of the border to keep.
Returns
-------
out : array
The montage image data array.
"""
try:
import Image
except (ValueError, ImportError):
from PIL import Image
from scipy import ndimage
# This line is only necessary to overcome a PIL bug, see:
# http://stackoverflow.com/questions/10854903/what-is-causing-
# dimension-dependent-attributeerror-in-pil-fromarray-function
fnames = [f if isinstance(f, string_types) else f.copy() for f in fnames]
if isinstance(fnames[0], string_types):
images = list(map(Image.open, fnames))
else:
images = list(map(Image.fromarray, fnames))
# get bounding box for cropping
boxes = []
for ix, im in enumerate(images):
# sum the RGB dimension so we do not miss G or B-only pieces
gray = np.sum(np.array(im), axis=-1)
gray[gray == gray[0, 0]] = 0 # hack for find_objects that wants 0
if np.all(gray == 0):
raise ValueError("Empty image (all pixels have the same color).")
labels, n_labels = ndimage.label(gray.astype(np.float))
slices = ndimage.find_objects(labels, n_labels) # slice roi
if colorbar is not None and ix in colorbar:
# we need all pieces so let's compose them into single min/max
slices_a = np.array([[[xy.start, xy.stop] for xy in s]
for s in slices])
# TODO: ideally gaps could be deduced and cut out with
# consideration of border_size
# so we need mins on 0th and maxs on 1th of 1-nd dimension
mins = np.min(slices_a[:, :, 0], axis=0)
maxs = np.max(slices_a[:, :, 1], axis=0)
s = (slice(mins[0], maxs[0]), slice(mins[1], maxs[1]))
else:
# we need just the first piece
s = slices[0]
# box = (left, top, width, height)
boxes.append([s[1].start - border_size, s[0].start - border_size,
s[1].stop + border_size, s[0].stop + border_size])
# convert orientation to nested list of int
if orientation == 'h':
orientation = [range(len(images))]
elif orientation == 'v':
orientation = [[i] for i in range(len(images))]
# find bounding box
n_rows = len(orientation)
n_cols = max(len(row) for row in orientation)
if n_rows > 1:
min_left = min(box[0] for box in boxes)
max_width = max(box[2] for box in boxes)
for box in boxes:
box[0] = min_left
box[2] = max_width
if n_cols > 1:
min_top = min(box[1] for box in boxes)
max_height = max(box[3] for box in boxes)
for box in boxes:
box[1] = min_top
box[3] = max_height
# crop images
cropped_images = []
for im, box in zip(images, boxes):
cropped_images.append(im.crop(box))
images = cropped_images
# Get full image size
row_w = [sum(images[i].size[0] for i in row) for row in orientation]
row_h = [max(images[i].size[1] for i in row) for row in orientation]
out_w = max(row_w)
out_h = sum(row_h)
# compose image
new = Image.new("RGBA", (out_w, out_h))
y = 0
for row, h in zip(orientation, row_h):
x = 0
for i in row:
im = images[i]
pos = (x, y)
new.paste(im, pos)
x += im.size[0]
y += h
if filename is not None:
new.save(filename)
return np.array(new)
def _prepare_data(data):
"""Ensure data is float64 and has proper endianness.
Note: this is largely aimed at working around a Mayavi bug.
"""
data = data.copy()
data = data.astype(np.float64)
if data.dtype.byteorder == '>':
data.byteswap(True)
return data
def _force_render(figures):
"""Ensure plots are updated before properties are used"""
if not isinstance(figures, list):
figures = [[figures]]
_gui = GUI()
orig_val = _gui.busy
_gui.set_busy(busy=True)
_gui.process_events()
for ff in figures:
for f in ff:
f.render()
mlab.draw(figure=f)
_gui.set_busy(busy=orig_val)
_gui.process_events()
def _make_viewer(figure, n_row, n_col, title, scene_size, offscreen,
interaction='trackball', antialias=True):
"""Triage viewer creation
If n_row == n_col == 1, then we can use a Mayavi figure, which
generally guarantees that things will be drawn before control
is returned to the command line. With the multi-view, TraitsUI
unfortunately has no such support, so we only use it if needed.
"""
if figure is None:
# spawn scenes
h, w = scene_size
if offscreen == 'auto':
offscreen = mlab.options.offscreen
if offscreen:
orig_val = mlab.options.offscreen
try:
mlab.options.offscreen = True
with warnings.catch_warnings(record=True): # traits
figures = [[mlab.figure(size=(w / n_col, h / n_row))
for _ in range(n_col)] for __ in range(n_row)]
finally:
mlab.options.offscreen = orig_val
_v = None
else:
# Triage: don't make TraitsUI if we don't have to
if n_row == 1 and n_col == 1:
with warnings.catch_warnings(record=True): # traits
figure = mlab.figure(size=(w, h))
figure.name = title # should set the figure title
figures = [[figure]]
_v = None
else:
window = _MlabGenerator(n_row, n_col, w, h, title)
figures, _v = window._get_figs_view()
if interaction == 'terrain': # "trackball" is default
for figure in figures:
for f in figure:
f.scene.interactor.interactor_style = \
tvtk.InteractorStyleTerrain()
if antialias:
for figure in figures:
for f in figure:
# on a non-testing backend, and using modern VTK/Mayavi
if hasattr(getattr(f.scene, 'renderer', None),
'use_fxaa'):
f.scene.renderer.use_fxaa = True
else:
if isinstance(figure, int): # use figure with specified id
figure = [mlab.figure(figure, size=scene_size)]
elif isinstance(figure, tuple):
figure = list(figure)
elif not isinstance(figure, list):
figure = [figure]
if not all(isinstance(f, Scene) for f in figure):
raise TypeError('figure must be a mayavi scene or list of scenes')
if not len(figure) == n_row * n_col:
raise ValueError('For the requested view, figure must be a '
'list or tuple with exactly %i elements, '
'not %i' % (n_row * n_col, len(figure)))
_v = None
figures = [figure[slice(ri * n_col, (ri + 1) * n_col)]
for ri in range(n_row)]
return figures, _v
class _MlabGenerator(HasTraits):
"""TraitsUI mlab figure generator"""
view = Instance(View)
def __init__(self, n_row, n_col, width, height, title, **traits):
HasTraits.__init__(self, **traits)
self.mlab_names = []
self.n_row = n_row
self.n_col = n_col
self.width = width
self.height = height
for fi in range(n_row * n_col):
name = 'mlab_view%03g' % fi
self.mlab_names.append(name)
self.add_trait(name, Instance(MlabSceneModel, ()))
self.view = self._get_gen_view()
self._v = self.edit_traits(view=self.view)
self._v.title = title
def _get_figs_view(self):
figures = []
ind = 0
for ri in range(self.n_row):
rfigs = []
for ci in range(self.n_col):
x = getattr(self, self.mlab_names[ind])
rfigs.append(x.mayavi_scene)
ind += 1
figures.append(rfigs)
return figures, self._v
def _get_gen_view(self):
ind = 0
va = []
for ri in range(self.n_row):
ha = []
for ci in range(self.n_col):
ha += [Item(name=self.mlab_names[ind], style='custom',
resizable=True, show_label=False,
editor=SceneEditor(scene_class=MayaviScene))]
ind += 1
va += [HGroup(*ha)]
view = View(VGroup(*va), resizable=True,
height=self.height, width=self.width)
return view
class Brain(object):
"""Class for visualizing a brain using multiple views in mlab
Parameters
----------
subject_id : str
subject name in Freesurfer subjects dir
hemi : str
hemisphere id (ie 'lh', 'rh', 'both', or 'split'). In the case
of 'both', both hemispheres are shown in the same window.
In the case of 'split' hemispheres are displayed side-by-side
in different viewing panes.
surf : str
freesurfer surface mesh name (ie 'white', 'inflated', etc.)
title : str
title for the window
cortex : str, tuple, dict, or None
Specifies how the cortical surface is rendered. Options:
1. The name of one of the preset cortex styles:
``'classic'`` (default), ``'high_contrast'``,
``'low_contrast'``, or ``'bone'``.
2. A color-like argument to render the cortex as a single
color, e.g. ``'red'`` or ``(0.1, 0.4, 1.)``. Setting
this to ``None`` is equivalent to ``(0.5, 0.5, 0.5)``.
3. The name of a colormap used to render binarized
curvature values, e.g., ``Grays``.
4. A list of colors used to render binarized curvature
values. Only the first and last colors are used. E.g.,
['red', 'blue'] or [(1, 0, 0), (0, 0, 1)].
5. A container with four entries for colormap (string
specifiying the name of a colormap), vmin (float
specifying the minimum value for the colormap), vmax
(float specifying the maximum value for the colormap),
and reverse (bool specifying whether the colormap
should be reversed. E.g., ``('Greys', -1, 2, False)``.
6. A dict of keyword arguments that is passed on to the
call to surface.
alpha : float in [0, 1]
Alpha level to control opacity of the cortical surface.
size : float or pair of floats
the size of the window, in pixels. can be one number to specify
a square window, or the (width, height) of a rectangular window.
background : matplotlib color
Color of the background.
foreground : matplotlib color
Color of the foreground (will be used for colorbars and text).
None (default) will use black or white depending on the value
of ``background``.
figure : list of mayavi.core.scene.Scene | None | int
If None (default), a new window will be created with the appropriate
views. For single view plots, the figure can be specified as int to
retrieve the corresponding Mayavi window.
subjects_dir : str | None
If not None, this directory will be used as the subjects directory
instead of the value set using the SUBJECTS_DIR environment
variable.
views : list | str
views to use
offset : bool
If True, aligs origin with medial wall. Useful for viewing inflated
surface where hemispheres typically overlap (Default: True)
show_toolbar : bool
If True, toolbars will be shown for each view.
offscreen : bool | str
If True, rendering will be done offscreen (not shown). Useful
mostly for generating images or screenshots, but can be buggy.
Use at your own risk. Can be "auto" (default) to use
``mlab.options.offscreen``.
interaction : str
Can be "trackball" (default) or "terrain", i.e. a turntable-style
camera.
units : str
Can be 'm' or 'mm' (default).
antialias : bool
If True (default), turn on antialiasing. Can be problematic for
some renderers (e.g., software rendering with MESA).
Attributes
----------
annot : list
List of annotations.
brains : list
List of the underlying brain instances.
contour : list
List of the contours.
foci : foci
The foci.
labels : dict
The labels.
overlays : dict
The overlays.
texts : dict
The text objects.
"""
def __init__(self, subject_id, hemi, surf, title=None,
cortex="classic", alpha=1.0, size=800, background="black",
foreground=None, figure=None, subjects_dir=None,
views=['lat'], offset=True, show_toolbar=False,
offscreen='auto', interaction='trackball', units='mm',
antialias=True):
if not isinstance(interaction, string_types) or \
interaction not in ('trackball', 'terrain'):
raise ValueError('interaction must be "trackball" or "terrain", '
'got "%s"' % (interaction,))
self._units = _check_units(units)
col_dict = dict(lh=1, rh=1, both=1, split=2)
n_col = col_dict[hemi]
if hemi not in col_dict.keys():
raise ValueError('hemi must be one of [%s], not %s'
% (', '.join(col_dict.keys()), hemi))
# Get the subjects directory from parameter or env. var
subjects_dir = _get_subjects_dir(subjects_dir=subjects_dir)
self._hemi = hemi
if title is None:
title = subject_id
self.subject_id = subject_id
if not isinstance(views, (list, tuple)):
views = [views]
n_row = len(views)
# load geometry for one or both hemispheres as necessary
offset = None if (not offset or hemi != 'both') else 0.0
self.geo = dict()
if hemi in ['split', 'both']:
geo_hemis = ['lh', 'rh']
elif hemi == 'lh':
geo_hemis = ['lh']
elif hemi == 'rh':
geo_hemis = ['rh']
else:
raise ValueError('bad hemi value')
geo_kwargs, geo_reverse, geo_curv = self._get_geo_params(cortex, alpha)
for h in geo_hemis:
# Initialize a Surface object as the geometry
geo = Surface(subject_id, h, surf, subjects_dir, offset,
units=self._units)
# Load in the geometry and (maybe) curvature
geo.load_geometry()
if geo_curv:
geo.load_curvature()
self.geo[h] = geo
# deal with making figures
self._set_window_properties(size, background, foreground)
del background, foreground
figures, _v = _make_viewer(figure, n_row, n_col, title,
self._scene_size, offscreen,
interaction, antialias)
self._figures = figures
self._v = _v
self._window_backend = 'Mayavi' if self._v is None else 'TraitsUI'
for ff in self._figures:
for f in ff:
if f.scene is not None:
f.scene.background = self._bg_color
f.scene.foreground = self._fg_color
# force rendering so scene.lights exists
_force_render(self._figures)
self.toggle_toolbars(show_toolbar)
_force_render(self._figures)
self._toggle_render(False)
# fill figures with brains
kwargs = dict(geo_curv=geo_curv, geo_kwargs=geo_kwargs,
geo_reverse=geo_reverse, subjects_dir=subjects_dir,
bg_color=self._bg_color, fg_color=self._fg_color)
brains = []
brain_matrix = []
for ri, view in enumerate(views):
brain_row = []
for hi, h in enumerate(['lh', 'rh']):
if not (hemi in ['lh', 'rh'] and h != hemi):
ci = hi if hemi == 'split' else 0
kwargs['hemi'] = h
kwargs['geo'] = self.geo[h]
kwargs['figure'] = figures[ri][ci]
kwargs['backend'] = self._window_backend
brain = _Hemisphere(subject_id, **kwargs)
brain.show_view(view)
brains += [dict(row=ri, col=ci, brain=brain, hemi=h)]
brain_row += [brain]
brain_matrix += [brain_row]
self._toggle_render(True)
self._original_views = views
self._brain_list = brains
for brain in self._brain_list:
brain['brain']._orient_lights()
self.brains = [b['brain'] for b in brains]
self.brain_matrix = np.array(brain_matrix)
self.subjects_dir = subjects_dir
self.surf = surf
# Initialize the overlay and label dictionaries
self.foci_dict = dict()
self._label_dicts = dict()
self.overlays_dict = dict()
self.contour_list = []
self.morphometry_list = []
self.annot_list = []
self._data_dicts = dict(lh=[], rh=[])
# note that texts gets treated differently
self.texts_dict = dict()
self._times = None
self.n_times = None
@property
def data_dict(self):
"""For backwards compatibility"""
lh_list = self._data_dicts['lh']
rh_list = self._data_dicts['rh']
return dict(lh=lh_list[-1] if lh_list else None,
rh=rh_list[-1] if rh_list else None)
@property
def labels_dict(self):
"""For backwards compatibility"""
return {key: data['surfaces'] for key, data in
self._label_dicts.items()}
###########################################################################
# HELPERS
def _toggle_render(self, state, views=None):
"""Turn rendering on (True) or off (False)"""
figs = [fig for fig_row in self._figures for fig in fig_row]
if views is None:
views = [None] * len(figs)
for vi, (_f, view) in enumerate(zip(figs, views)):
# Testing backend doesn't have these options
if mlab.options.backend == 'test':
continue
if state is False and view is None:
views[vi] = (mlab.view(figure=_f), mlab.roll(figure=_f),
_f.scene.camera.parallel_scale
if _f.scene is not None else False)
if _f.scene is not None:
_f.scene.disable_render = not state
if state is True and view is not None and _f.scene is not None:
mlab.draw(figure=_f)
with warnings.catch_warnings(record=True): # traits focalpoint
mlab.view(*view[0], figure=_f)
mlab.roll(view[1], figure=_f)
# let's do the ugly force draw
if state is True:
_force_render(self._figures)
return views
def _set_window_properties(self, size, background, foreground):
"""Set window properties that are used elsewhere."""
# old option "size" sets both width and height
from matplotlib.colors import colorConverter
try:
width, height = size
except (TypeError, ValueError):
width, height = size, size
self._scene_size = height, width
self._bg_color = colorConverter.to_rgb(background)
if foreground is None:
foreground = 'w' if sum(self._bg_color) < 2 else 'k'
self._fg_color = colorConverter.to_rgb(foreground)
def _get_geo_params(self, cortex, alpha=1.0):
"""Return keyword arguments and other parameters for surface
rendering.
Parameters
----------
cortex : {str, tuple, dict, None}
Can be set to: (1) the name of one of the preset cortex
styles ('classic', 'high_contrast', 'low_contrast', or
'bone'), (2) the name of a colormap, (3) a tuple with
four entries for (colormap, vmin, vmax, reverse)
indicating the name of the colormap, the min and max
values respectively and whether or not the colormap should
be reversed, (4) a valid color specification (such as a
3-tuple with RGB values or a valid color name), or (5) a
dictionary of keyword arguments that is passed on to the
call to surface. If set to None, color is set to (0.5,
0.5, 0.5).
alpha : float in [0, 1]
Alpha level to control opacity of the cortical surface.
Returns
-------
kwargs : dict
Dictionary with keyword arguments to be used for surface
rendering. For colormaps, keys are ['colormap', 'vmin',
'vmax', 'alpha'] to specify the name, minimum, maximum,
and alpha transparency of the colormap respectively. For
colors, keys are ['color', 'alpha'] to specify the name
and alpha transparency of the color respectively.
reverse : boolean
Boolean indicating whether a colormap should be
reversed. Set to False if a color (rather than a colormap)
is specified.
curv : boolean
Boolean indicating whether curv file is loaded and binary
curvature is displayed.
"""
from matplotlib.colors import colorConverter
colormap_map = dict(classic=(dict(colormap="Greys",
vmin=-1, vmax=2,
opacity=alpha), False, True),
high_contrast=(dict(colormap="Greys",
vmin=-.1, vmax=1.3,
opacity=alpha), False, True),
low_contrast=(dict(colormap="Greys",
vmin=-5, vmax=5,
opacity=alpha), False, True),
bone=(dict(colormap="bone",
vmin=-.2, vmax=2,
opacity=alpha), True, True))
if isinstance(cortex, dict):
if 'opacity' not in cortex:
cortex['opacity'] = alpha
if 'colormap' in cortex:
if 'vmin' not in cortex:
cortex['vmin'] = -1
if 'vmax' not in cortex:
cortex['vmax'] = 2
geo_params = cortex, False, True
elif isinstance(cortex, string_types):
if cortex in colormap_map:
geo_params = colormap_map[cortex]
elif cortex in lut_manager.lut_mode_list():
geo_params = dict(colormap=cortex, vmin=-1, vmax=2,
opacity=alpha), False, True
else:
try:
color = colorConverter.to_rgb(cortex)
geo_params = dict(color=color, opacity=alpha), False, False
except ValueError:
geo_params = cortex, False, True
# check for None before checking len:
elif cortex is None:
geo_params = dict(color=(0.5, 0.5, 0.5),
opacity=alpha), False, False
# Test for 4-tuple specifying colormap parameters. Need to
# avoid 4 letter strings and 4-tuples not specifying a
# colormap name in the first position (color can be specified
# as RGBA tuple, but the A value will be dropped by to_rgb()):
elif (len(cortex) == 4) and (isinstance(cortex[0], string_types)):
geo_params = dict(colormap=cortex[0], vmin=cortex[1],
vmax=cortex[2], opacity=alpha), cortex[3], True
else:
try: # check if it's a non-string color specification
color = colorConverter.to_rgb(cortex)
geo_params = dict(color=color, opacity=alpha), False, False
except ValueError:
try:
lut = create_color_lut(cortex)
geo_params = dict(colormap="Greys", opacity=alpha,
lut=lut), False, True
except ValueError:
geo_params = cortex, False, True
return geo_params
def get_data_properties(self):
""" Get properties of the data shown
Returns
-------
props : dict
Dictionary with data properties
props["fmin"] : minimum colormap
props["fmid"] : midpoint colormap
props["fmax"] : maximum colormap
props["transparent"] : lower part of colormap transparent?
props["time"] : time points
props["time_idx"] : current time index
props["smoothing_steps"] : number of smoothing steps
"""
props = dict()
keys = ['fmin', 'fmid', 'fmax', 'transparent', 'time', 'time_idx',
'smoothing_steps', 'center']
try:
if self.data_dict['lh'] is not None:
hemi = 'lh'
else:
hemi = 'rh'
for key in keys:
props[key] = self.data_dict[hemi][key]
except KeyError:
# The user has not added any data
for key in keys:
props[key] = 0
return props
def toggle_toolbars(self, show=None):
"""Toggle toolbar display
Parameters
----------
show : bool | None
If None, the state is toggled. If True, the toolbar will
be shown, if False, hidden.
"""
# don't do anything if testing is on
if self._figures[0][0].scene is not None:
# this may not work if QT is not the backend (?), or in testing
if hasattr(self._figures[0][0].scene, 'scene_editor'):
# Within TraitsUI
bars = [f.scene.scene_editor._tool_bar
for ff in self._figures for f in ff]
else:
# Mayavi figure
bars = [f.scene._tool_bar for ff in self._figures for f in ff]
if show is None:
if hasattr(bars[0], 'isVisible'):
# QT4
show = not bars[0].isVisible()
elif hasattr(bars[0], 'Shown'):
# WX
show = not bars[0].Shown()
for bar in bars:
if hasattr(bar, 'setVisible'):
bar.setVisible(show)
elif hasattr(bar, 'Show'):
bar.Show(show)
def _get_one_brain(self, d, name):
"""Helper for various properties"""
if len(self.brains) > 1:
raise ValueError('Cannot access brain.%s when more than '
'one view is plotted. Use brain.brain_matrix '
'or brain.brains.' % name)
if isinstance(d, dict):
out = dict()
for key, value in d.items():
out[key] = value[0]
else:
out = d[0]
return out
@property
def overlays(self):
return self._get_one_brain(self.overlays_dict, 'overlays')
@property
def foci(self):
return self._get_one_brain(self.foci_dict, 'foci')
@property
def labels(self):
return self._get_one_brain(self.labels_dict, 'labels')
@property
def contour(self):
return self._get_one_brain(self.contour_list, 'contour')
@property
def annot(self):
return self._get_one_brain(self.annot_list, 'annot')
@property
def texts(self):
self._get_one_brain([[]], 'texts')
out = dict()
for key, val in self.texts_dict.iteritems():
out[key] = val['text']
return out
@property
def data(self):
self._get_one_brain([[]], 'data')
if self.data_dict['lh'] is not None:
data = self.data_dict['lh'].copy()
else:
data = self.data_dict['rh'].copy()
if 'colorbars' in data:
data['colorbar'] = data['colorbars'][0]
return data
def _check_hemi(self, hemi):
"""Check for safe single-hemi input, returns str"""
if hemi is None:
if self._hemi not in ['lh', 'rh']:
raise ValueError('hemi must not be None when both '
'hemispheres are displayed')
else:
hemi = self._hemi
elif hemi not in ['lh', 'rh']:
extra = ' or None' if self._hemi in ['lh', 'rh'] else ''
raise ValueError('hemi must be either "lh" or "rh"' + extra)
return hemi
def _check_hemis(self, hemi):
"""Check for safe dual or single-hemi input, returns list"""
if hemi is None:
if self._hemi not in ['lh', 'rh']:
hemi = ['lh', 'rh']
else:
hemi = [self._hemi]
elif hemi not in ['lh', 'rh']:
extra = ' or None' if self._hemi in ['lh', 'rh'] else ''
raise ValueError('hemi must be either "lh" or "rh"' + extra)
else:
hemi = [hemi]
return hemi
def _read_scalar_data(self, source, hemi, name=None, cast=True):
"""Load in scalar data from an image stored in a file or an array
Parameters
----------
source : str or numpy array
path to scalar data file or a numpy array
name : str or None, optional
name for the overlay in the internal dictionary
cast : bool, optional
either to cast float data into 64bit datatype as a
workaround. cast=True can fix a rendering problem with
certain versions of Mayavi
Returns
-------
scalar_data : numpy array
flat numpy array of scalar data
name : str
if no name was provided, deduces the name if filename was given
as a source
"""
# If source is a string, try to load a file
if isinstance(source, string_types):
if name is None:
basename = os.path.basename(source)
if basename.endswith(".gz"):
basename = basename[:-3]
if basename.startswith("%s." % hemi):
basename = basename[3:]
name = os.path.splitext(basename)[0]
scalar_data = io.read_scalar_data(source)
else:
# Can't think of a good way to check that this will work nicely
scalar_data = source
if cast:
if (scalar_data.dtype.char == 'f' and
scalar_data.dtype.itemsize < 8):
scalar_data = scalar_data.astype(np.float)
return scalar_data, name
def _get_display_range(self, scalar_data, min, max, sign):
if scalar_data.min() >= 0:
sign = "pos"
elif scalar_data.max() <= 0:
sign = "neg"
# Get data with a range that will make sense for automatic thresholding
if sign == "neg":
range_data = np.abs(scalar_data[np.where(scalar_data < 0)])
elif sign == "pos":
range_data = scalar_data[np.where(scalar_data > 0)]
else:
range_data = np.abs(scalar_data)
# Get a numeric value for the scalar minimum
if min is None:
min = "robust_min"
if min == "robust_min":
min = np.percentile(range_data, 2)
elif min == "actual_min":
min = range_data.min()
# Get a numeric value for the scalar maximum
if max is None:
max = "robust_max"
if max == "robust_max":
max = np.percentile(scalar_data, 98)
elif max == "actual_max":
max = range_data.max()
return min, max
def _iter_time(self, time_idx, interpolation):
"""Iterate through time points, then reset to current time
Parameters
----------
time_idx : array_like
Time point indexes through which to iterate.
interpolation : str
Interpolation method (``scipy.interpolate.interp1d`` parameter,
one of 'linear' | 'nearest' | 'zero' | 'slinear' | 'quadratic' |
'cubic'). Interpolation is only used for non-integer indexes.
Yields
------
idx : int | float
Current index.
Notes
-----
Used by movie and image sequence saving functions.
"""
current_time_idx = self.data_time_index
for idx in time_idx:
self.set_data_time_index(idx, interpolation)
yield idx
# Restore original time index
self.set_data_time_index(current_time_idx)
###########################################################################
# ADDING DATA PLOTS
def add_overlay(self, source, min=2, max="robust_max", sign="abs",
name=None, hemi=None, **kwargs):
"""Add an overlay to the overlay dict from a file or array.
Parameters
----------
source : str or numpy array
path to the overlay file or numpy array with data
min : float
threshold for overlay display
max : float
saturation point for overlay display
sign : {'abs' | 'pos' | 'neg'}
whether positive, negative, or both values should be displayed
name : str
name for the overlay in the internal dictionary
hemi : str | None
If None, it is assumed to belong to the hemipshere being
shown. If two hemispheres are being shown, an error will
be thrown.
**kwargs : additional keyword arguments
These are passed to the underlying
``mayavi.mlab.pipeline.surface`` call.
"""
hemi = self._check_hemi(hemi)
# load data here
scalar_data, name = self._read_scalar_data(source, hemi, name=name)
min, max = self._get_display_range(scalar_data, min, max, sign)
if sign not in ["abs", "pos", "neg"]:
raise ValueError("Overlay sign must be 'abs', 'pos', or 'neg'")
old = OverlayData(scalar_data, min, max, sign)
ol = []
views = self._toggle_render(False)
for brain in self._brain_list:
if brain['hemi'] == hemi:
ol.append(brain['brain'].add_overlay(old, **kwargs))
if name in self.overlays_dict:
name = "%s%d" % (name, len(self.overlays_dict) + 1)
self.overlays_dict[name] = ol
self._toggle_render(True, views)
@verbose
def add_data(self, array, min=None, max=None, thresh=None,
colormap="auto", alpha=1,
vertices=None, smoothing_steps=20, time=None,
time_label="time index=%d", colorbar=True,
hemi=None, remove_existing=False, time_label_size=14,
initial_time=None, scale_factor=None, vector_alpha=None,
mid=None, center=None, transparent=False, verbose=None,
**kwargs):
"""Display data from a numpy array on the surface.
This provides a similar interface to
:meth:`surfer.Brain.add_overlay`, but it displays
it with a single colormap. It offers more flexibility over the
colormap, and provides a way to display four-dimensional data
(i.e., a timecourse) or five-dimensional data (i.e., a
vector-valued timecourse).
.. note:: ``min`` sets the low end of the colormap, and is separate
from thresh (this is a different convention from
:meth:`surfer.Brain.add_overlay`).
Parameters
----------
array : numpy array, shape (n_vertices[, 3][, n_times])
Data array. For the data to be understood as vector-valued
(3 values per vertex corresponding to X/Y/Z surface RAS),
then ``array`` must be have all 3 dimensions.
If vectors with no time dimension are desired, consider using a
singleton (e.g., ``np.newaxis``) to create a "time" dimension
and pass ``time_label=None``.
min : float
min value in colormap (uses real min if None)
mid : float
intermediate value in colormap (middle between min and max if None)
max : float
max value in colormap (uses real max if None)
thresh : None or float
if not None, values below thresh will not be visible
center : float or None
if not None, center of a divergent colormap, changes the meaning of
min, max and mid, see :meth:`scale_data_colormap` for further info.
transparent : bool
if True: use a linear transparency between fmin and fmid and make
values below fmin fully transparent (symmetrically for divergent
colormaps)
colormap : string, list of colors, or array
name of matplotlib colormap to use, a list of matplotlib colors,
or a custom look up table (an n x 4 array coded with RBGA values
between 0 and 255), the default "auto" chooses a default divergent
colormap, if "center" is given (currently "icefire"), otherwise a
default sequential colormap (currently "rocket").
alpha : float in [0, 1]
alpha level to control opacity of the overlay.
vertices : numpy array
vertices for which the data is defined (needed if len(data) < nvtx)
smoothing_steps : int | str | None
Number of smoothing steps (if data come from surface subsampling).
Can be None to use the fewest steps that result in all vertices
taking on data values, or "nearest" such that each high resolution
vertex takes the value of the its nearest (on the sphere)
low-resolution vertex. Default is 20.
time : numpy array
time points in the data array (if data is 2D or 3D)
time_label : str | callable | None
format of the time label (a format string, a function that maps
floating point time values to strings, or None for no label)
colorbar : bool
whether to add a colorbar to the figure
hemi : str | None
If None, it is assumed to belong to the hemisphere being
shown. If two hemispheres are being shown, an error will
be thrown.
remove_existing : bool
Remove surface added by previous "add_data" call. Useful for
conserving memory when displaying different data in a loop.
time_label_size : int
Font size of the time label (default 14)
initial_time : float | None
Time initially shown in the plot. ``None`` to use the first time
sample (default).
scale_factor : float | None (default)
The scale factor to use when displaying glyphs for vector-valued
data.
vector_alpha : float | None
alpha level to control opacity of the arrows. Only used for
vector-valued data. If None (default), ``alpha`` is used.
verbose : bool, str, int, or None
If not None, override default verbose level (see surfer.verbose).
**kwargs : additional keyword arguments
These are passed to the underlying
``mayavi.mlab.pipeline.surface`` call.
Notes
-----
If the data is defined for a subset of vertices (specified
by the "vertices" parameter), a smoothing method is used to interpolate
the data onto the high resolution surface. If the data is defined for
subsampled version of the surface, smoothing_steps can be set to None,
in which case only as many smoothing steps are applied until the whole
surface is filled with non-zeros.
Due to a Mayavi (or VTK) alpha rendering bug, ``vector_alpha`` is
clamped to be strictly < 1.
"""
hemi = self._check_hemi(hemi)
array = np.asarray(array)
if center is None:
if min is None:
min = array.min() if array.size > 0 else 0
if max is None:
max = array.max() if array.size > 0 else 1
else:
if min is None:
min = 0
if max is None:
max = np.abs(center - array).max() if array.size > 0 else 1
if mid is None:
mid = (min + max) / 2.
_check_limits(min, mid, max, extra='')
# Create smoothing matrix if necessary
if len(array) < self.geo[hemi].x.shape[0]:
if vertices is None:
raise ValueError("len(data) < nvtx (%s < %s): the vertices "
"parameter must not be None"
% (len(array), self.geo[hemi].x.shape[0]))
adj_mat = utils.mesh_edges(self.geo[hemi].faces)
smooth_mat = utils.smoothing_matrix(vertices, adj_mat,
smoothing_steps)
else:
smooth_mat = None
magnitude = None
if array.ndim == 3:
if array.shape[1] != 3:
raise ValueError('If array has 3 dimensions, array.shape[1] '
'must equal 3, got %s' % (array.shape[1],))
magnitude = np.linalg.norm(array, axis=1)
if scale_factor is None:
distance = 4 * np.linalg.norm(array, axis=1).max()
if distance == 0:
scale_factor = 1
else:
scale_factor = (0.4 * distance /
(4 * array.shape[0] ** (0.33)))
if self._units == 'm':
scale_factor = scale_factor / 1000.
elif array.ndim not in (1, 2):
raise ValueError('array has must have 1, 2, or 3 dimensions, '
'got (%s)' % (array.ndim,))
# Process colormap argument into a lut
lut = create_color_lut(colormap, center=center)
colormap = "Greys"
# determine unique data layer ID
data_dicts = self._data_dicts['lh'] + self._data_dicts['rh']
if data_dicts:
layer_id = np.max([data['layer_id'] for data in data_dicts]) + 1
else:
layer_id = 0
data = dict(array=array, smoothing_steps=smoothing_steps,
fmin=min, fmid=mid, fmax=max, center=center,
scale_factor=scale_factor,
transparent=False, time=0, time_idx=0,
vertices=vertices, smooth_mat=smooth_mat,
layer_id=layer_id, magnitude=magnitude)
# clean up existing data
if remove_existing:
self.remove_data(hemi)
# Create time array and add label if > 1D
if array.ndim <= 1:
initial_time_index = None
else:
# check time array
if time is None:
time = np.arange(array.shape[-1])
else:
time = np.asarray(time)
if time.shape != (array.shape[-1],):
raise ValueError('time has shape %s, but need shape %s '
'(array.shape[-1])' %
(time.shape, (array.shape[-1],)))
if self.n_times is None:
self.n_times = len(time)
self._times = time
elif len(time) != self.n_times:
raise ValueError("New n_times is different from previous "
"n_times")
elif not np.array_equal(time, self._times):
raise ValueError("Not all time values are consistent with "
"previously set times.")
# initial time
if initial_time is None:
initial_time_index = None
else:
initial_time_index = self.index_for_time(initial_time)
# time label
if isinstance(time_label, string_types):
time_label_fmt = time_label
def time_label(x):
return time_label_fmt % x
data["time_label"] = time_label
data["time"] = time
data["time_idx"] = 0
y_txt = 0.05 + 0.05 * bool(colorbar)
surfs = []
bars = []
glyphs = []
views = self._toggle_render(False)
vector_alpha = alpha if vector_alpha is None else vector_alpha
for brain in self._brain_list:
if brain['hemi'] == hemi:
s, ct, bar, gl = brain['brain'].add_data(
array, min, mid, max, thresh, lut, colormap, alpha,
colorbar, layer_id, smooth_mat, magnitude,
scale_factor, vertices, vector_alpha, **kwargs)
surfs.append(s)
bars.append(bar)
glyphs.append(gl)
if array.ndim >= 2 and time_label is not None:
self.add_text(0.95, y_txt, time_label(time[0]),
name="time_label", row=brain['row'],
col=brain['col'], font_size=time_label_size,
justification='right')
data['surfaces'] = surfs
data['colorbars'] = bars
data['orig_ctable'] = ct
data['glyphs'] = glyphs
self._data_dicts[hemi].append(data)
self.scale_data_colormap(min, mid, max, transparent, center, alpha,
data, hemi=hemi)
if initial_time_index is not None:
self.set_data_time_index(initial_time_index)
self._toggle_render(True, views)
def add_annotation(self, annot, borders=True, alpha=1, hemi=None,
remove_existing=True, color=None, **kwargs):
"""Add an annotation file.
Parameters
----------
annot : str | tuple
Either path to annotation file or annotation name. Alternatively,
the annotation can be specified as a ``(labels, ctab)`` tuple per
hemisphere, i.e. ``annot=(labels, ctab)`` for a single hemisphere
or ``annot=((lh_labels, lh_ctab), (rh_labels, rh_ctab))`` for both
hemispheres. ``labels`` and ``ctab`` should be arrays as returned
by :func:`nibabel.freesurfer.io.read_annot`.
borders : bool | int
Show only label borders. If int, specify the number of steps
(away from the true border) along the cortical mesh to include
as part of the border definition.
alpha : float in [0, 1]
Alpha level to control opacity.
hemi : str | None
If None, it is assumed to belong to the hemipshere being
shown. If two hemispheres are being shown, data must exist
for both hemispheres.
remove_existing : bool
If True (default), remove old annotations.
color : matplotlib-style color code
If used, show all annotations in the same (specified) color.
Probably useful only when showing annotation borders.
**kwargs : additional keyword arguments
These are passed to the underlying
``mayavi.mlab.pipeline.surface`` call.
"""
hemis = self._check_hemis(hemi)
# Figure out where the data is coming from
if isinstance(annot, string_types):
if os.path.isfile(annot):
filepath = annot
path = os.path.split(filepath)[0]
file_hemi, annot = os.path.basename(filepath).split('.')[:2]
if len(hemis) > 1:
if annot[:2] == 'lh.':
filepaths = [filepath, pjoin(path, 'rh' + annot[2:])]
elif annot[:2] == 'rh.':
filepaths = [pjoin(path, 'lh' + annot[2:], filepath)]
else:
raise RuntimeError('To add both hemispheres '
'simultaneously, filename must '
'begin with "lh." or "rh."')
else:
filepaths = [filepath]
else:
filepaths = []
for hemi in hemis:
filepath = pjoin(self.subjects_dir,
self.subject_id,
'label',
".".join([hemi, annot, 'annot']))
if not os.path.exists(filepath):
raise ValueError('Annotation file %s does not exist'
% filepath)
filepaths += [filepath]
annots = []
for hemi, filepath in zip(hemis, filepaths):
# Read in the data
labels, cmap, _ = nib.freesurfer.read_annot(
filepath, orig_ids=True)
annots.append((labels, cmap))
else:
annots = [annot] if len(hemis) == 1 else annot
annot = 'annotation'
views = self._toggle_render(False)
if remove_existing:
# Get rid of any old annots
for a in self.annot_list:
a['brain']._remove_scalar_data(a['array_id'])
self.annot_list = []
for hemi, (labels, cmap) in zip(hemis, annots):
# Maybe zero-out the non-border vertices
self._to_borders(labels, hemi, borders)
# Handle null labels properly
cmap[:, 3] = 255
bgcolor = self._brain_color
bgcolor[-1] = 0
cmap[cmap[:, 4] < 0, 4] += 2 ** 24 # wrap to positive
cmap[cmap[:, 4] <= 0, :4] = bgcolor
if np.any(labels == 0) and not np.any(cmap[:, -1] <= 0):
cmap = np.vstack((cmap, np.concatenate([bgcolor, [0]])))
# Set label ids sensibly
order = np.argsort(cmap[:, -1])
cmap = cmap[order]
ids = np.searchsorted(cmap[:, -1], labels)
cmap = cmap[:, :4]
# Set the alpha level
alpha_vec = cmap[:, 3]
alpha_vec[alpha_vec > 0] = alpha * 255
# Override the cmap when a single color is used
if color is not None:
from matplotlib.colors import colorConverter
rgb = np.round(np.multiply(colorConverter.to_rgb(color), 255))
cmap[:, :3] = rgb.astype(cmap.dtype)
for brain in self._brain_list:
if brain['hemi'] == hemi:
self.annot_list.append(
brain['brain'].add_annotation(annot, ids, cmap,
**kwargs))
self._toggle_render(True, views)
def add_label(self, label, color=None, alpha=1, scalar_thresh=None,
borders=False, hemi=None, subdir=None, **kwargs):
"""Add an ROI label to the image.
Parameters
----------
label : str | instance of Label
label filepath or name. Can also be an instance of
an object with attributes "hemi", "vertices", "name", and
optionally "color" and "values" (if scalar_thresh is not None).
color : matplotlib-style color | None
anything matplotlib accepts: string, RGB, hex, etc. (default
"crimson")
alpha : float in [0, 1]
alpha level to control opacity
scalar_thresh : None or number
threshold the label ids using this value in the label
file's scalar field (i.e. label only vertices with
scalar >= thresh)
borders : bool | int
Show only label borders. If int, specify the number of steps
(away from the true border) along the cortical mesh to include
as part of the border definition.
hemi : str | None
If None, it is assumed to belong to the hemipshere being
shown. If two hemispheres are being shown, an error will
be thrown.
subdir : None | str
If a label is specified as name, subdir can be used to indicate
that the label file is in a sub-directory of the subject's
label directory rather than in the label directory itself (e.g.
for ``$SUBJECTS_DIR/$SUBJECT/label/aparc/lh.cuneus.label``
``brain.add_label('cuneus', subdir='aparc')``).
**kwargs : additional keyword arguments
These are passed to the underlying
``mayavi.mlab.pipeline.surface`` call.
Notes
-----
To remove previously added labels, run Brain.remove_labels().
"""
if isinstance(label, string_types):
hemi = self._check_hemi(hemi)
if color is None:
color = "crimson"
if os.path.isfile(label):
filepath = label
label_name = os.path.basename(filepath).split('.')[1]
else:
label_name = label
label_fname = ".".join([hemi, label_name, 'label'])
if subdir is None:
filepath = pjoin(self.subjects_dir, self.subject_id,
'label', label_fname)
else:
filepath = pjoin(self.subjects_dir, self.subject_id,
'label', subdir, label_fname)
if not os.path.exists(filepath):
raise ValueError('Label file %s does not exist'
% filepath)
# Load the label data and create binary overlay
if scalar_thresh is None:
ids = nib.freesurfer.read_label(filepath)
else:
ids, scalars = nib.freesurfer.read_label(filepath,
read_scalars=True)
ids = ids[scalars >= scalar_thresh]
else:
# try to extract parameters from label instance
try:
hemi = label.hemi
ids = label.vertices
if label.name is None:
label_name = 'unnamed'
else:
label_name = str(label.name)
if color is None:
if hasattr(label, 'color') and label.color is not None:
color = label.color
else:
color = "crimson"
if scalar_thresh is not None:
scalars = label.values
except Exception:
raise ValueError('Label was not a filename (str), and could '
'not be understood as a class. The class '
'must have attributes "hemi", "vertices", '
'"name", and (if scalar_thresh is not None)'
'"values"')
hemi = self._check_hemi(hemi)
if scalar_thresh is not None:
ids = ids[scalars >= scalar_thresh]
label = np.zeros(self.geo[hemi].coords.shape[0])
label[ids] = 1
# make sure we have a unique name
if label_name in self._label_dicts:
i = 2
name = label_name + '_%i'
while name % i in self._label_dicts:
i += 1
label_name = name % i
self._to_borders(label, hemi, borders, restrict_idx=ids)
# make a list of all the plotted labels
surfaces = []
array_ids = []
views = self._toggle_render(False)
for brain in self.brains:
if brain.hemi == hemi:
array_id, surf = brain.add_label(label, label_name, color,
alpha, **kwargs)
surfaces.append(surf)
array_ids.append((brain, array_id))
self._label_dicts[label_name] = {'surfaces': surfaces,
'array_ids': array_ids}
self._toggle_render(True, views)
def _to_borders(self, label, hemi, borders, restrict_idx=None):
"""Helper to potentially convert a label/parc to borders"""
if not isinstance(borders, (bool, int)) or borders < 0:
raise ValueError('borders must be a bool or positive integer')
if borders:
n_vertices = label.size
edges = utils.mesh_edges(self.geo[hemi].faces)
border_edges = label[edges.row] != label[edges.col]
show = np.zeros(n_vertices, dtype=np.int)
keep_idx = np.unique(edges.row[border_edges])
if isinstance(borders, int):
for _ in range(borders):
keep_idx = np.in1d(self.geo[hemi].faces.ravel(), keep_idx)
keep_idx.shape = self.geo[hemi].faces.shape
keep_idx = self.geo[hemi].faces[np.any(keep_idx, axis=1)]
keep_idx = np.unique(keep_idx)
if restrict_idx is not None:
keep_idx = keep_idx[np.in1d(keep_idx, restrict_idx)]
show[keep_idx] = 1
label *= show
def remove_data(self, hemi=None):
"""Remove data shown with ``Brain.add_data()``.
Parameters
----------
hemi : str | None
Hemisphere from which to remove data (default is all shown
hemispheres).
"""
hemis = self._check_hemis(hemi)
for hemi in hemis:
for brain in self.brains:
if brain.hemi == hemi:
for data in self._data_dicts[hemi]:
brain.remove_data(data['layer_id'])
self._data_dicts[hemi] = []
# if no data is left, reset time properties
if all(len(brain.data) == 0 for brain in self.brains):
self.n_times = self._times = None
def remove_foci(self, name=None):
"""Remove foci added with ``Brain.add_foci()``.
Parameters
----------
name : str | list of str | None
Names of the foci to remove (if None, remove all).
Notes
-----
Only foci added with a unique names can be removed.
"""
if name is None:
keys = tuple(self.foci_dict)
else:
if isinstance(name, str):
keys = (name,)
else:
keys = name
if not all(key in self.foci_dict for key in keys):
missing = ', '.join(key for key in keys if key not in
self.foci_dict)
raise ValueError("foci=%r: no foci named %s" % (name, missing))
for key in keys:
for points in self.foci_dict.pop(key):
points.remove()
def remove_labels(self, labels=None, hemi=None):
"""Remove one or more previously added labels from the image.
Parameters
----------
labels : None | str | list of str
Labels to remove. Can be a string naming a single label, or None to
remove all labels. Possible names can be found in the Brain.labels
attribute.
hemi : None
Deprecated parameter, do not use.
"""
if hemi is not None:
warn("The `hemi` parameter to Brain.remove_labels() has no effect "
"and will be removed in PySurfer 0.9", DeprecationWarning)
if labels is None:
# make list before iterating (Py3k)
labels_ = list(self._label_dicts.keys())
else:
labels_ = [labels] if isinstance(labels, str) else labels
missing = [key for key in labels_ if key not in self._label_dicts]
if missing:
raise ValueError("labels=%r contains unknown labels: %s" %
(labels, ', '.join(map(repr, missing))))
for key in labels_:
data = self._label_dicts.pop(key)
for brain, array_id in data['array_ids']:
brain._remove_scalar_data(array_id)
def add_morphometry(self, measure, grayscale=False, hemi=None,
remove_existing=True, colormap=None,
min=None, max=None, colorbar=True, **kwargs):
"""Add a morphometry overlay to the image.
Parameters
----------
measure : {'area' | 'curv' | 'jacobian_white' | 'sulc' | 'thickness'}
which measure to load
grayscale : bool
whether to load the overlay with a grayscale colormap
hemi : str | None
If None, it is assumed to belong to the hemipshere being
shown. If two hemispheres are being shown, data must exist
for both hemispheres.
remove_existing : bool
If True (default), remove old annotations.
colormap : str
Mayavi colormap name, or None to use a sensible default.
min, max : floats
Endpoints for the colormap; if not provided the robust range
of the data is used.
colorbar : bool
If True, show a colorbar corresponding to the overlay data.
**kwargs : additional keyword arguments
These are passed to the underlying
``mayavi.mlab.pipeline.surface`` call.
"""
hemis = self._check_hemis(hemi)
morph_files = []
for hemi in hemis:
# Find the source data
surf_dir = pjoin(self.subjects_dir, self.subject_id, 'surf')
morph_file = pjoin(surf_dir, '.'.join([hemi, measure]))
if not os.path.exists(morph_file):
raise ValueError(
'Could not find %s in subject directory' % morph_file)
morph_files += [morph_file]
views = self._toggle_render(False)
if remove_existing is True:
# Get rid of any old overlays
for m in self.morphometry_list:
if m["colorbar"] is not None:
m['colorbar'].visible = False
m['brain']._remove_scalar_data(m['array_id'])
self.morphometry_list = []
for hemi, morph_file in zip(hemis, morph_files):
if colormap is None:
# Preset colormaps
if grayscale:
colormap = "gray"
else:
colormap = dict(area="pink",
curv="RdBu",
jacobian_white="pink",
sulc="RdBu",
thickness="pink")[measure]
# Read in the morphometric data
morph_data = nib.freesurfer.read_morph_data(morph_file)
# Get a cortex mask for robust range
self.geo[hemi].load_label("cortex")
ctx_idx = self.geo[hemi].labels["cortex"]
# Get the display range
min_default, max_default = np.percentile(morph_data[ctx_idx],
[2, 98])
if min is None:
min = min_default
if max is None:
max = max_default
# Use appropriate values for bivariate measures
if measure in ["curv", "sulc"]:
lim = np.max([abs(min), abs(max)])
min, max = -lim, lim
# Set up the Mayavi pipeline
morph_data = _prepare_data(morph_data)
for brain in self.brains:
if brain.hemi == hemi:
self.morphometry_list.append(brain.add_morphometry(
morph_data, colormap, measure, min, max, colorbar,
**kwargs))
self._toggle_render(True, views)
def add_foci(self, coords, coords_as_verts=False, map_surface=None,
scale_factor=1, color="white", alpha=1, name=None,
hemi=None, **kwargs):
"""Add spherical foci, possibly mapping to displayed surf.
The foci spheres can be displayed at the coordinates given, or
mapped through a surface geometry. In other words, coordinates
from a volume-based analysis in MNI space can be displayed on an
inflated average surface by finding the closest vertex on the
white surface and mapping to that vertex on the inflated mesh.
Parameters
----------
coords : numpy array
x, y, z coordinates in stereotaxic space (default) or array of
vertex ids (with ``coord_as_verts=True``)
coords_as_verts : bool
whether the coords parameter should be interpreted as vertex ids
map_surface : Freesurfer surf or None
surface to map coordinates through, or None to use raw coords
scale_factor : float
Controls the size of the foci spheres (relative to 1cm).
color : matplotlib color code
HTML name, RBG tuple, or hex code
alpha : float in [0, 1]
opacity of focus gylphs
name : str
internal name to use
hemi : str | None
If None, it is assumed to belong to the hemipshere being
shown. If two hemispheres are being shown, an error will
be thrown.
**kwargs : additional keyword arguments
These are passed to the underlying
:func:`mayavi.mlab.points3d` call.
"""
from matplotlib.colors import colorConverter
hemi = self._check_hemi(hemi)
# Figure out how to interpret the first parameter
if coords_as_verts:
coords = self.geo[hemi].coords[coords]
map_surface = None
# Possibly map the foci coords through a surface
if map_surface is None:
foci_coords = np.atleast_2d(coords)
else:
foci_surf = Surface(self.subject_id, hemi, map_surface,
subjects_dir=self.subjects_dir,
units=self._units)
foci_surf.load_geometry()
foci_vtxs = utils.find_closest_vertices(foci_surf.coords, coords)
foci_coords = self.geo[hemi].coords[foci_vtxs]
# Get a unique name (maybe should take this approach elsewhere)
if name is None:
name = "foci_%d" % (len(self.foci_dict) + 1)
# Convert the color code
if not isinstance(color, tuple):
color = colorConverter.to_rgb(color)
views = self._toggle_render(False)
fl = []
if self._units == 'm':
scale_factor = scale_factor / 1000.
for brain in self._brain_list:
if brain['hemi'] == hemi:
fl.append(brain['brain'].add_foci(foci_coords, scale_factor,
color, alpha, name,
**kwargs))
self.foci_dict[name] = fl
self._toggle_render(True, views)
def add_contour_overlay(self, source, min=None, max=None,
n_contours=7, line_width=1.5, colormap="YlOrRd_r",
hemi=None, remove_existing=True, colorbar=True,
**kwargs):
"""Add a topographic contour overlay of the positive data.
Note: This visualization will look best when using the "low_contrast"
cortical curvature colorscheme.
Parameters
----------
source : str or array
path to the overlay file or numpy array
min : float
threshold for overlay display
max : float
saturation point for overlay display
n_contours : int
number of contours to use in the display
line_width : float
width of contour lines
colormap : string, list of colors, or array
name of matplotlib colormap to use, a list of matplotlib colors,
or a custom look up table (an n x 4 array coded with RBGA values
between 0 and 255).
hemi : str | None
If None, it is assumed to belong to the hemipshere being
shown. If two hemispheres are being shown, an error will
be thrown.
remove_existing : bool
If there is an existing contour overlay, remove it before plotting.
colorbar : bool
If True, show the colorbar for the scalar value.
**kwargs : additional keyword arguments
These are passed to the underlying
``mayavi.mlab.pipeline.contour_surface`` call.
"""
hemi = self._check_hemi(hemi)
# Read the scalar data
scalar_data, _ = self._read_scalar_data(source, hemi)
min, max = self._get_display_range(scalar_data, min, max, "pos")
# Deal with Mayavi bug
scalar_data = _prepare_data(scalar_data)
# Maybe get rid of an old overlay
if remove_existing:
for c in self.contour_list:
if c['colorbar'] is not None:
c['colorbar'].visible = False
c['brain']._remove_scalar_data(c['array_id'])
self.contour_list = []
# Process colormap argument into a lut
lut = create_color_lut(colormap)
views = self._toggle_render(False)
for brain in self.brains:
if brain.hemi == hemi:
self.contour_list.append(brain.add_contour_overlay(
scalar_data, min, max, n_contours, line_width, lut,
colorbar, **kwargs))
self._toggle_render(True, views)
def add_text(self, x, y, text, name, color=None, opacity=1.0,
row=-1, col=-1, font_size=None, justification=None, **kwargs):
""" Add a text to the visualization
Parameters
----------
x : Float
x coordinate
y : Float
y coordinate
text : str
Text to add
name : str
Name of the text (text label can be updated using update_text())
color : Tuple
Color of the text. Default is the foreground color set during
initialization (default is black or white depending on the
background color).
opacity : Float
Opacity of the text. Default: 1.0
row : int
Row index of which brain to use
col : int
Column index of which brain to use
**kwargs : additional keyword arguments
These are passed to the underlying
:func:`mayavi.mlab.text3d` call.
"""
if name in self.texts_dict:
self.texts_dict[name]['text'].remove()
text = self.brain_matrix[row, col].add_text(x, y, text,
name, color, opacity,
**kwargs)
self.texts_dict[name] = dict(row=row, col=col, text=text)
if font_size is not None:
text.property.font_size = font_size
text.actor.text_scale_mode = 'viewport'
if justification is not None:
text.property.justification = justification
def update_text(self, text, name, row=-1, col=-1):
"""Update text label
Parameters
----------
text : str
New text for label
name : str
Name of text label
"""
if name not in self.texts_dict:
raise KeyError('text name "%s" unknown' % name)
self.texts_dict[name]['text'].text = text
###########################################################################
# DATA SCALING / DISPLAY
def reset_view(self):
"""Orient camera to display original view
"""
for view, brain in zip(self._original_views, self._brain_list):
brain['brain'].show_view(view)
def show_view(self, view=None, roll=None, distance=None, row=-1, col=-1):
"""Orient camera to display view
Parameters
----------
view : str | dict
brain surface to view (one of 'lateral', 'medial', 'rostral',
'caudal', 'dorsal', 'ventral', 'frontal', 'parietal') or kwargs to
pass to :func:`mayavi.mlab.view()`.
roll : float
camera roll
distance : float | 'auto' | None
distance from the origin
row : int
Row index of which brain to use
col : int
Column index of which brain to use
Returns
-------
view : tuple
tuple returned from mlab.view
roll : float
camera roll returned from mlab.roll
"""
return self.brain_matrix[row][col].show_view(view, roll, distance)
def set_distance(self, distance=None):
"""Set view distances for all brain plots to the same value
Parameters
----------
distance : float | None
Distance to use. If None, brains are set to the farthest
"best fit" distance across all current views; note that
the underlying "best fit" function can be buggy.
Returns
-------
distance : float
The distance used.
"""
if distance is None:
distance = []
for ff in self._figures:
for f in ff:
mlab.view(figure=f, distance='auto')
v = mlab.view(figure=f)
# This should only happen for the test backend
if v is None:
v = [0, 0, 100]
distance += [v[2]]
distance = max(distance)
for ff in self._figures:
for f in ff:
mlab.view(distance=distance, figure=f)
return distance
def set_surf(self, surf):
"""Change the surface geometry
Parameters
----------
surf : str
freesurfer surface mesh name (ie 'white', 'inflated', etc.)
"""
if self.surf == surf:
return
views = self._toggle_render(False)
# load new geometry
for geo in self.geo.values():
try:
geo.surf = surf
geo.load_geometry()
except IOError: # surface file does not exist
geo.surf = self.surf
self._toggle_render(True)
raise
# update mesh objects (they use a reference to geo.coords)
for brain in self.brains:
brain._geo_mesh.data.points = self.geo[brain.hemi].coords
brain.update_surf()
self.surf = surf
self._toggle_render(True, views)
for brain in self.brains:
if brain._f.scene is not None:
brain._f.scene.reset_zoom()
@property
def _brain_color(self):
geo_actor = self._brain_list[0]['brain']._geo_surf.actor
if self._brain_list[0]['brain']._using_lut:
bgcolor = np.mean(
self._brain_list[0]['brain']._geo_surf.module_manager
.scalar_lut_manager.lut.table.to_array(), axis=0)
else:
bgcolor = geo_actor.property.color
if len(bgcolor) == 3:
bgcolor = bgcolor + (1,)
bgcolor = 255 * np.array(bgcolor)
bgcolor[-1] *= geo_actor.property.opacity
return bgcolor
@verbose
def scale_data_colormap(self, fmin, fmid, fmax, transparent,
center=None, alpha=1.0, data=None,
hemi=None, verbose=None):
"""Scale the data colormap.
The colormap may be sequential or divergent. When the colormap is
divergent indicate this by providing a value for 'center'. The
meanings of fmin, fmid and fmax are different for sequential and
divergent colormaps. For sequential colormaps the colormap is
characterised by::
[fmin, fmid, fmax]
where fmin and fmax define the edges of the colormap and fmid will be
the value mapped to the center of the originally chosen colormap. For
divergent colormaps the colormap is characterised by::
[center-fmax, center-fmid, center-fmin, center,
center+fmin, center+fmid, center+fmax]
i.e., values between center-fmin and center+fmin will not be shown
while center-fmid will map to the middle of the first half of the
original colormap and center-fmid to the middle of the second half.
Parameters
----------
fmin : float
minimum value for colormap
fmid : float
value corresponding to color midpoint
fmax : float
maximum value for colormap
transparent : boolean
if True: use a linear transparency between fmin and fmid and make
values below fmin fully transparent (symmetrically for divergent
colormaps)
center : float
if not None, gives the data value that should be mapped to the
center of the (divergent) colormap
alpha : float
sets the overall opacity of colors, maintains transparent regions
data : dict | None
The data entry for which to scale the colormap.
If None, will use the data dict from either the left or right
hemisphere (in that order).
hemi : str | None
If None, all hemispheres will be scaled.
verbose : bool, str, int, or None
If not None, override default verbose level (see surfer.verbose).
"""
divergent = center is not None
hemis = self._check_hemis(hemi)
del hemi
# Get the original colormap
if data is None:
for hemi in hemis:
data = self.data_dict[hemi]
if data is not None:
break
table = data["orig_ctable"].copy()
lut = _scale_mayavi_lut(table, fmin, fmid, fmax, transparent,
center, alpha)
# Get the effective background color as 255-based 4-element array
bgcolor = self._brain_color
views = self._toggle_render(False)
# Use the new colormap
for hemi in hemis:
data = self.data_dict[hemi]
if data is not None:
for surf in data['surfaces']:
cmap = surf.module_manager.scalar_lut_manager
cmap.load_lut_from_list(lut / 255.)
if divergent:
cmap.data_range = np.array(
[center - fmax, center + fmax])
else:
cmap.data_range = np.array([fmin, fmax])
# if there is any transparent color in the lut
if np.any(lut[:, -1] < 255):
# Update the colorbar to deal with transparency
cbar_lut = tvtk.LookupTable()
cbar_lut.deep_copy(surf.module_manager
.scalar_lut_manager.lut)
alphas = lut[:, -1][:, np.newaxis] / 255.
use_lut = lut.copy()
use_lut[:, -1] = 255.
vals = (use_lut * alphas) + bgcolor * (1 - alphas)
cbar_lut.table.from_array(vals)
cmap.scalar_bar.lookup_table = cbar_lut
cmap.scalar_bar.use_opacity = 1
# Update the data properties
data.update(fmin=fmin, fmid=fmid, fmax=fmax, center=center,
transparent=transparent)
# And the hemisphere properties to match
for glyph in data['glyphs']:
if glyph is not None:
l_m = glyph.parent.vector_lut_manager
l_m.load_lut_from_list(lut / 255.)
if divergent:
l_m.data_range = np.array(
[center - fmax, center + fmax])
else:
l_m.data_range = np.array([fmin, fmax])
self._toggle_render(True, views)
def set_data_time_index(self, time_idx, interpolation='quadratic'):
"""Set the data time index to show
Parameters
----------
time_idx : int | float
Time index. Non-integer values will be displayed using
interpolation between samples.
interpolation : str
Interpolation method (``scipy.interpolate.interp1d`` parameter,
one of 'linear' | 'nearest' | 'zero' | 'slinear' | 'quadratic' |
'cubic', default 'quadratic'). Interpolation is only used for
non-integer indexes.
"""
from scipy.interpolate import interp1d
if self.n_times is None:
raise RuntimeError('cannot set time index with no time data')
if time_idx < 0 or time_idx >= self.n_times:
raise ValueError("time index out of range")
views = self._toggle_render(False)
for hemi in ['lh', 'rh']:
for data in self._data_dicts[hemi]:
if data['array'].ndim == 1:
continue # skip data without time axis
# interpolation
if data['array'].ndim == 2:
scalar_data = data['array']
vectors = None
else:
scalar_data = data['magnitude']
vectors = data['array']
if isinstance(time_idx, float):
times = np.arange(self.n_times)
scalar_data = interp1d(
times, scalar_data, interpolation, axis=1,
assume_sorted=True)(time_idx)
if vectors is not None:
vectors = interp1d(
times, vectors, interpolation, axis=2,
assume_sorted=True)(time_idx)
else:
scalar_data = scalar_data[:, time_idx]
if vectors is not None:
vectors = vectors[:, :, time_idx]
if data['smooth_mat'] is not None:
scalar_data = data['smooth_mat'] * scalar_data
for brain in self.brains:
if brain.hemi == hemi:
brain.set_data(data['layer_id'], scalar_data, vectors)
del brain
data["time_idx"] = time_idx
# Update time label
if data["time_label"]:
if isinstance(time_idx, float):
ifunc = interp1d(times, data['time'])
time = ifunc(time_idx)
else:
time = data["time"][time_idx]
self.update_text(data["time_label"](time), "time_label")
self._toggle_render(True, views)
@property
def data_time_index(self):
"""Retrieve the currently displayed data time index
Returns
-------
time_idx : int
Current time index.
Notes
-----
Raises a RuntimeError if the Brain instance has not data overlay.
"""
for hemi in ['lh', 'rh']:
data = self.data_dict[hemi]
if data is not None:
time_idx = data["time_idx"]
return time_idx
raise RuntimeError("Brain instance has no data overlay")
@verbose
def set_data_smoothing_steps(self, smoothing_steps=20, verbose=None):
"""Set the number of smoothing steps
Parameters
----------
smoothing_steps : int | str | None
Number of smoothing steps (if data come from surface subsampling).
Can be None to use the fewest steps that result in all vertices
taking on data values, or "nearest" such that each high resolution
vertex takes the value of the its nearest (on the sphere)
low-resolution vertex. Default is 20.
verbose : bool, str, int, or None
If not None, override default verbose level (see surfer.verbose).
"""
views = self._toggle_render(False)
for hemi in ['lh', 'rh']:
data = self.data_dict[hemi]
if data is not None:
adj_mat = utils.mesh_edges(self.geo[hemi].faces)
smooth_mat = utils.smoothing_matrix(data["vertices"],
adj_mat, smoothing_steps)
data["smooth_mat"] = smooth_mat
# Redraw
if data["array"].ndim == 1:
plot_data = data["array"]
elif data["array"].ndim == 2:
plot_data = data["array"][:, data["time_idx"]]
else: # vector-valued
plot_data = data["magnitude"][:, data["time_idx"]]
plot_data = data["smooth_mat"] * plot_data
for brain in self.brains:
if brain.hemi == hemi:
brain.set_data(data['layer_id'], plot_data)
# Update data properties
data["smoothing_steps"] = smoothing_steps
self._toggle_render(True, views)
def index_for_time(self, time, rounding='closest'):
"""Find the data time index closest to a specific time point.
Parameters
----------
time : scalar
Time.
rounding : 'closest' | 'up' | 'down'
How to round if the exact time point is not an index.
Returns
-------
index : int
Data time index closest to time.
"""
if self.n_times is None:
raise RuntimeError("Brain has no time axis")
times = self._times
# Check that time is in range
tmin = np.min(times)
tmax = np.max(times)
max_diff = (tmax - tmin) / (len(times) - 1) / 2
if time < tmin - max_diff or time > tmax + max_diff:
err = ("time = %s lies outside of the time axis "
"[%s, %s]" % (time, tmin, tmax))
raise ValueError(err)
if rounding == 'closest':
idx = np.argmin(np.abs(times - time))
elif rounding == 'up':
idx = np.nonzero(times >= time)[0][0]
elif rounding == 'down':
idx = np.nonzero(times <= time)[0][-1]
else:
err = "Invalid rounding parameter: %s" % repr(rounding)
raise ValueError(err)
return idx
def set_time(self, time):
"""Set the data time index to the time point closest to time
Parameters
----------
time : scalar
Time.
"""
idx = self.index_for_time(time)
self.set_data_time_index(idx)
def _get_colorbars(self, row, col):
shape = self.brain_matrix.shape
row = row % shape[0]
col = col % shape[1]
ind = np.ravel_multi_index((row, col), self.brain_matrix.shape)
colorbars = []
h = self._brain_list[ind]['hemi']
if self.data_dict[h] is not None and 'colorbars' in self.data_dict[h]:
colorbars.append(self.data_dict[h]['colorbars'][row])
if len(self.morphometry_list) > 0:
colorbars.append(self.morphometry_list[ind]['colorbar'])
if len(self.contour_list) > 0:
colorbars.append(self.contour_list[ind]['colorbar'])
if len(self.overlays_dict) > 0:
for name, obj in self.overlays_dict.items():
for bar in ["pos_bar", "neg_bar"]:
try: # deal with positive overlays
this_ind = min(len(obj) - 1, ind)
colorbars.append(getattr(obj[this_ind], bar))
except AttributeError:
pass
return colorbars
def _colorbar_visibility(self, visible, row, col):
for cb in self._get_colorbars(row, col):
if cb is not None:
cb.visible = visible
def show_colorbar(self, row=-1, col=-1):
"""Show colorbar(s) for given plot
Parameters
----------
row : int
Row index of which brain to use
col : int
Column index of which brain to use
"""
self._colorbar_visibility(True, row, col)
def hide_colorbar(self, row=-1, col=-1):
"""Hide colorbar(s) for given plot
Parameters
----------
row : int
Row index of which brain to use
col : int
Column index of which brain to use
"""
self._colorbar_visibility(False, row, col)
def close(self):
"""Close all figures and cleanup data structure."""
self._close()
def _close(self, force_render=True):
for ri, ff in enumerate(getattr(self, '_figures', [])):
for ci, f in enumerate(ff):
if f is not None:
try:
mlab.close(f)
except Exception:
pass
self._figures[ri][ci] = None
if force_render:
_force_render([])
# should we tear down other variables?
if getattr(self, '_v', None) is not None:
try:
self._v.dispose()
except Exception:
pass
self._v = None
def __del__(self):
# Forcing the GUI updates during GC seems to be problematic
self._close(force_render=False)
###########################################################################
# SAVING OUTPUT
def save_single_image(self, filename, row=-1, col=-1):
"""Save view from one panel to disk
Only mayavi image types are supported:
(png jpg bmp tiff ps eps pdf rib oogl iv vrml obj
Parameters
----------
filename: string
path to new image file
row : int
row index of the brain to use
col : int
column index of the brain to use
Due to limitations in TraitsUI, if multiple views or hemi='split'
is used, there is no guarantee painting of the windows will
complete before control is returned to the command line. Thus
we strongly recommend using only one figure window (which uses
a Mayavi figure to plot instead of TraitsUI) if you intend to
script plotting commands.
"""
brain = self.brain_matrix[row, col]
ftype = filename[filename.rfind('.') + 1:]
good_ftypes = ['png', 'jpg', 'bmp', 'tiff', 'ps',
'eps', 'pdf', 'rib', 'oogl', 'iv', 'vrml', 'obj']
if ftype not in good_ftypes:
raise ValueError("Supported image types are %s"
% " ".join(good_ftypes))
mlab.draw(brain._f)
if mlab.options.backend != 'test':
mlab.savefig(filename, figure=brain._f)
def _screenshot_figure(self, mode='rgb', antialiased=False):
"""Create a matplolib figure from the current screenshot."""
# adapted from matplotlib.image.imsave
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
fig = Figure(frameon=False)
FigureCanvasAgg(fig)
fig.figimage(self.screenshot(mode, antialiased), resize=True)
return fig
def save_image(self, filename, mode='rgb', antialiased=False):
"""Save view from all panels to disk
Only mayavi image types are supported:
(png jpg bmp tiff ps eps pdf rib oogl iv vrml obj
Parameters
----------
filename: string
path to new image file
mode : string
Either 'rgb' (default) to render solid background, or 'rgba' to
include alpha channel for transparent background.
antialiased : bool
Antialias the image (see :func:`mayavi.mlab.screenshot`
for details; see default False).
Notes
-----
Due to limitations in TraitsUI, if multiple views or hemi='split'
is used, there is no guarantee painting of the windows will
complete before control is returned to the command line. Thus
we strongly recommend using only one figure window (which uses
a Mayavi figure to plot instead of TraitsUI) if you intend to
script plotting commands.
"""
self._screenshot_figure(mode, antialiased).savefig(filename)
def screenshot(self, mode='rgb', antialiased=False):
"""Generate a screenshot of current view.
Wraps to :func:`mayavi.mlab.screenshot` for ease of use.
Parameters
----------
mode : string
Either 'rgb' or 'rgba' for values to return.
antialiased : bool
Antialias the image (see :func:`mayavi.mlab.screenshot`
for details; default False).
Returns
-------
screenshot : array
Image pixel values.
Notes
-----
Due to limitations in TraitsUI, if multiple views or ``hemi='split'``
is used, there is no guarantee painting of the windows will
complete before control is returned to the command line. Thus
we strongly recommend using only one figure window (which uses
a Mayavi figure to plot instead of TraitsUI) if you intend to
script plotting commands.
"""
row = []
for ri in range(self.brain_matrix.shape[0]):
col = []
n_col = 2 if self._hemi == 'split' else 1
for ci in range(n_col):
col += [self.screenshot_single(mode, antialiased,
ri, ci)]
row += [np.concatenate(col, axis=1)]
data = np.concatenate(row, axis=0)
return data
def screenshot_single(self, mode='rgb', antialiased=False, row=-1, col=-1):
"""Generate a screenshot of current view from a single panel.
Wraps to :func:`mayavi.mlab.screenshot` for ease of use.
Parameters
----------
mode: string
Either 'rgb' or 'rgba' for values to return
antialiased: bool
Antialias the image (see :func:`mayavi.mlab.screenshot`
for details).
row : int
row index of the brain to use
col : int
column index of the brain to use
Returns
-------
screenshot: array
Image pixel values
Notes
-----
Due to limitations in TraitsUI, if multiple views or hemi='split'
is used, there is no guarantee painting of the windows will
complete before control is returned to the command line. Thus
we strongly recommend using only one figure window (which uses
a Mayavi figure to plot instead of TraitsUI) if you intend to
script plotting commands.
"""
brain = self.brain_matrix[row, col]
if mlab.options.backend != 'test':
return mlab.screenshot(brain._f, mode, antialiased)
else:
out = np.ones(tuple(self._scene_size) + (3,), np.uint8)
out[0, 0, 0] = 0
return out
def save_imageset(self, prefix, views, filetype='png', colorbar='auto',
row=-1, col=-1):
"""Convenience wrapper for save_image
Files created are prefix+'_$view'+filetype
Parameters
----------
prefix: string | None
filename prefix for image to be created. If None, a list of
arrays representing images is returned (not saved to disk).
views: list
desired views for images
filetype: string
image type
colorbar: 'auto' | int | list of int | None
For 'auto', the colorbar is shown in the middle view (default).
For int or list of int, the colorbar is shown in the specified
views. For ``None``, no colorbar is shown.
row : int
row index of the brain to use
col : int
column index of the brain to use
Returns
-------
images_written: list
all filenames written
"""
if isinstance(views, string_types):
raise ValueError("Views must be a non-string sequence"
"Use show_view & save_image for a single view")
if colorbar == 'auto':
colorbar = [len(views) // 2]
elif isinstance(colorbar, int):
colorbar = [colorbar]
images_written = []
for iview, view in enumerate(views):
try:
if colorbar is not None and iview in colorbar:
self.show_colorbar(row, col)
else:
self.hide_colorbar(row, col)
self.show_view(view, row=row, col=col)
if prefix is not None:
fname = "%s_%s.%s" % (prefix, view, filetype)
images_written.append(fname)
self.save_single_image(fname, row, col)
else:
images_written.append(self.screenshot_single(row=row,
col=col))
except ValueError:
print("Skipping %s: not in view dict" % view)
return images_written
def save_image_sequence(self, time_idx, fname_pattern, use_abs_idx=True,
row=-1, col=-1, montage='single', border_size=15,
colorbar='auto', interpolation='quadratic'):
"""Save a temporal image sequence
The files saved are named ``fname_pattern % pos`` where ``pos`` is a
relative or absolute index (controlled by ``use_abs_idx``).
Parameters
----------
time_idx : array_like
Time indices to save. Non-integer values will be displayed using
interpolation between samples.
fname_pattern : str
Filename pattern, e.g. 'movie-frame_%0.4d.png'.
use_abs_idx : bool
If True the indices given by ``time_idx`` are used in the filename
if False the index in the filename starts at zero and is
incremented by one for each image (Default: True).
row : int
Row index of the brain to use.
col : int
Column index of the brain to use.
montage : 'current' | 'single' | list
Views to include in the images: 'current' uses the currently
displayed image; 'single' (default) uses a single view, specified
by the ``row`` and ``col`` parameters; a 1 or 2 dimensional list
can be used to specify a complete montage. Examples:
``['lat', 'med']`` lateral and ventral views ordered horizontally;
``[['fro'], ['ven']]`` frontal and ventral views ordered
vertically.
border_size : int
Size of image border (more or less space between images).
colorbar : 'auto' | int | list of int | None
For 'auto', the colorbar is shown in the middle view (default).
For int or list of int, the colorbar is shown in the specified
views. For ``None``, no colorbar is shown.
interpolation : str
Interpolation method (``scipy.interpolate.interp1d`` parameter,
one of 'linear' | 'nearest' | 'zero' | 'slinear' | 'quadratic' |
'cubic', default 'quadratic'). Interpolation is only used for
non-integer indexes.
Returns
-------
images_written : list
All filenames written.
"""
images_written = list()
for i, idx in enumerate(self._iter_time(time_idx, interpolation)):
fname = fname_pattern % (idx if use_abs_idx else i)
if montage == 'single':
self.save_single_image(fname, row, col)
elif montage == 'current':
self.save_image(fname)
else:
self.save_montage(fname, montage, 'h', border_size, colorbar,
row, col)
images_written.append(fname)
return images_written
def save_montage(self, filename, order=['lat', 'ven', 'med'],
orientation='h', border_size=15, colorbar='auto',
row=-1, col=-1):
"""Create a montage from a given order of images
Parameters
----------
filename: string | None
path to final image. If None, the image will not be saved.
order: list
list of views: order of views to build montage (default
``['lat', 'ven', 'med']``; nested list of views to specify
views in a 2-dimensional grid (e.g,
``[['lat', 'ven'], ['med', 'fro']]``)
orientation: {'h' | 'v'}
montage image orientation (horizontal of vertical alignment; only
applies if ``order`` is a flat list)
border_size: int
Size of image border (more or less space between images)
colorbar: 'auto' | int | list of int | None
For 'auto', the colorbar is shown in the middle view (default).
For int or list of int, the colorbar is shown in the specified
views. For ``None``, no colorbar is shown.
row : int
row index of the brain to use
col : int
column index of the brain to use
Returns
-------
out : array
The montage image, usable with :func:`matplotlib.pyplot.imshow`.
"""
# find flat list of views and nested list of view indexes
assert orientation in ['h', 'v']
if isinstance(order, (str, dict)):
views = [order]
elif all(isinstance(x, (str, dict)) for x in order):
views = order
else:
views = []
orientation = []
for row_order in order:
if isinstance(row_order, (str, dict)):
orientation.append([len(views)])
views.append(row_order)
else:
orientation.append([])
for view in row_order:
orientation[-1].append(len(views))
views.append(view)
if colorbar == 'auto':
colorbar = [len(views) // 2]
elif isinstance(colorbar, int):
colorbar = [colorbar]
brain = self.brain_matrix[row, col]
# store current view + colorbar visibility
with warnings.catch_warnings(record=True): # traits focalpoint
current_view = mlab.view(figure=brain._f)
colorbars = self._get_colorbars(row, col)
colorbars_visibility = dict()
for cb in colorbars:
if cb is not None:
colorbars_visibility[cb] = cb.visible
images = self.save_imageset(None, views, colorbar=colorbar, row=row,
col=col)
out = make_montage(filename, images, orientation, colorbar,
border_size)
# get back original view and colorbars
if current_view is not None: # can be None with test backend
with warnings.catch_warnings(record=True): # traits focalpoint
mlab.view(*current_view, figure=brain._f)
for cb in colorbars:
if cb is not None:
cb.visible = colorbars_visibility[cb]
return out
def save_movie(self, fname, time_dilation=4., tmin=None, tmax=None,
framerate=24, interpolation='quadratic', codec=None,
bitrate=None, **kwargs):
"""Save a movie (for data with a time axis)
The movie is created through the :mod:`imageio` module. The format is
determined by the extension, and additional options can be specified
through keyword arguments that depend on the format. For available
formats and corresponding parameters see the imageio documentation:
http://imageio.readthedocs.io/en/latest/formats.html#multiple-images
.. Warning::
This method assumes that time is specified in seconds when adding
data. If time is specified in milliseconds this will result in
movies 1000 times longer than expected.
Parameters
----------
fname : str
Path at which to save the movie. The extension determines the
format (e.g., `'*.mov'`, `'*.gif'`, ...; see the :mod:`imageio`
documenttion for available formats).
time_dilation : float
Factor by which to stretch time (default 4). For example, an epoch
from -100 to 600 ms lasts 700 ms. With ``time_dilation=4`` this
would result in a 2.8 s long movie.
tmin : float
First time point to include (default: all data).
tmax : float
Last time point to include (default: all data).
framerate : float
Framerate of the movie (frames per second, default 24).
interpolation : str
Interpolation method (``scipy.interpolate.interp1d`` parameter,
one of 'linear' | 'nearest' | 'zero' | 'slinear' | 'quadratic' |
'cubic', default 'quadratic').
**kwargs :
Specify additional options for :mod:`imageio`.
Notes
-----
Requires imageio package, which can be installed together with
PySurfer with::
$ pip install -U pysurfer[save_movie]
"""
try:
import imageio
except ImportError:
raise ImportError("Saving movies from PySurfer requires the "
"imageio library. To install imageio with pip, "
"run\n\n $ pip install imageio\n\nTo "
"install/update PySurfer and imageio together, "
"run\n\n $ pip install -U "
"pysurfer[save_movie]\n")
from scipy.interpolate import interp1d
# find imageio FFMPEG parameters
if 'fps' not in kwargs:
kwargs['fps'] = framerate
if codec is not None:
kwargs['codec'] = codec
if bitrate is not None:
kwargs['bitrate'] = bitrate
# find tmin
if tmin is None:
tmin = self._times[0]
elif tmin < self._times[0]:
raise ValueError("tmin=%r is smaller than the first time point "
"(%r)" % (tmin, self._times[0]))
# find indexes at which to create frames
if tmax is None:
tmax = self._times[-1]
elif tmax > self._times[-1]:
raise ValueError("tmax=%r is greater than the latest time point "
"(%r)" % (tmax, self._times[-1]))
n_frames = floor((tmax - tmin) * time_dilation * framerate)
times = np.arange(n_frames, dtype=float)
times /= framerate * time_dilation
times += tmin
interp_func = interp1d(self._times, np.arange(self.n_times))
time_idx = interp_func(times)
n_times = len(time_idx)
if n_times == 0:
raise ValueError("No time points selected")
logger.debug("Save movie for time points/samples\n%s\n%s"
% (times, time_idx))
# Sometimes the first screenshot is rendered with a different
# resolution on OS X
self.screenshot()
images = [self.screenshot() for _ in
self._iter_time(time_idx, interpolation)]
imageio.mimwrite(fname, images, **kwargs)
def animate(self, views, n_steps=180., fname=None, use_cache=False,
row=-1, col=-1):
"""Animate a rotation.
Currently only rotations through the axial plane are allowed.
Parameters
----------
views: sequence
views to animate through
n_steps: float
number of steps to take in between
fname: string
If not None, it saves the animation as a movie.
fname should end in '.avi' as only the AVI format is supported
use_cache: bool
Use previously generated images in ``./.tmp/``
row : int
Row index of the brain to use
col : int
Column index of the brain to use
"""
brain = self.brain_matrix[row, col]
gviews = list(map(brain._xfm_view, views))
allowed = ('lateral', 'caudal', 'medial', 'rostral')
if not len([v for v in gviews if v in allowed]) == len(gviews):
raise ValueError('Animate through %s views.' % ' '.join(allowed))
if fname is not None:
if not fname.endswith('.avi'):
raise ValueError('Can only output to AVI currently.')
tmp_dir = './.tmp'
tmp_fname = pjoin(tmp_dir, '%05d.png')
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
for i, beg in enumerate(gviews):
try:
end = gviews[i + 1]
dv, dr = brain._min_diff(beg, end)
dv /= np.array((n_steps))
dr /= np.array((n_steps))
brain.show_view(beg)
for i in range(int(n_steps)):
brain._f.scene.camera.orthogonalize_view_up()
brain._f.scene.camera.azimuth(dv[0])
brain._f.scene.camera.elevation(dv[1])
brain._f.scene.renderer.reset_camera_clipping_range()
_force_render([[brain._f]])
if fname is not None:
if not (os.path.isfile(tmp_fname % i) and use_cache):
self.save_single_image(tmp_fname % i, row, col)
except IndexError:
pass
if fname is not None:
fps = 10
# we'll probably want some config options here
enc_cmd = " ".join(["mencoder",
"-ovc lavc",
"-mf fps=%d" % fps,
"mf://%s" % tmp_fname,
"-of avi",
"-lavcopts vcodec=mjpeg",
"-ofps %d" % fps,
"-noskip",
"-o %s" % fname])
ret = os.system(enc_cmd)
if ret:
print("\n\nError occured when exporting movie\n\n")
def __repr__(self):
return ('<Brain subject_id="%s", hemi="%s", surf="%s">' %
(self.subject_id, self._hemi, self.surf))
def _ipython_display_(self):
"""Called by Jupyter notebook to display a brain."""
from IPython.display import display as idisplay
if mlab.options.offscreen:
# Render the mayavi scenes to the notebook
for figure in self._figures:
for scene in figure:
idisplay(scene.scene)
else:
# Render string representation
print(repr(self))
def _scale_sequential_lut(lut_table, fmin, fmid, fmax):
"""Scale a sequential colormap."""
lut_table_new = lut_table.copy()
n_colors = lut_table.shape[0]
n_colors2 = n_colors // 2
# Index of fmid in new colorbar (which position along the N colors would
# fmid take, if fmin is first and fmax is last?)
fmid_idx = int(np.round(n_colors * ((fmid - fmin) /
(fmax - fmin))) - 1)
# morph each color channel so that fmid gets assigned the middle color of
# the original table and the number of colors to the left and right are
# stretched or squeezed such that they correspond to the distance of fmid
# to fmin and fmax, respectively
for i in range(4):
part1 = np.interp(np.linspace(0, n_colors2 - 1, fmid_idx + 1),
np.arange(n_colors),
lut_table[:, i])
lut_table_new[:fmid_idx + 1, i] = part1
part2 = np.interp(np.linspace(n_colors2, n_colors - 1,
n_colors - fmid_idx - 1),
np.arange(n_colors),
lut_table[:, i])
lut_table_new[fmid_idx + 1:, i] = part2
return lut_table_new
def _check_limits(fmin, fmid, fmax, extra='f'):
"""Check for monotonicity."""
if fmin >= fmid:
raise ValueError('%smin must be < %smid, got %0.4g >= %0.4g'
% (extra, extra, fmin, fmid))
if fmid >= fmax:
raise ValueError('%smid must be < %smax, got %0.4g >= %0.4g'
% (extra, extra, fmid, fmax))
def _get_fill_colors(cols, n_fill):
"""Get the fill colors for the middle of divergent colormaps.
Tries to figure out whether there is a smooth transition in the center of
the original colormap. If yes, it chooses the color in the center as the
only fill color, else it chooses the two colors between which there is
a large step in color space to fill up the middle of the new colormap.
"""
steps = np.linalg.norm(np.diff(cols[:, :3].astype(float), axis=0), axis=1)
# if there is a jump in the middle of the colors
# (define a jump as a step in 3D colorspace whose size is 3-times larger
# than the mean step size between the first and last steps of the given
# colors - I verified that no such jumps exist in the divergent colormaps
# of matplotlib 2.0 which all have a smooth transition in the middle)
ind = np.flatnonzero(steps[1:-1] > steps[[0, -1]].mean() * 3)
if ind.size > 0:
# choose the two colors between which there is the large step
ind = ind[0] + 1
fillcols = np.r_[np.tile(cols[ind, :], (n_fill // 2, 1)),
np.tile(cols[ind + 1, :], (n_fill - n_fill // 2, 1))]
else:
# choose a color from the middle of the colormap
fillcols = np.tile(cols[int(cols.shape[0] / 2), :], (n_fill, 1))
return fillcols
@verbose
def _scale_mayavi_lut(lut_table, fmin, fmid, fmax, transparent,
center=None, alpha=1.0, verbose=None):
"""Scale a mayavi colormap LUT to a given fmin, fmid and fmax.
This function operates on a Mayavi LUTManager. This manager can be obtained
through the traits interface of mayavi. For example:
``x.module_manager.vector_lut_manager``.
Divergent colormaps are respected, if ``center`` is given, see
``Brain.scale_data_colormap`` for more info.
Parameters
----------
lut_orig : array
The original LUT.
fmin : float
minimum value of colormap.
fmid : float
value corresponding to color midpoint.
fmax : float
maximum value for colormap.
transparent : boolean
if True: use a linear transparency between fmin and fmid and make
values below fmin fully transparent (symmetrically for divergent
colormaps)
center : float
gives the data value that should be mapped to the center of the
(divergent) colormap
alpha : float
sets the overall opacity of colors, maintains transparent regions
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
Returns
-------
lut_table_new : 2D array (n_colors, 4)
The re-scaled color lookup table
"""
if not (fmin < fmid) and (fmid < fmax):
raise ValueError("Invalid colormap, we need fmin<fmid<fmax")
if not 0 <= alpha <= 1:
raise ValueError("Invalid alpha: it needs to be within [0, 1]")
# Cast inputs to float to prevent integer division
fmin = float(fmin)
fmid = float(fmid)
fmax = float(fmax)
_check_limits(fmin, fmid, fmax)
divergent = center is not None
trstr = ['(opaque)', '(transparent)']
if divergent:
logger.debug(
"colormap divergent: center=%0.2e, [%0.2e, %0.2e, %0.2e] %s"
% (center, fmin, fmid, fmax, trstr[transparent]))
else:
logger.debug(
"colormap sequential: [%0.2e, %0.2e, %0.2e] %s"
% (fmin, fmid, fmax, trstr[transparent]))
n_colors = lut_table.shape[0]
# Add transparency if needed
if transparent:
if divergent:
N4 = np.full(4, n_colors / 4, dtype=int)
N4[:np.mod(n_colors, 4)] += 1
assert N4.sum() == n_colors
lut_table[:, -1] = np.r_[255 * np.ones(N4[0]),
np.linspace(255, 0, N4[2]),
np.linspace(0, 255, N4[3]),
255 * np.ones(N4[1])]
else:
n_colors2 = int(n_colors / 2)
lut_table[:n_colors2, -1] = np.linspace(0, 255, n_colors2)
lut_table[n_colors2:, -1] = 255 * np.ones(n_colors - n_colors2)
alpha = float(alpha)
if alpha < 1.0:
lut_table[:, -1] = lut_table[:, -1] * alpha
if divergent:
# the colormap should consist of 3 parts: a left part for the negative
# data, a right part for the positive data and a middle, fill part
# representing the values in [center-fmin, center+fmin], we
# introduce this middle part by extending the number of 'colors' of the
# original colormap because the Mayavi lut manager scales linearly
# between colors and we don't want to reduce the color resolution in
# the interesting regions of data space
n_colors2 = int(n_colors / 2)
n_fill = int(round(fmin * n_colors2 / (fmax-fmin))) * 2
lut_table = np.r_[
_scale_sequential_lut(lut_table[:n_colors2, :],
center-fmax, center-fmid, center-fmin),
_get_fill_colors(
lut_table[n_colors2 - 3:n_colors2 + 3, :], n_fill),
_scale_sequential_lut(lut_table[n_colors2:, :],
center+fmin, center+fmid, center+fmax)]
else:
lut_table = _scale_sequential_lut(lut_table, fmin, fmid, fmax)
# rescale to 256 colors; this is necessary, because Mayavi/VTK does not
# handle a change in the number of colors well: when you change from a long
# table to a short table, values beyond the table value range get somehow
# not mapped to the colors defined by the table edges; it may be that this
# is due to improper setting of the number of table values / colors in the
# underlying VTK lookup table, or mapper, but I couldn't figure out where
# exactly the fault lies, so simply stick with the constant table size
n_colors = lut_table.shape[0]
if n_colors != 256:
lut = np.zeros((256, 4))
x = np.linspace(1, n_colors, 256)
for chan in range(4):
lut[:, chan] = np.interp(x,
np.arange(1, n_colors+1),
lut_table[:, chan])
lut_table = lut
return lut_table
class _Hemisphere(object):
"""Object for visualizing one hemisphere with mlab"""
def __init__(self, subject_id, hemi, figure, geo, geo_curv,
geo_kwargs, geo_reverse, subjects_dir, bg_color, backend,
fg_color):
if hemi not in ['lh', 'rh']:
raise ValueError('hemi must be either "lh" or "rh"')
# Set the identifying info
self.subject_id = subject_id
self.hemi = hemi
self.subjects_dir = subjects_dir
self.viewdict = viewdicts[hemi]
self._f = figure
self._bg_color = bg_color
self._fg_color = fg_color
self._backend = backend
self.data = {}
self._mesh_clones = {} # surface mesh data-sources
# mlab pipeline mesh and surface for geomtery
meshargs = dict(scalars=geo.bin_curv) if geo_curv else dict()
with warnings.catch_warnings(record=True): # traits
self._geo_mesh = mlab.pipeline.triangular_mesh_source(
geo.x, geo.y, geo.z, geo.faces, figure=self._f, **meshargs)
self._geo_mesh.data.points = geo.coords
self._mesh_dataset = self._geo_mesh.mlab_source.dataset
# add surface normals
self._geo_mesh.data.point_data.normals = geo.nn
self._geo_mesh.data.cell_data.normals = None
if mlab.options.backend != 'test':
self._geo_mesh.update()
if 'lut' in geo_kwargs:
# create a new copy we can modify:
geo_kwargs = dict(geo_kwargs)
lut = geo_kwargs.pop('lut')
else:
lut = None
self._using_lut = bool(geo_curv)
with warnings.catch_warnings(record=True): # traits warnings
self._geo_surf = mlab.pipeline.surface(
self._geo_mesh, figure=self._f, reset_zoom=True, **geo_kwargs)
self._geo_surf.actor.property.backface_culling = True
if lut is not None:
lut_manager = self._geo_surf.module_manager.scalar_lut_manager
lut_manager.load_lut_from_list(lut / 255.)
if geo_curv and geo_reverse:
curv_bar = mlab.scalarbar(self._geo_surf)
curv_bar.reverse_lut = True
curv_bar.visible = False
def show_view(self, view=None, roll=None, distance=None):
"""Orient camera to display view"""
if isinstance(view, string_types):
try:
vd = self._xfm_view(view, 'd')
view = dict(azimuth=vd['v'][0], elevation=vd['v'][1])
roll = vd['r']
except ValueError as v:
print(v)
raise
_force_render(self._f)
if view is not None:
view = deepcopy(view)
view['reset_roll'] = True
view['figure'] = self._f
if 'distance' not in view:
view['distance'] = distance
elif distance is not None and distance != view['distance']:
raise ValueError('view parameters view["distance"] != '
'distance (%s != %s)' % (view['distance'],
distance))
# DO NOT set focal point, can screw up non-centered brains
# view['focalpoint'] = (0.0, 0.0, 0.0)
mlab.view(**view)
if roll is not None:
mlab.roll(roll=roll, figure=self._f)
_force_render(self._f)
view = mlab.view(figure=self._f)
roll = mlab.roll(figure=self._f)
return view, roll
def _xfm_view(self, view, out='s'):
"""Normalize a given string to available view
Parameters
----------
view: string
view which may match leading substring of available views
Returns
-------
good: string
matching view string
out: {'s' | 'd'}
's' to return string, 'd' to return dict
"""
if view not in self.viewdict:
good_view = [k for k in self.viewdict if view == k[:len(view)]]
if len(good_view) == 0:
raise ValueError('No views exist with this substring')
if len(good_view) > 1:
raise ValueError("Multiple views exist with this substring."
"Try a longer substring")
view = good_view[0]
if out == 'd':
return self.viewdict[view]
else:
return view
def _min_diff(self, beg, end):
"""Determine minimum "camera distance" between two views.
Parameters
----------
beg : string
origin anatomical view.
end : string
destination anatomical view.
Returns
-------
diffs : tuple
(min view "distance", min roll "distance").
"""
beg = self._xfm_view(beg)
end = self._xfm_view(end)
if beg == end:
dv = [360., 0.]
dr = 0
else:
end_d = self._xfm_view(end, 'd')
beg_d = self._xfm_view(beg, 'd')
dv = []
for b, e in zip(beg_d['v'], end_d['v']):
diff = e - b
# to minimize the rotation we need -180 <= diff <= 180
if diff > 180:
dv.append(diff - 360)
elif diff < -180:
dv.append(diff + 360)
else:
dv.append(diff)
dr = np.array(end_d['r']) - np.array(beg_d['r'])
return (np.array(dv), dr)
def _add_scalar_data(self, data):
"""Add scalar values to dataset"""
array_id = self._mesh_dataset.point_data.add_array(data)
self._mesh_dataset.point_data.get_array(array_id).name = array_id
self._mesh_dataset.point_data.update()
# build visualization pipeline
with warnings.catch_warnings(record=True):
pipe = mlab.pipeline.set_active_attribute(
self._mesh_dataset, point_scalars=array_id, figure=self._f)
# The new data-source is added to the wrong figure by default
# (a Mayavi bug??)
if pipe.parent not in self._f.children:
self._f.add_child(pipe.parent)
self._mesh_clones[array_id] = pipe.parent
return array_id, pipe
def _remove_scalar_data(self, array_id):
"""Removes scalar data"""
self._mesh_clones.pop(array_id).remove()
self._mesh_dataset.point_data.remove_array(array_id)
def _add_vector_data(self, vectors, fmin, fmid, fmax,
scale_factor, vertices, vector_alpha, lut):
vertices = slice(None) if vertices is None else vertices
x, y, z = np.array(self._geo_mesh.data.points.data)[vertices].T
vector_alpha = min(vector_alpha, 0.9999999)
with warnings.catch_warnings(record=True): # HasTraits
quiver = mlab.quiver3d(
x, y, z, vectors[:, 0], vectors[:, 1], vectors[:, 2],
colormap='hot', vmin=fmin, scale_mode='vector',
vmax=fmax, figure=self._f, opacity=vector_alpha)
# Enable backface culling
quiver.actor.property.backface_culling = True
quiver.mlab_source.update()
# Set scaling for the glyphs
quiver.glyph.glyph.scale_factor = scale_factor
quiver.glyph.glyph.clamping = False
quiver.glyph.glyph.range = (0., 1.)
# Scale colormap used for the glyphs
l_m = quiver.parent.vector_lut_manager
l_m.load_lut_from_list(lut / 255.)
l_m.data_range = np.array([fmin, fmax])
return quiver
def _remove_vector_data(self, glyphs):
if glyphs is not None:
glyphs.parent.parent.remove()
def add_overlay(self, old, **kwargs):
"""Add an overlay to the overlay dict from a file or array"""
array_id, mesh = self._add_scalar_data(old.mlab_data)
if old.pos_lims is not None:
with warnings.catch_warnings(record=True):
pos_thresh = threshold_filter(mesh, low=old.pos_lims[0])
pos = mlab.pipeline.surface(
pos_thresh, colormap="YlOrRd", figure=self._f,
vmin=old.pos_lims[1], vmax=old.pos_lims[2],
reset_zoom=False, **kwargs)
pos.actor.property.backface_culling = False
pos_bar = mlab.scalarbar(pos, nb_labels=5)
pos_bar.reverse_lut = True
pos_bar.scalar_bar_representation.position = (0.53, 0.01)
pos_bar.scalar_bar_representation.position2 = (0.42, 0.09)
pos_bar.label_text_property.color = self._fg_color
else:
pos = pos_bar = None
if old.neg_lims is not None:
with warnings.catch_warnings(record=True):
neg_thresh = threshold_filter(mesh, up=old.neg_lims[0])
neg = mlab.pipeline.surface(
neg_thresh, colormap="PuBu", figure=self._f,
vmin=old.neg_lims[1], vmax=old.neg_lims[2],
reset_zoom=False, **kwargs)
neg.actor.property.backface_culling = False
neg_bar = mlab.scalarbar(neg, nb_labels=5)
neg_bar.scalar_bar_representation.position = (0.05, 0.01)
neg_bar.scalar_bar_representation.position2 = (0.42, 0.09)
neg_bar.label_text_property.color = self._fg_color
else:
neg = neg_bar = None
return OverlayDisplay(self, array_id, pos, pos_bar, neg, neg_bar)
@verbose
def add_data(self, array, fmin, fmid, fmax, thresh, lut, colormap, alpha,
colorbar, layer_id, smooth_mat, magnitude,
scale_factor, vertices, vector_alpha, **kwargs):
"""Add data to the brain"""
# Calculate initial data to plot
if array.ndim == 1:
array_plot = array
elif array.ndim == 2:
array_plot = array[:, 0]
elif array.ndim == 3:
assert array.shape[1] == 3 # should always be true
assert magnitude is not None
assert scale_factor is not None
array_plot = magnitude[:, 0]
else:
raise ValueError("data has to be 1D, 2D, or 3D")
if smooth_mat is not None:
array_plot = smooth_mat * array_plot
# Copy and byteswap to deal with Mayavi bug
array_plot = _prepare_data(array_plot)
array_id, pipe = self._add_scalar_data(array_plot)
if array.ndim == 3:
vectors = array[:, :, 0].copy()
glyphs = self._add_vector_data(
vectors, fmin, fmid, fmax,
scale_factor, vertices, vector_alpha, lut)
else:
glyphs = None
mesh = pipe.parent
if thresh is not None:
if array_plot.min() >= thresh:
warn("Data min is greater than threshold.")
else:
with warnings.catch_warnings(record=True):
pipe = threshold_filter(pipe, low=thresh, figure=self._f)
with warnings.catch_warnings(record=True):
surf = mlab.pipeline.surface(
pipe, colormap=colormap, vmin=fmin, vmax=fmax,
opacity=float(alpha), figure=self._f, reset_zoom=False,
**kwargs)
surf.actor.property.backface_culling = False
# There is a bug on some graphics cards concerning transparant
# overlays that is fixed by setting force_opaque.
if float(alpha) == 1:
surf.actor.actor.force_opaque = True
# apply look up table if given
if lut is not None:
l_m = surf.module_manager.scalar_lut_manager
l_m.load_lut_from_list(lut / 255.)
# Get the original colormap table
orig_ctable = \
surf.module_manager.scalar_lut_manager.lut.table.to_array().copy()
# Get the colorbar
if colorbar:
bar = mlab.scalarbar(surf)
bar.label_text_property.color = self._fg_color
bar.scalar_bar_representation.position2 = .8, 0.09
else:
bar = None
self.data[layer_id] = dict(
array_id=array_id, mesh=mesh, glyphs=glyphs,
scale_factor=scale_factor)
return surf, orig_ctable, bar, glyphs
def add_annotation(self, annot, ids, cmap, **kwargs):
"""Add an annotation file"""
# Add scalar values to dataset
array_id, pipe = self._add_scalar_data(ids)
with warnings.catch_warnings(record=True):
surf = mlab.pipeline.surface(pipe, name=annot, figure=self._f,
reset_zoom=False, **kwargs)
surf.actor.property.backface_culling = False
# Set the color table
l_m = surf.module_manager.scalar_lut_manager
l_m.lut.table = np.round(cmap).astype(np.uint8)
# Set the brain attributes
return dict(surface=surf, name=annot, colormap=cmap, brain=self,
array_id=array_id)
def add_label(self, label, label_name, color, alpha, **kwargs):
"""Add an ROI label to the image"""
from matplotlib.colors import colorConverter
array_id, pipe = self._add_scalar_data(label)
with warnings.catch_warnings(record=True):
surf = mlab.pipeline.surface(pipe, name=label_name, figure=self._f,
reset_zoom=False, **kwargs)
surf.actor.property.backface_culling = False
color = colorConverter.to_rgba(color, alpha)
cmap = np.array([(0, 0, 0, 0,), color])
l_m = surf.module_manager.scalar_lut_manager
# for some reason (traits?) using `load_lut_from_list` here does
# not work (.data_range needs to be tweaked in this case),
# but setting the table directly does:
l_m.lut.table = np.round(cmap * 255).astype(np.uint8)
return array_id, surf
def add_morphometry(self, morph_data, colormap, measure,
min, max, colorbar, **kwargs):
"""Add a morphometry overlay to the image"""
array_id, pipe = self._add_scalar_data(morph_data)
with warnings.catch_warnings(record=True):
surf = mlab.pipeline.surface(
pipe, colormap=colormap, vmin=min, vmax=max, name=measure,
figure=self._f, reset_zoom=False, **kwargs)
# Get the colorbar
if colorbar:
bar = mlab.scalarbar(surf)
bar.label_text_property.color = self._fg_color
bar.scalar_bar_representation.position2 = .8, 0.09
else:
bar = None
# Fil in the morphometry dict
return dict(surface=surf, colorbar=bar, measure=measure, brain=self,
array_id=array_id)
def add_foci(self, foci_coords, scale_factor, color, alpha, name,
**kwargs):
"""Add spherical foci, possibly mapping to displayed surf"""
# Create the visualization
with warnings.catch_warnings(record=True): # traits
points = mlab.points3d(
foci_coords[:, 0], foci_coords[:, 1], foci_coords[:, 2],
np.ones(foci_coords.shape[0]), name=name, figure=self._f,
scale_factor=(10. * scale_factor), color=color, opacity=alpha,
reset_zoom=False, **kwargs)
return points
def add_contour_overlay(self, scalar_data, min=None, max=None,
n_contours=7, line_width=1.5, lut=None,
colorbar=True, **kwargs):
"""Add a topographic contour overlay of the positive data"""
array_id, pipe = self._add_scalar_data(scalar_data)
with warnings.catch_warnings(record=True):
thresh = threshold_filter(pipe, low=min)
surf = mlab.pipeline.contour_surface(
thresh, contours=n_contours, line_width=line_width,
reset_zoom=False, **kwargs)
if lut is not None:
l_m = surf.module_manager.scalar_lut_manager
l_m.load_lut_from_list(lut / 255.)
# Set the colorbar and range correctly
with warnings.catch_warnings(record=True): # traits
bar = mlab.scalarbar(surf, nb_colors=n_contours,
nb_labels=n_contours + 1)
bar.data_range = min, max
bar.label_text_property.color = self._fg_color
bar.scalar_bar_representation.position2 = .8, 0.09
if not colorbar:
bar.visible = False
# Set up a dict attribute with pointers at important things
return dict(surface=surf, colorbar=bar, brain=self, array_id=array_id)
def add_text(self, x, y, text, name, color=None, opacity=1.0, **kwargs):
""" Add a text to the visualization"""
color = self._fg_color if color is None else color
with warnings.catch_warnings(record=True):
text = mlab.text(x, y, text, name=name, color=color,
opacity=opacity, figure=self._f, **kwargs)
return text
def remove_data(self, layer_id):
"""Remove data shown with .add_data()"""
data = self.data.pop(layer_id)
self._remove_scalar_data(data['array_id'])
self._remove_vector_data(data['glyphs'])
def set_data(self, layer_id, values, vectors=None):
"""Set displayed data values and vectors."""
data = self.data[layer_id]
self._mesh_dataset.point_data.get_array(
data['array_id']).from_array(values)
# avoid "AttributeError: 'Scene' object has no attribute 'update'"
data['mesh'].update()
if vectors is not None:
q = data['glyphs']
# extract params that will change after calling .update()
l_m = q.parent.vector_lut_manager
data_range = np.array(l_m.data_range)
lut = l_m.lut.table.to_array().copy()
# Update glyphs
q.mlab_source.vectors = vectors
q.mlab_source.update()
# Update changed parameters, and glyph scaling
q.glyph.glyph.scale_factor = data['scale_factor']
q.glyph.glyph.range = (0., 1.)
q.glyph.glyph.clamping = False
l_m.load_lut_from_list(lut / 255.)
l_m.data_range = data_range
def _orient_lights(self):
"""Set lights to come from same direction relative to brain."""
if self.hemi == "rh":
if self._f.scene is not None and \
self._f.scene.light_manager is not None:
for light in self._f.scene.light_manager.lights:
light.azimuth *= -1
def update_surf(self):
"""Update surface mesh after mesh coordinates change."""
with warnings.catch_warnings(record=True): # traits
self._geo_mesh.update()
for mesh in self._mesh_clones.values():
mesh.update()
class OverlayData(object):
"""Encapsulation of statistical neuroimaging overlay viz data"""
def __init__(self, scalar_data, min, max, sign):
if scalar_data.min() >= 0:
sign = "pos"
elif scalar_data.max() <= 0:
sign = "neg"
if sign in ["abs", "pos"]:
# Figure out the correct threshold to avoid TraitErrors
# This seems like not the cleanest way to do this
pos_max = np.max((0.0, np.max(scalar_data)))
if pos_max < min:
thresh_low = pos_max
else:
thresh_low = min
self.pos_lims = [thresh_low, min, max]
else:
self.pos_lims = None
if sign in ["abs", "neg"]:
# Figure out the correct threshold to avoid TraitErrors
# This seems even less clean due to negative convolutedness
neg_min = np.min((0.0, np.min(scalar_data)))
if neg_min > -min:
thresh_up = neg_min
else:
thresh_up = -min
self.neg_lims = [thresh_up, -max, -min]
else:
self.neg_lims = None
# Byte swap copy; due to mayavi bug
self.mlab_data = _prepare_data(scalar_data)
class OverlayDisplay():
"""Encapsulation of overlay viz plotting"""
def __init__(self, brain, array_id, pos, pos_bar, neg, neg_bar):
self._brain = brain
self._array_id = array_id
self.pos = pos
self.pos_bar = pos_bar
self.neg = neg
self.neg_bar = neg_bar
def remove(self):
self._brain._remove_scalar_data(self._array_id)
if self.pos_bar is not None:
self.pos_bar.visible = False
if self.neg_bar is not None:
self.neg_bar.visible = False
class TimeViewer(HasTraits):
"""TimeViewer object providing a GUI for visualizing time series
Useful for visualizing M/EEG inverse solutions on Brain object(s).
Parameters
----------
brain : Brain (or list of Brain)
brain(s) to control
"""
# Nested import of traisui for setup.py without X server
min_time = Int(0)
max_time = Int(1E9)
current_time = Range(low="min_time", high="max_time", value=0)
# colormap: only update when user presses Enter
fmax = Float(enter_set=True, auto_set=False)
fmid = Float(enter_set=True, auto_set=False)
fmin = Float(enter_set=True, auto_set=False)
transparent = Bool(True)
smoothing_steps = Int(20, enter_set=True, auto_set=False,
desc="number of smoothing steps. Use -1 for"
"automatic number of steps")
orientation = Enum("lateral", "medial", "rostral", "caudal",
"dorsal", "ventral", "frontal", "parietal")
# GUI layout
view = View(VSplit(Item(name="current_time"),
Group(HSplit(Item(name="fmin"),
Item(name="fmid"),
Item(name="fmax"),
Item(name="transparent")
),
label="Color scale",
show_border=True),
Item(name="smoothing_steps"),
Item(name="orientation")
)
)
def __init__(self, brain):
super(TimeViewer, self).__init__()
if isinstance(brain, (list, tuple)):
self.brains = brain
else:
self.brains = [brain]
# Initialize GUI with values from first brain
props = self.brains[0].get_data_properties()
self._disable_updates = True
self.max_time = len(props["time"]) - 1
self.current_time = props["time_idx"]
self.fmin = props["fmin"]
self.fmid = props["fmid"]
self.fmax = props["fmax"]
self.transparent = props["transparent"]
self.center = props["center"]
if props["smoothing_steps"] is None:
self.smoothing_steps = -1
else:
self.smoothing_steps = props["smoothing_steps"]
self._disable_updates = False
# Make sure all brains have the same time points
for brain in self.brains[1:]:
this_props = brain.get_data_properties()
if not np.all(props["time"] == this_props["time"]):
raise ValueError("all brains must have the same time"
"points")
# Show GUI
self.configure_traits()
@on_trait_change("smoothing_steps")
def _set_smoothing_steps(self):
""" Change number of smooting steps
"""
if self._disable_updates:
return
smoothing_steps = self.smoothing_steps
if smoothing_steps < 0:
smoothing_steps = None
for brain in self.brains:
brain.set_data_smoothing_steps(self.smoothing_steps)
@on_trait_change("orientation")
def _set_orientation(self):
""" Set the orientation
"""
if self._disable_updates:
return
for brain in self.brains:
brain.show_view(view=self.orientation)
@on_trait_change("current_time")
def _set_time_point(self):
""" Set the time point shown
"""
if self._disable_updates:
return
for brain in self.brains:
brain.set_data_time_index(self.current_time)
@on_trait_change("fmin, fmid, fmax, transparent")
def _scale_colormap(self):
""" Scale the colormap
"""
if self._disable_updates:
return
for brain in self.brains:
brain.scale_data_colormap(self.fmin, self.fmid, self.fmax,
self.transparent, self.center)
|
nipy/PySurfer
|
surfer/viz.py
|
Python
|
bsd-3-clause
| 148,235
|
[
"Mayavi",
"VTK"
] |
d287111796b41862d38009754d7a37b81dd305130a5d75b0f7dabcaeb0c426db
|
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.constants` namespace for importing the functions
# included below.
import warnings
from . import _constants
__all__ = [ # noqa: F822
'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
'angstrom', 'arcmin', 'arcminute', 'arcsec',
'arcsecond', 'astronomical_unit', 'atm',
'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
'barrel', 'bbl', 'blob', 'c', 'calorie',
'calorie_IT', 'calorie_th', 'carat', 'centi',
'convert_temperature', 'day', 'deci', 'degree',
'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
'eV', 'electron_mass', 'electron_volt',
'elementary_charge', 'epsilon_0', 'erg',
'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
'hectare', 'hecto', 'horsepower', 'hour', 'hp',
'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
'light_year', 'liter', 'litre', 'long_ton', 'm_e',
'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
'metric_ton', 'micro', 'micron', 'mil', 'mile',
'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
'nautical_mile', 'neutron_mass', 'nu2lambda',
'ounce', 'oz', 'parsec', 'pebi', 'peta',
'pi', 'pico', 'point', 'pound', 'pound_force',
'proton_mass', 'psi', 'pt', 'short_ton',
'sigma', 'slinch', 'slug', 'speed_of_light',
'speed_of_sound', 'stone', 'survey_foot',
'survey_mile', 'tebi', 'tera', 'ton_TNT',
'torr', 'troy_ounce', 'troy_pound', 'u',
'week', 'yard', 'year', 'yobi', 'yocto',
'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
]
def __dir__():
return __all__
def __getattr__(name):
if name not in __all__:
raise AttributeError(
"scipy.constants.constants is deprecated and has no attribute "
f"{name}. Try looking in scipy.constants instead.")
warnings.warn(f"Please use `{name}` from the `scipy.constants` namespace, "
"the `scipy.constants.constants` namespace is deprecated.",
category=DeprecationWarning, stacklevel=2)
return getattr(_constants, name)
|
grlee77/scipy
|
scipy/constants/constants.py
|
Python
|
bsd-3-clause
| 2,477
|
[
"Avogadro"
] |
93c20e0ed1a4927678e1c9431448a15696abbe3245c040c6e39e15da87f80694
|
"""
Sphinx plugins for Django documentation.
"""
import json
import os
import re
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx import addnodes, __version__ as sphinx_ver
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.writers.html import SmartyPantsHTMLTranslator
from sphinx.util.console import bold
from sphinx.util.compat import Directive
from sphinx.util.nodes import set_source_info
# RE for option descriptions without a '--' prefix
simple_option_desc_re = re.compile(
r'([-_a-zA-Z0-9]+)(\s*.*?)(?=,\s+(?:/|-|--)|$)')
def setup(app):
app.add_crossref_type(
directivename="setting",
rolename="setting",
indextemplate="pair: %s; setting",
)
app.add_crossref_type(
directivename="templatetag",
rolename="ttag",
indextemplate="pair: %s; template tag"
)
app.add_crossref_type(
directivename="templatefilter",
rolename="tfilter",
indextemplate="pair: %s; template filter"
)
app.add_crossref_type(
directivename="fieldlookup",
rolename="lookup",
indextemplate="pair: %s; field lookup type",
)
app.add_description_unit(
directivename="django-admin",
rolename="djadmin",
indextemplate="pair: %s; django-admin command",
parse_node=parse_django_admin_node,
)
app.add_description_unit(
directivename="django-admin-option",
rolename="djadminopt",
indextemplate="pair: %s; django-admin command-line option",
parse_node=parse_django_adminopt_node,
)
app.add_config_value('django_next_version', '0.0', True)
app.add_directive('versionadded', VersionDirective)
app.add_directive('versionchanged', VersionDirective)
app.add_builder(DjangoStandaloneHTMLBuilder)
# register the snippet directive
app.add_directive('snippet', SnippetWithFilename)
# register a node for snippet directive so that the xml parser
# knows how to handle the enter/exit parsing event
app.add_node(snippet_with_filename,
html=(visit_snippet, depart_snippet_literal),
latex=(visit_snippet_latex, depart_snippet_latex),
man=(visit_snippet_literal, depart_snippet_literal),
text=(visit_snippet_literal, depart_snippet_literal),
texinfo=(visit_snippet_literal, depart_snippet_literal))
class snippet_with_filename(nodes.literal_block):
"""
Subclass the literal_block to override the visit/depart event handlers
"""
pass
def visit_snippet_literal(self, node):
"""
default literal block handler
"""
self.visit_literal_block(node)
def depart_snippet_literal(self, node):
"""
default literal block handler
"""
self.depart_literal_block(node)
def visit_snippet(self, node):
"""
HTML document generator visit handler
"""
lang = self.highlightlang
linenos = node.rawsource.count('\n') >= self.highlightlinenothreshold - 1
fname = node['filename']
highlight_args = node.get('highlight_args', {})
if 'language' in node:
# code-block directives
lang = node['language']
highlight_args['force'] = True
if 'linenos' in node:
linenos = node['linenos']
def warner(msg):
self.builder.warn(msg, (self.builder.current_docname, node.line))
highlighted = self.highlighter.highlight_block(node.rawsource, lang,
warn=warner,
linenos=linenos,
**highlight_args)
starttag = self.starttag(node, 'div', suffix='',
CLASS='highlight-%s' % lang)
self.body.append(starttag)
self.body.append('<div class="snippet-filename">%s</div>\n''' % (fname,))
self.body.append(highlighted)
self.body.append('</div>\n')
raise nodes.SkipNode
def visit_snippet_latex(self, node):
"""
Latex document generator visit handler
"""
self.verbatim = ''
def depart_snippet_latex(self, node):
"""
Latex document generator depart handler.
"""
code = self.verbatim.rstrip('\n')
lang = self.hlsettingstack[-1][0]
linenos = code.count('\n') >= self.hlsettingstack[-1][1] - 1
fname = node['filename']
highlight_args = node.get('highlight_args', {})
if 'language' in node:
# code-block directives
lang = node['language']
highlight_args['force'] = True
if 'linenos' in node:
linenos = node['linenos']
def warner(msg):
self.builder.warn(msg, (self.curfilestack[-1], node.line))
hlcode = self.highlighter.highlight_block(code, lang, warn=warner,
linenos=linenos,
**highlight_args)
self.body.append('\n{\\colorbox[rgb]{0.9,0.9,0.9}'
'{\\makebox[\\textwidth][l]'
'{\\small\\texttt{%s}}}}\n' % (fname,))
if self.table:
hlcode = hlcode.replace('\\begin{Verbatim}',
'\\begin{OriginalVerbatim}')
self.table.has_problematic = True
self.table.has_verbatim = True
hlcode = hlcode.rstrip()[:-14] # strip \end{Verbatim}
hlcode = hlcode.rstrip() + '\n'
self.body.append('\n' + hlcode + '\\end{%sVerbatim}\n' %
(self.table and 'Original' or ''))
self.verbatim = None
class SnippetWithFilename(Directive):
"""
The 'snippet' directive that allows to add the filename (optional)
of a code snippet in the document. This is modeled after CodeBlock.
"""
has_content = True
optional_arguments = 1
option_spec = {'filename': directives.unchanged_required}
def run(self):
code = '\n'.join(self.content)
literal = snippet_with_filename(code, code)
if self.arguments:
literal['language'] = self.arguments[0]
literal['filename'] = self.options['filename']
set_source_info(self, literal)
return [literal]
class VersionDirective(Directive):
has_content = True
required_arguments = 1
optional_arguments = 1
final_argument_whitespace = True
option_spec = {}
def run(self):
if len(self.arguments) > 1:
msg = """Only one argument accepted for directive '{directive_name}::'.
Comments should be provided as content,
not as an extra argument.""".format(directive_name=self.name)
raise self.error(msg)
env = self.state.document.settings.env
ret = []
node = addnodes.versionmodified()
ret.append(node)
if self.arguments[0] == env.config.django_next_version:
node['version'] = "Development version"
else:
node['version'] = self.arguments[0]
node['type'] = self.name
if self.content:
self.state.nested_parse(self.content, self.content_offset, node)
env.note_versionchange(node['type'], node['version'], node, self.lineno)
return ret
class DjangoHTMLTranslator(SmartyPantsHTMLTranslator):
"""
Django-specific reST to HTML tweaks.
"""
# Don't use border=1, which docutils does by default.
def visit_table(self, node):
self.context.append(self.compact_p)
self.compact_p = True
self._table_row_index = 0 # Needed by Sphinx
self.body.append(self.starttag(node, 'table', CLASS='docutils'))
def depart_table(self, node):
self.compact_p = self.context.pop()
self.body.append('</table>\n')
def visit_desc_parameterlist(self, node):
self.body.append('(') # by default sphinx puts <big> around the "("
self.first_param = 1
self.optional_param_level = 0
self.param_separator = node.child_text_separator
self.required_params_left = sum([isinstance(c, addnodes.desc_parameter)
for c in node.children])
def depart_desc_parameterlist(self, node):
self.body.append(')')
if sphinx_ver < '1.0.8':
#
# Don't apply smartypants to literal blocks
#
def visit_literal_block(self, node):
self.no_smarty += 1
SmartyPantsHTMLTranslator.visit_literal_block(self, node)
def depart_literal_block(self, node):
SmartyPantsHTMLTranslator.depart_literal_block(self, node)
self.no_smarty -= 1
#
# Turn the "new in version" stuff (versionadded/versionchanged) into a
# better callout -- the Sphinx default is just a little span,
# which is a bit less obvious that I'd like.
#
# FIXME: these messages are all hardcoded in English. We need to change
# that to accommodate other language docs, but I can't work out how to make
# that work.
#
version_text = {
'deprecated': 'Deprecated in Django %s',
'versionchanged': 'Changed in Django %s',
'versionadded': 'New in Django %s',
}
def visit_versionmodified(self, node):
self.body.append(
self.starttag(node, 'div', CLASS=node['type'])
)
title = "%s%s" % (
self.version_text[node['type']] % node['version'],
":" if len(node) else "."
)
self.body.append('<span class="title">%s</span> ' % title)
def depart_versionmodified(self, node):
self.body.append("</div>\n")
# Give each section a unique ID -- nice for custom CSS hooks
def visit_section(self, node):
old_ids = node.get('ids', [])
node['ids'] = ['s-' + i for i in old_ids]
node['ids'].extend(old_ids)
SmartyPantsHTMLTranslator.visit_section(self, node)
node['ids'] = old_ids
def parse_django_admin_node(env, sig, signode):
command = sig.split(' ')[0]
env._django_curr_admin_command = command
title = "manage.py %s" % sig
signode += addnodes.desc_name(title, title)
return sig
def parse_django_adminopt_node(env, sig, signode):
"""A copy of sphinx.directives.CmdoptionDesc.parse_signature()"""
from sphinx.domains.std import option_desc_re
count = 0
firstname = ''
for m in option_desc_re.finditer(sig):
optname, args = m.groups()
if count:
signode += addnodes.desc_addname(', ', ', ')
signode += addnodes.desc_name(optname, optname)
signode += addnodes.desc_addname(args, args)
if not count:
firstname = optname
count += 1
if not count:
for m in simple_option_desc_re.finditer(sig):
optname, args = m.groups()
if count:
signode += addnodes.desc_addname(', ', ', ')
signode += addnodes.desc_name(optname, optname)
signode += addnodes.desc_addname(args, args)
if not count:
firstname = optname
count += 1
if not firstname:
raise ValueError
return firstname
class DjangoStandaloneHTMLBuilder(StandaloneHTMLBuilder):
"""
Subclass to add some extra things we need.
"""
name = 'djangohtml'
def finish(self):
super(DjangoStandaloneHTMLBuilder, self).finish()
self.info(bold("writing templatebuiltins.js..."))
xrefs = self.env.domaindata["std"]["objects"]
templatebuiltins = {
"ttags": [n for ((t, n), (l, a)) in xrefs.items()
if t == "templatetag" and l == "ref/templates/builtins"],
"tfilters": [n for ((t, n), (l, a)) in xrefs.items()
if t == "templatefilter" and l == "ref/templates/builtins"],
}
outfilename = os.path.join(self.outdir, "templatebuiltins.js")
with open(outfilename, 'w') as fp:
fp.write('var django_template_builtins = ')
json.dump(templatebuiltins, fp)
fp.write(';\n')
|
paour/weblate
|
docs/_ext/djangodocs.py
|
Python
|
gpl-3.0
| 12,011
|
[
"VisIt"
] |
0c54d21e646f33114228a12a968ea4736fe7124a6ab3084348a395dba2cd3150
|
from ase.structure import molecule
from gpaw import GPAW
from gpaw.wavefunctions.pw import PW
from gpaw.mpi import world
a = molecule('H', pbc=1)
a.center(vacuum=2)
comm = world.new_communicator([world.rank])
e0 = 0.0
a.calc = GPAW(mode=PW(250),
communicator=comm,
txt=None)
e0 = a.get_potential_energy()
e0 = world.sum(e0) / world.size
a.calc = GPAW(mode=PW(250),
eigensolver='rmm-diis',
basis='szp(dzp)',
txt='%d.txt' % world.size)
e = a.get_potential_energy()
f = a.get_forces()
assert abs(e - e0) < 7e-5, abs(e - e0)
assert abs(f).max() < 1e-10, abs(f).max()
|
robwarm/gpaw-symm
|
gpaw/test/pw/h.py
|
Python
|
gpl-3.0
| 637
|
[
"ASE",
"GPAW"
] |
39c2f665efa9b457c23dc53288011aa88ba963543636b1056e9a075cd0f4602e
|
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import os
import subprocess
class Turbomole(Package):
"""TURBOMOLE: Program Package for ab initio Electronic Structure
Calculations.
Note: Turbomole requires purchase of a license to download. Go to the
Turbomole home page, http://www.turbomole-gmbh.com, for details.
Spack will search the current directory for this file. It is
probably best to add this file to a Spack mirror so that it can be
found from anywhere. For information on setting up a Spack mirror
see http://spack.readthedocs.io/en/latest/mirrors.html"""
homepage = "http://www.turbomole-gmbh.com/"
manual_download = True
version('7.0.2', '92b97e1e52e8dcf02a4d9ac0147c09d6',
url="file://%s/turbolinux702.tar.gz" % os.getcwd())
variant('mpi', default=True, description='Set up MPI environment')
variant('smp', default=False, description='Set up SMP environment')
# Turbomole's install is odd. There are three variants
# - serial
# - parallel, MPI
# - parallel, SMP
#
# Only one of these can be active at a time. MPI and SMP are set as
# variants so there could be up to 3 installs per version. Switching
# between them would be accomplished with `module swap` commands.
def do_fetch(self, mirror_only=True):
if '+mpi' in self.spec and '+smp' in self.spec:
raise InstallError('Can not have both SMP and MPI enabled in the '
'same build.')
super(Turbomole, self).do_fetch(mirror_only)
def get_tm_arch(self):
if 'TURBOMOLE' in os.getcwd():
tm_sysname = Executable('./scripts/sysname')
tm_arch = tm_sysname(output=str)
return tm_arch.rstrip('\n')
else:
return
def install(self, spec, prefix):
calculate_version = 'calculate_2.4_linux64'
molecontrol_version = 'MoleControl_2.5'
tm_arch = self.get_tm_arch()
tar = which('tar')
dst = join_path(prefix, 'TURBOMOLE')
tar('-x', '-z', '-f', 'thermocalc.tar.gz')
with working_dir('thermocalc'):
subprocess.call('./install<<<y', shell=True)
install_tree('basen', join_path(dst, 'basen'))
install_tree('cabasen', join_path(dst, 'cabasen'))
install_tree(calculate_version, join_path(dst, calculate_version))
install_tree('cbasen', join_path(dst, 'cbasen'))
install_tree('DOC', join_path(dst, 'DOC'))
install_tree('jbasen', join_path(dst, 'jbasen'))
install_tree('jkbasen', join_path(dst, 'jkbasen'))
install_tree(molecontrol_version, join_path(dst, molecontrol_version))
install_tree('parameter', join_path(dst, 'parameter'))
install_tree('perlmodules', join_path(dst, 'perlmodules'))
install_tree('scripts', join_path(dst, 'scripts'))
install_tree('smprun_scripts', join_path(dst, 'smprun_scripts'))
install_tree('structures', join_path(dst, 'structures'))
install_tree('thermocalc', join_path(dst, 'thermocalc'))
install_tree('TURBOTEST', join_path(dst, 'TURBOTEST'))
install_tree('xbasen', join_path(dst, 'xbasen'))
install('Config_turbo_env', dst)
install('Config_turbo_env.tcsh', dst)
install('README', dst)
install('README_LICENSES', dst)
install('TURBOMOLE_702_LinuxPC', dst)
if '+mpi' in spec:
install_tree('bin/%s_mpi' % tm_arch,
join_path(dst, 'bin', '%s_mpi' % tm_arch))
install_tree('libso/%s_mpi' % tm_arch,
join_path(dst, 'libso', '%s_mpi' % tm_arch))
install_tree('mpirun_scripts/%s_mpi' % tm_arch,
join_path(dst, 'mpirun_scripts', '%s_mpi' % tm_arch))
elif '+smp' in spec:
install_tree('bin/%s_smp' % tm_arch,
join_path(dst, 'bin', '%s_smp' % tm_arch))
install_tree('libso/%s_smp' % tm_arch,
join_path(dst, 'libso', '%s_smp' % tm_arch))
install_tree('mpirun_scripts/%s_smp' % tm_arch,
join_path(dst, 'mpirun_scripts', '%s_smp' % tm_arch))
else:
install_tree('bin/%s' % tm_arch, join_path(dst, 'bin', tm_arch))
if '+mpi' in spec or '+smp' in spec:
install('mpirun_scripts/ccsdf12', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/dscf', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/grad', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/mpgrad', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/pnoccsd', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/rdgrad', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/ricc2', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/ridft', join_path(dst, 'mpirun_scripts'))
def setup_run_environment(self, env):
molecontrol_version = 'MoleControl_2.5'
tm_arch = self.get_tm_arch()
env.set('TURBODIR', self.prefix.TURBOMOLE)
env.set('MOLE_CONTROL',
join_path(self.prefix, 'TURBOMOLE', molecontrol_version))
env.prepend_path('PATH', self.prefix.TURBOMOLE.thermocalc)
env.prepend_path('PATH', self.prefix.TURBOMOLE.scripts)
if '+mpi' in self.spec:
env.set('PARA_ARCH', 'MPI')
env.prepend_path('PATH', join_path(
self.prefix, 'TURBOMOLE', 'bin', '%s_mpi' % tm_arch))
elif '+smp' in self.spec:
env.set('PARA_ARCH', 'SMP')
env.prepend_path('PATH', join_path(
self.prefix, 'TURBOMOLE', 'bin', '%s_smp' % tm_arch))
else:
env.prepend_path('PATH', join_path(
self.prefix, 'TURBOMOLE', 'bin', tm_arch))
|
iulian787/spack
|
var/spack/repos/builtin/packages/turbomole/package.py
|
Python
|
lgpl-2.1
| 6,080
|
[
"TURBOMOLE"
] |
e364da8a896de31d9a6d867e27cf7c1c0270330d61fa18c432b599143e83096f
|
##############################################################################
# Copyright (c) 2013-2018, 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/spack/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 shutil
class AtomDft(MakefilePackage):
"""ATOM is a program for DFT calculations in atoms and pseudopotential
generation."""
homepage = "https://departments.icmab.es/leem/siesta/Pseudopotentials/"
url = "https://departments.icmab.es/leem/siesta/Pseudopotentials/Code/atom-4.2.6.tgz"
version('4.2.6', 'c0c80cf349f951601942ed6c7cb0256b')
depends_on('libgridxc')
depends_on('xmlf90')
def edit(self, spec, prefix):
shutil.copyfile('arch.make.sample', 'arch.make')
@property
def build_targets(self):
return ['XMLF90_ROOT=%s' % self.spec['xmlf90'].prefix,
'GRIDXC_ROOT=%s' % self.spec['libgridxc'].prefix,
'FC=fc']
def install(self, spec, prefix):
mkdir(prefix.bin)
install('atm', prefix.bin)
|
EmreAtes/spack
|
var/spack/repos/builtin/packages/atom-dft/package.py
|
Python
|
lgpl-2.1
| 2,074
|
[
"SIESTA"
] |
fd5048cc050d1675790c2c71e51f401367667b971bc6710284dab31dee980935
|
#!/usr/bin/env python
# -----------------------------------------------------------------------------
# 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
from unittest import TestCase, main
from skbio.parse.sequences import parse_clustal, write_clustal
from skbio.parse.sequences.clustal import (_is_clustal_seq_line, last_space,
_delete_trailing_number)
from skbio.io import RecordError
class ClustalTests(TestCase):
"""Tests of top-level functions."""
def test_is_clustal_seq_line(self):
"""_is_clustal_seq_line should reject blanks and 'CLUSTAL'"""
ic = _is_clustal_seq_line
assert ic('abc')
assert ic('abc def')
assert not ic('CLUSTAL')
assert not ic('CLUSTAL W fsdhicjkjsdk')
assert not ic(' * *')
assert not ic(' abc def')
assert not ic('MUSCLE (3.41) multiple sequence alignment')
def test_last_space(self):
"""last_space should split on last whitespace"""
self.assertEqual(last_space('a\t\t\t b c'), ['a b', 'c'])
self.assertEqual(last_space('xyz'), ['xyz'])
self.assertEqual(last_space(' a b'), ['a', 'b'])
def test_delete_trailing_number(self):
"""Should delete the trailing number if present"""
dtn = _delete_trailing_number
self.assertEqual(dtn('abc'), 'abc')
self.assertEqual(dtn('a b c'), 'a b c')
self.assertEqual(dtn('a \t b \t c'), 'a \t b \t c')
self.assertEqual(dtn('a b 3'), 'a b')
self.assertEqual(dtn('a b c \t 345'), 'a b c')
class ClustalParserTests(TestCase):
"""Tests of the parse_clustal function"""
def test_null(self):
"""Should return empty dict and list on null input"""
result = parse_clustal([])
self.assertEqual(dict(result), {})
def test_minimal(self):
"""Should handle single-line input correctly"""
result = parse_clustal([MINIMAL]) # expects seq of lines
self.assertEqual(dict(result), {'abc': 'ucag'})
def test_two(self):
"""Should handle two-sequence input correctly"""
result = parse_clustal(TWO)
self.assertEqual(dict(result), {'abc': 'uuuaaa', 'def': 'cccggg'})
def test_real(self):
"""Should handle real Clustal output"""
data = parse_clustal(REAL)
self.assertEqual(dict(data), {
'abc':
'GCAUGCAUGCAUGAUCGUACGUCAGCAUGCUAGACUGCAUACGUACGUACGCAUGCAUCA'
'GUCGAUACGUACGUCAGUCAGUACGUCAGCAUGCAUACGUACGUCGUACGUACGU-CGAC'
'UGACUAGUCAGCUAGCAUCGAUCAGU',
'def':
'------------------------------------------------------------'
'-----------------------------------------CGCGAUGCAUGCAU-CGAU'
'CGAUCAGUCAGUCGAU----------',
'xyz':
'------------------------------------------------------------'
'-------------------------------------CAUGCAUCGUACGUACGCAUGAC'
'UGCUGCAUCA----------------'
})
def test_bad(self):
"""Should reject bad data if strict"""
result = parse_clustal(BAD, strict=False)
self.assertEqual(dict(result), {})
# should fail unless we turned strict processing off
with self.assertRaises(RecordError):
dict(parse_clustal(BAD))
def test_space_labels(self):
"""Should tolerate spaces in labels"""
result = parse_clustal(SPACE_LABELS)
self.assertEqual(dict(result), {'abc': 'uca', 'def ggg': 'ccc'})
def test_write(self):
"""Should write real Clustal output"""
import os
fname = "test.aln"
testfile = open(fname, 'w')
seqs = [('abc',
'GCAUGCAUGCAUGAUCGUACGUCAGCAUGCUAGACUGCAUACGUACGUACGCAUGCAUCA'
'GUCGAUACGUACGUCAGUCAGUACGUCAGCAUGCAUACGUACGUCGUACGUACGU-CGAC'
'UGACUAGUCAGCUAGCAUCGAUCAGU'),
('def',
'------------------------------------------------------------'
'-----------------------------------------CGCGAUGCAUGCAU-CGAU'
'CGAUCAGUCAGUCGAU----------'),
('xyz',
'------------------------------------------------------------'
'-------------------------------------CAUGCAUCGUACGUACGCAUGAC'
'UGCUGCAUCA----------------')]
records = (x for x in seqs)
write_clustal(records, testfile)
testfile.close()
raw = open(fname, 'r').read()
data = parse_clustal(raw.split('\n'))
data = list(data)
self.assertEqual(len(data), len(seqs))
self.assertEqual(set(data), set(seqs))
testfile.close()
os.remove(fname)
MINIMAL = 'abc\tucag'
TWO = 'abc\tuuu\ndef\tccc\n\n ***\n\ndef ggg\nabc\taaa\n'.split('\n')
REAL = """CLUSTAL W (1.82) multiple sequence alignment
abc GCAUGCAUGCAUGAUCGUACGUCAGCAUGCUAGACUGCAUACGUACGUACGCAUGCAUCA 60
def ------------------------------------------------------------
xyz ------------------------------------------------------------
abc GUCGAUACGUACGUCAGUCAGUACGUCAGCAUGCAUACGUACGUCGUACGUACGU-CGAC 11
def -----------------------------------------CGCGAUGCAUGCAU-CGAU 18
xyz -------------------------------------CAUGCAUCGUACGUACGCAUGAC 23
* * * * * **
abc UGACUAGUCAGCUAGCAUCGAUCAGU 145
def CGAUCAGUCAGUCGAU---------- 34
xyz UGCUGCAUCA---------------- 33
* ***""".split('\n')
BAD = ['dshfjsdfhdfsj', 'hfsdjksdfhjsdf']
SPACE_LABELS = ['abc uca', 'def ggg ccc']
if __name__ == '__main__':
main()
|
Kleptobismol/scikit-bio
|
skbio/parse/sequences/tests/test_clustal.py
|
Python
|
bsd-3-clause
| 6,048
|
[
"scikit-bio"
] |
8ac7a37172599b3513d74708069a0015bc8f9471ba77ed46db056744a8e06d7f
|
from typing import Any, DefaultDict, Dict, List, Set, Tuple, TypeVar, \
Union, Optional, Sequence, AbstractSet, Callable, Iterable
from typing.re import Match
from django.db import models
from django.db.models.query import QuerySet
from django.db.models import Manager, Sum, CASCADE
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, UserManager, \
PermissionsMixin
import django.contrib.auth
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator, MinLengthValidator, \
RegexValidator
from django.dispatch import receiver
from zerver.lib.cache import cache_with_key, flush_user_profile, flush_realm, \
user_profile_by_api_key_cache_key, active_non_guest_user_ids_cache_key, \
user_profile_by_id_cache_key, user_profile_by_email_cache_key, \
user_profile_cache_key, generic_bulk_cached_fetch, cache_set, flush_stream, \
display_recipient_cache_key, cache_delete, active_user_ids_cache_key, \
get_stream_cache_key, realm_user_dicts_cache_key, \
bot_dicts_in_realm_cache_key, realm_user_dict_fields, \
bot_dict_fields, flush_message, flush_submessage, bot_profile_cache_key, \
flush_used_upload_space_cache, get_realm_used_upload_space_cache_key
from zerver.lib.utils import make_safe_digest, generate_random_token
from django.db import transaction
from django.utils.timezone import now as timezone_now
from django.contrib.sessions.models import Session
from zerver.lib.timestamp import datetime_to_timestamp
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.translation import ugettext_lazy as _
from zerver.lib import cache
from zerver.lib.validator import check_int, \
check_short_string, check_long_string, validate_choice_field, check_date, \
check_url, check_list
from zerver.lib.name_restrictions import is_disposable_domain
from zerver.lib.types import Validator, ExtendedValidator, \
ProfileDataElement, ProfileData, RealmUserValidator, \
ExtendedFieldElement, UserFieldElement, FieldElement
from bitfield import BitField
from bitfield.types import BitHandler
from collections import defaultdict, OrderedDict
from datetime import timedelta
import pylibmc
import re
import sre_constants
import time
import datetime
MAX_TOPIC_NAME_LENGTH = 60
MAX_MESSAGE_LENGTH = 10000
MAX_LANGUAGE_ID_LENGTH = 50 # type: int
STREAM_NAMES = TypeVar('STREAM_NAMES', Sequence[str], AbstractSet[str])
def query_for_ids(query: QuerySet, user_ids: List[int], field: str) -> QuerySet:
'''
This function optimizes searches of the form
`user_profile_id in (1, 2, 3, 4)` by quickly
building the where clauses. Profiling shows significant
speedups over the normal Django-based approach.
Use this very carefully! Also, the caller should
guard against empty lists of user_ids.
'''
assert(user_ids)
value_list = ', '.join(str(int(user_id)) for user_id in user_ids)
clause = '%s in (%s)' % (field, value_list)
query = query.extra(
where=[clause]
)
return query
# Doing 1000 remote cache requests to get_display_recipient is quite slow,
# so add a local cache as well as the remote cache cache.
#
# This local cache has a lifetime of just a single request; it is
# cleared inside `flush_per_request_caches` in our middleware. It
# could be replaced with smarter bulk-fetching logic that deduplicates
# queries for the same recipient; this is just a convenient way to
# write that code.
per_request_display_recipient_cache = {} # type: Dict[int, Union[str, List[Dict[str, Any]]]]
def get_display_recipient_by_id(recipient_id: int, recipient_type: int,
recipient_type_id: Optional[int]) -> Union[str, List[Dict[str, Any]]]:
"""
returns: an object describing the recipient (using a cache).
If the type is a stream, the type_id must be an int; a string is returned.
Otherwise, type_id may be None; an array of recipient dicts is returned.
"""
if recipient_id not in per_request_display_recipient_cache:
result = get_display_recipient_remote_cache(recipient_id, recipient_type, recipient_type_id)
per_request_display_recipient_cache[recipient_id] = result
return per_request_display_recipient_cache[recipient_id]
def get_display_recipient(recipient: 'Recipient') -> Union[str, List[Dict[str, Any]]]:
return get_display_recipient_by_id(
recipient.id,
recipient.type,
recipient.type_id
)
def flush_per_request_caches() -> None:
global per_request_display_recipient_cache
per_request_display_recipient_cache = {}
global per_request_realm_filters_cache
per_request_realm_filters_cache = {}
DisplayRecipientCacheT = Union[str, List[Dict[str, Any]]]
@cache_with_key(lambda *args: display_recipient_cache_key(args[0]),
timeout=3600*24*7)
def get_display_recipient_remote_cache(recipient_id: int, recipient_type: int,
recipient_type_id: Optional[int]) -> DisplayRecipientCacheT:
"""
returns: an appropriate object describing the recipient. For a
stream this will be the stream name as a string. For a huddle or
personal, it will be an array of dicts about each recipient.
"""
if recipient_type == Recipient.STREAM:
assert recipient_type_id is not None
stream = Stream.objects.get(id=recipient_type_id)
return stream.name
# The main priority for ordering here is being deterministic.
# Right now, we order by ID, which matches the ordering of user
# names in the left sidebar.
user_profile_list = (UserProfile.objects.filter(subscription__recipient_id=recipient_id)
.select_related()
.order_by('id'))
return [{'email': user_profile.email,
'full_name': user_profile.full_name,
'short_name': user_profile.short_name,
'id': user_profile.id,
'is_mirror_dummy': user_profile.is_mirror_dummy} for user_profile in user_profile_list]
def get_realm_emoji_cache_key(realm: 'Realm') -> str:
return u'realm_emoji:%s' % (realm.id,)
def get_active_realm_emoji_cache_key(realm: 'Realm') -> str:
return u'active_realm_emoji:%s' % (realm.id,)
# This simple call-once caching saves ~500us in auth_enabled_helper,
# which is a significant optimization for common_context. Note that
# these values cannot change in a running production system, but do
# regularly change within unit tests; we address the latter by calling
# clear_supported_auth_backends_cache in our standard tearDown code.
supported_backends = None # type: Optional[Set[type]]
def supported_auth_backends() -> Set[type]:
global supported_backends
# Caching temporarily disabled for debugging
supported_backends = django.contrib.auth.get_backends()
assert supported_backends is not None
return supported_backends
def clear_supported_auth_backends_cache() -> None:
global supported_backends
supported_backends = None
class Realm(models.Model):
MAX_REALM_NAME_LENGTH = 40
MAX_REALM_SUBDOMAIN_LENGTH = 40
MAX_GOOGLE_HANGOUTS_DOMAIN_LENGTH = 255 # This is just the maximum domain length by RFC
INVITES_STANDARD_REALM_DAILY_MAX = 3000
MESSAGE_VISIBILITY_LIMITED = 10000
AUTHENTICATION_FLAGS = [u'Google', u'Email', u'GitHub', u'LDAP', u'Dev', u'RemoteUser', u'AzureAD']
SUBDOMAIN_FOR_ROOT_DOMAIN = ''
# User-visible display name and description used on e.g. the organization homepage
name = models.CharField(max_length=MAX_REALM_NAME_LENGTH, null=True) # type: Optional[str]
description = models.TextField(default=u"") # type: str
# A short, identifier-like name for the organization. Used in subdomains;
# e.g. on a server at example.com, an org with string_id `foo` is reached
# at `foo.example.com`.
string_id = models.CharField(max_length=MAX_REALM_SUBDOMAIN_LENGTH, unique=True) # type: str
date_created = models.DateTimeField(default=timezone_now) # type: datetime.datetime
deactivated = models.BooleanField(default=False) # type: bool
# See RealmDomain for the domains that apply for a given organization.
emails_restricted_to_domains = models.BooleanField(default=False) # type: bool
invite_required = models.BooleanField(default=True) # type: bool
invite_by_admins_only = models.BooleanField(default=False) # type: bool
_max_invites = models.IntegerField(null=True, db_column='max_invites') # type: Optional[int]
disallow_disposable_email_addresses = models.BooleanField(default=True) # type: bool
authentication_methods = BitField(flags=AUTHENTICATION_FLAGS,
default=2**31 - 1) # type: BitHandler
# Whether the organization has enabled inline image and URL previews.
inline_image_preview = models.BooleanField(default=True) # type: bool
inline_url_embed_preview = models.BooleanField(default=False) # type: bool
# Whether digest emails are enabled for the organization.
digest_emails_enabled = models.BooleanField(default=False) # type: bool
# Day of the week on which the digest is sent (default: Tuesday).
digest_weekday = models.SmallIntegerField(default=1) # type: int
send_welcome_emails = models.BooleanField(default=True) # type: bool
message_content_allowed_in_email_notifications = models.BooleanField(default=True) # type: bool
mandatory_topics = models.BooleanField(default=False) # type: bool
add_emoji_by_admins_only = models.BooleanField(default=False) # type: bool
name_changes_disabled = models.BooleanField(default=False) # type: bool
email_changes_disabled = models.BooleanField(default=False) # type: bool
avatar_changes_disabled = models.BooleanField(default=False) # type: bool
# Who in the organization is allowed to create streams.
CREATE_STREAM_POLICY_MEMBERS = 1
CREATE_STREAM_POLICY_ADMINS = 2
CREATE_STREAM_POLICY_WAITING_PERIOD = 3
create_stream_policy = models.PositiveSmallIntegerField(
default=CREATE_STREAM_POLICY_MEMBERS) # type: int
# Who in the organization is allowed to invite other users to streams.
INVITE_TO_STREAM_POLICY_MEMBERS = 1
INVITE_TO_STREAM_POLICY_ADMINS = 2
INVITE_TO_STREAM_POLICY_WAITING_PERIOD = 3
invite_to_stream_policy = models.PositiveSmallIntegerField(
default=INVITE_TO_STREAM_POLICY_MEMBERS) # type: int
# Who in the organization has access to users' actual email
# addresses. Controls whether the UserProfile.email field is the
# same as UserProfile.delivery_email, or is instead garbage.
EMAIL_ADDRESS_VISIBILITY_EVERYONE = 1
EMAIL_ADDRESS_VISIBILITY_MEMBERS = 2
EMAIL_ADDRESS_VISIBILITY_ADMINS = 3
email_address_visibility = models.PositiveSmallIntegerField(default=EMAIL_ADDRESS_VISIBILITY_EVERYONE) # type: int
EMAIL_ADDRESS_VISIBILITY_TYPES = [
EMAIL_ADDRESS_VISIBILITY_EVERYONE,
# The MEMBERS level is not yet implemented on the backend.
## EMAIL_ADDRESS_VISIBILITY_MEMBERS,
EMAIL_ADDRESS_VISIBILITY_ADMINS,
]
# Threshold in days for new users to create streams, and potentially take
# some other actions.
waiting_period_threshold = models.PositiveIntegerField(default=0) # type: int
allow_message_deleting = models.BooleanField(default=False) # type: bool
DEFAULT_MESSAGE_CONTENT_DELETE_LIMIT_SECONDS = 600 # if changed, also change in admin.js, setting_org.js
message_content_delete_limit_seconds = models.IntegerField(default=DEFAULT_MESSAGE_CONTENT_DELETE_LIMIT_SECONDS) # type: int
allow_message_editing = models.BooleanField(default=True) # type: bool
DEFAULT_MESSAGE_CONTENT_EDIT_LIMIT_SECONDS = 600 # if changed, also change in admin.js, setting_org.js
message_content_edit_limit_seconds = models.IntegerField(default=DEFAULT_MESSAGE_CONTENT_EDIT_LIMIT_SECONDS) # type: int
# Whether users have access to message edit history
allow_edit_history = models.BooleanField(default=True) # type: bool
DEFAULT_COMMUNITY_TOPIC_EDITING_LIMIT_SECONDS = 86400
allow_community_topic_editing = models.BooleanField(default=True) # type: bool
# Defaults for new users
default_twenty_four_hour_time = models.BooleanField(default=False) # type: bool
default_language = models.CharField(default=u'en', max_length=MAX_LANGUAGE_ID_LENGTH) # type: str
DEFAULT_NOTIFICATION_STREAM_NAME = u'general'
INITIAL_PRIVATE_STREAM_NAME = u'core team'
STREAM_EVENTS_NOTIFICATION_TOPIC = _('stream events')
notifications_stream = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE) # type: Optional[Stream]
signup_notifications_stream = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE) # type: Optional[Stream]
# For old messages being automatically deleted
message_retention_days = models.IntegerField(null=True) # type: Optional[int]
# When non-null, all but the latest this many messages in the organization
# are inaccessible to users (but not deleted).
message_visibility_limit = models.IntegerField(null=True) # type: Optional[int]
# Messages older than this message ID in the organization are inaccessible.
first_visible_message_id = models.IntegerField(default=0) # type: int
# Valid org_types are {CORPORATE, COMMUNITY}
CORPORATE = 1
COMMUNITY = 2
org_type = models.PositiveSmallIntegerField(default=CORPORATE) # type: int
UPGRADE_TEXT_STANDARD = _("Available on Zulip Standard. Upgrade to access.")
# plan_type controls various features around resource/feature
# limitations for a Zulip organization on multi-tenant servers
# like zulipchat.com.
SELF_HOSTED = 1
LIMITED = 2
STANDARD = 3
STANDARD_FREE = 4
plan_type = models.PositiveSmallIntegerField(default=SELF_HOSTED) # type: int
# This value is also being used in static/js/settings_bots.bot_creation_policy_values.
# On updating it here, update it there as well.
BOT_CREATION_EVERYONE = 1
BOT_CREATION_LIMIT_GENERIC_BOTS = 2
BOT_CREATION_ADMINS_ONLY = 3
bot_creation_policy = models.PositiveSmallIntegerField(default=BOT_CREATION_EVERYONE) # type: int
# See upload_quota_bytes; don't interpret upload_quota_gb directly.
UPLOAD_QUOTA_LIMITED = 5
UPLOAD_QUOTA_STANDARD = 50
upload_quota_gb = models.IntegerField(null=True) # type: Optional[int]
VIDEO_CHAT_PROVIDERS = {
'jitsi_meet': {
'name': u"Jitsi Meet",
'id': 1
},
'google_hangouts': {
'name': u"Google Hangouts",
'id': 2
},
'zoom': {
'name': u"Zoom",
'id': 3
}
}
video_chat_provider = models.PositiveSmallIntegerField(default=VIDEO_CHAT_PROVIDERS['jitsi_meet']['id'])
google_hangouts_domain = models.TextField(default="")
zoom_user_id = models.TextField(default="")
zoom_api_key = models.TextField(default="")
zoom_api_secret = models.TextField(default="")
# Define the types of the various automatically managed properties
property_types = dict(
add_emoji_by_admins_only=bool,
allow_edit_history=bool,
allow_message_deleting=bool,
bot_creation_policy=int,
create_stream_policy=int,
invite_to_stream_policy=int,
default_language=str,
default_twenty_four_hour_time = bool,
description=str,
digest_emails_enabled=bool,
disallow_disposable_email_addresses=bool,
email_address_visibility=int,
email_changes_disabled=bool,
google_hangouts_domain=str,
zoom_user_id=str,
zoom_api_key=str,
zoom_api_secret=str,
invite_required=bool,
invite_by_admins_only=bool,
inline_image_preview=bool,
inline_url_embed_preview=bool,
mandatory_topics=bool,
message_retention_days=(int, type(None)),
name=str,
name_changes_disabled=bool,
avatar_changes_disabled=bool,
emails_restricted_to_domains=bool,
send_welcome_emails=bool,
message_content_allowed_in_email_notifications=bool,
video_chat_provider=int,
waiting_period_threshold=int,
digest_weekday=int,
) # type: Dict[str, Union[type, Tuple[type, ...]]]
# Icon is the square mobile icon.
ICON_FROM_GRAVATAR = u'G'
ICON_UPLOADED = u'U'
ICON_SOURCES = (
(ICON_FROM_GRAVATAR, 'Hosted by Gravatar'),
(ICON_UPLOADED, 'Uploaded by administrator'),
)
icon_source = models.CharField(default=ICON_FROM_GRAVATAR, choices=ICON_SOURCES,
max_length=1) # type: str
icon_version = models.PositiveSmallIntegerField(default=1) # type: int
# Logo is the horizonal logo we show in top-left of webapp navbar UI.
LOGO_DEFAULT = u'D'
LOGO_UPLOADED = u'U'
LOGO_SOURCES = (
(LOGO_DEFAULT, 'Default to Zulip'),
(LOGO_UPLOADED, 'Uploaded by administrator'),
)
logo_source = models.CharField(default=LOGO_DEFAULT, choices=LOGO_SOURCES,
max_length=1) # type: str
logo_version = models.PositiveSmallIntegerField(default=1) # type: int
night_logo_source = models.CharField(default=LOGO_DEFAULT, choices=LOGO_SOURCES,
max_length=1) # type: str
night_logo_version = models.PositiveSmallIntegerField(default=1) # type: int
BOT_CREATION_POLICY_TYPES = [
BOT_CREATION_EVERYONE,
BOT_CREATION_LIMIT_GENERIC_BOTS,
BOT_CREATION_ADMINS_ONLY,
]
def authentication_methods_dict(self) -> Dict[str, bool]:
"""Returns the a mapping from authentication flags to their status,
showing only those authentication flags that are supported on
the current server (i.e. if EmailAuthBackend is not configured
on the server, this will not return an entry for "Email")."""
# This mapping needs to be imported from here due to the cyclic
# dependency.
from zproject.backends import AUTH_BACKEND_NAME_MAP
ret = {} # type: Dict[str, bool]
supported_backends = [backend.__class__ for backend in supported_auth_backends()]
for k, v in self.authentication_methods.iteritems():
backend = AUTH_BACKEND_NAME_MAP[k]
if backend in supported_backends:
ret[k] = v
return ret
def __str__(self) -> str:
return "<Realm: %s %s>" % (self.string_id, self.id)
@cache_with_key(get_realm_emoji_cache_key, timeout=3600*24*7)
def get_emoji(self) -> Dict[str, Dict[str, Iterable[str]]]:
return get_realm_emoji_uncached(self)
@cache_with_key(get_active_realm_emoji_cache_key, timeout=3600*24*7)
def get_active_emoji(self) -> Dict[str, Dict[str, Iterable[str]]]:
return get_active_realm_emoji_uncached(self)
def get_admin_users_and_bots(self) -> Sequence['UserProfile']:
"""Use this in contexts where we want administrative users as well as
bots with administrator privileges, like send_event calls for
notifications to all administrator users.
"""
# TODO: Change return type to QuerySet[UserProfile]
return UserProfile.objects.filter(realm=self, is_realm_admin=True,
is_active=True)
def get_human_admin_users(self) -> Sequence['UserProfile']:
"""Use this in contexts where we want only human users with
administrative privileges, like sending an email to all of a
realm's administrators (bots don't have real email addresses).
"""
# TODO: Change return type to QuerySet[UserProfile]
return UserProfile.objects.filter(realm=self, is_bot=False, is_realm_admin=True,
is_active=True)
def get_active_users(self) -> Sequence['UserProfile']:
# TODO: Change return type to QuerySet[UserProfile]
return UserProfile.objects.filter(realm=self, is_active=True).select_related()
def get_bot_domain(self) -> str:
# Remove the port. Mainly needed for development environment.
return self.host.split(':')[0]
def get_notifications_stream(self) -> Optional['Stream']:
if self.notifications_stream is not None and not self.notifications_stream.deactivated:
return self.notifications_stream
return None
def get_signup_notifications_stream(self) -> Optional['Stream']:
if self.signup_notifications_stream is not None and not self.signup_notifications_stream.deactivated:
return self.signup_notifications_stream
return None
@property
def max_invites(self) -> int:
if self._max_invites is None:
return settings.INVITES_DEFAULT_REALM_DAILY_MAX
return self._max_invites
@max_invites.setter
def max_invites(self, value: int) -> None:
self._max_invites = value
def upload_quota_bytes(self) -> Optional[int]:
if self.upload_quota_gb is None:
return None
# We describe the quota to users in "GB" or "gigabytes", but actually apply
# it as gibibytes (GiB) to be a bit more generous in case of confusion.
return self.upload_quota_gb << 30
@cache_with_key(get_realm_used_upload_space_cache_key, timeout=3600*24*7)
def currently_used_upload_space_bytes(self) -> int:
used_space = Attachment.objects.filter(realm=self).aggregate(Sum('size'))['size__sum']
if used_space is None:
return 0
return used_space
@property
def subdomain(self) -> str:
return self.string_id
@property
def display_subdomain(self) -> str:
"""Likely to be temporary function to avoid signup messages being sent
to an empty topic"""
if self.string_id == "":
return "."
return self.string_id
@property
def uri(self) -> str:
return settings.EXTERNAL_URI_SCHEME + self.host
@property
def host(self) -> str:
return self.host_for_subdomain(self.subdomain)
@staticmethod
def host_for_subdomain(subdomain: str) -> str:
if subdomain == Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:
return settings.EXTERNAL_HOST
default_host = "%s.%s" % (subdomain, settings.EXTERNAL_HOST)
return settings.REALM_HOSTS.get(subdomain, default_host)
@property
def is_zephyr_mirror_realm(self) -> bool:
return self.string_id == "zephyr"
@property
def webathena_enabled(self) -> bool:
return self.is_zephyr_mirror_realm
@property
def presence_disabled(self) -> bool:
return self.is_zephyr_mirror_realm
class Meta:
permissions = (
('administer', "Administer a realm"),
('api_super_user', "Can send messages as other users for mirroring"),
)
post_save.connect(flush_realm, sender=Realm)
def get_realm(string_id: str) -> Realm:
return Realm.objects.get(string_id=string_id)
def name_changes_disabled(realm: Optional[Realm]) -> bool:
if realm is None:
return settings.NAME_CHANGES_DISABLED
return settings.NAME_CHANGES_DISABLED or realm.name_changes_disabled
def avatar_changes_disabled(realm: Realm) -> bool:
return settings.AVATAR_CHANGES_DISABLED or realm.avatar_changes_disabled
class RealmDomain(models.Model):
"""For an organization with emails_restricted_to_domains enabled, the list of
allowed domains"""
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
# should always be stored lowercase
domain = models.CharField(max_length=80, db_index=True) # type: str
allow_subdomains = models.BooleanField(default=False)
class Meta:
unique_together = ("realm", "domain")
# These functions should only be used on email addresses that have
# been validated via django.core.validators.validate_email
#
# Note that we need to use some care, since can you have multiple @-signs; e.g.
# "tabbott@test"@zulip.com
# is valid email address
def email_to_username(email: str) -> str:
return "@".join(email.split("@")[:-1]).lower()
# Returns the raw domain portion of the desired email address
def email_to_domain(email: str) -> str:
return email.split("@")[-1].lower()
class DomainNotAllowedForRealmError(Exception):
pass
class DisposableEmailError(Exception):
pass
class EmailContainsPlusError(Exception):
pass
# Is a user with the given email address allowed to be in the given realm?
# (This function does not check whether the user has been invited to the realm.
# So for invite-only realms, this is the test for whether a user can be invited,
# not whether the user can sign up currently.)
def email_allowed_for_realm(email: str, realm: Realm) -> None:
if not realm.emails_restricted_to_domains:
if realm.disallow_disposable_email_addresses and \
is_disposable_domain(email_to_domain(email)):
raise DisposableEmailError
return
elif '+' in email_to_username(email):
raise EmailContainsPlusError
domain = email_to_domain(email)
query = RealmDomain.objects.filter(realm=realm)
if query.filter(domain=domain).exists():
return
else:
query = query.filter(allow_subdomains=True)
while len(domain) > 0:
subdomain, sep, domain = domain.partition('.')
if query.filter(domain=domain).exists():
return
raise DomainNotAllowedForRealmError
def get_realm_domains(realm: Realm) -> List[Dict[str, str]]:
return list(realm.realmdomain_set.values('domain', 'allow_subdomains'))
class RealmEmoji(models.Model):
author = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE) # type: Optional[UserProfile]
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
name = models.TextField(validators=[
MinLengthValidator(1),
# The second part of the regex (negative lookbehind) disallows names
# ending with one of the punctuation characters.
RegexValidator(regex=r'^[0-9a-z.\-_]+(?<![.\-_])$',
message=_("Invalid characters in emoji name"))]) # type: str
# The basename of the custom emoji's filename; see PATH_ID_TEMPLATE for the full path.
file_name = models.TextField(db_index=True, null=True, blank=True) # type: Optional[str]
deactivated = models.BooleanField(default=False) # type: bool
PATH_ID_TEMPLATE = "{realm_id}/emoji/images/{emoji_file_name}"
def __str__(self) -> str:
return "<RealmEmoji(%s): %s %s %s %s>" % (self.realm.string_id,
self.id,
self.name,
self.deactivated,
self.file_name)
def get_realm_emoji_dicts(realm: Realm,
only_active_emojis: bool=False) -> Dict[str, Dict[str, Any]]:
query = RealmEmoji.objects.filter(realm=realm).select_related('author')
if only_active_emojis:
query = query.filter(deactivated=False)
d = {}
from zerver.lib.emoji import get_emoji_url
for realm_emoji in query.all():
author = None
if realm_emoji.author:
author = {
'id': realm_emoji.author.id,
'email': realm_emoji.author.email,
'full_name': realm_emoji.author.full_name}
emoji_url = get_emoji_url(realm_emoji.file_name, realm_emoji.realm_id)
d[str(realm_emoji.id)] = dict(id=str(realm_emoji.id),
name=realm_emoji.name,
source_url=emoji_url,
deactivated=realm_emoji.deactivated,
author=author)
return d
def get_realm_emoji_uncached(realm: Realm) -> Dict[str, Dict[str, Any]]:
return get_realm_emoji_dicts(realm)
def get_active_realm_emoji_uncached(realm: Realm) -> Dict[str, Dict[str, Any]]:
realm_emojis = get_realm_emoji_dicts(realm, only_active_emojis=True)
d = {}
for emoji_id, emoji_dict in realm_emojis.items():
d[emoji_dict['name']] = emoji_dict
return d
def flush_realm_emoji(sender: Any, **kwargs: Any) -> None:
realm = kwargs['instance'].realm
cache_set(get_realm_emoji_cache_key(realm),
get_realm_emoji_uncached(realm),
timeout=3600*24*7)
cache_set(get_active_realm_emoji_cache_key(realm),
get_active_realm_emoji_uncached(realm),
timeout=3600*24*7)
post_save.connect(flush_realm_emoji, sender=RealmEmoji)
post_delete.connect(flush_realm_emoji, sender=RealmEmoji)
def filter_pattern_validator(value: str) -> None:
regex = re.compile(r'^(?:(?:[\w\-#_= /:]*|[+]|[!])(\(\?P<\w+>.+\)))+$')
error_msg = _('Invalid filter pattern. Valid characters are %s.') % (
'[ a-zA-Z_#=/:+!-]',)
if not regex.match(str(value)):
raise ValidationError(error_msg)
try:
re.compile(value)
except sre_constants.error:
# Regex is invalid
raise ValidationError(error_msg)
def filter_format_validator(value: str) -> None:
regex = re.compile(r'^([\.\/:a-zA-Z0-9#_?=&;-]+%\(([a-zA-Z0-9_-]+)\)s)+[/a-zA-Z0-9#_?=&;-]*$')
if not regex.match(value):
raise ValidationError(_('Invalid URL format string.'))
class RealmFilter(models.Model):
"""Realm-specific regular expressions to automatically linkify certain
strings inside the markdown processor. See "Custom filters" in the settings UI.
"""
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
pattern = models.TextField(validators=[filter_pattern_validator]) # type: str
url_format_string = models.TextField(validators=[URLValidator(), filter_format_validator]) # type: str
class Meta:
unique_together = ("realm", "pattern")
def __str__(self) -> str:
return "<RealmFilter(%s): %s %s>" % (self.realm.string_id, self.pattern, self.url_format_string)
def get_realm_filters_cache_key(realm_id: int) -> str:
return u'%s:all_realm_filters:%s' % (cache.KEY_PREFIX, realm_id,)
# We have a per-process cache to avoid doing 1000 remote cache queries during page load
per_request_realm_filters_cache = {} # type: Dict[int, List[Tuple[str, str, int]]]
def realm_in_local_realm_filters_cache(realm_id: int) -> bool:
return realm_id in per_request_realm_filters_cache
def realm_filters_for_realm(realm_id: int) -> List[Tuple[str, str, int]]:
if not realm_in_local_realm_filters_cache(realm_id):
per_request_realm_filters_cache[realm_id] = realm_filters_for_realm_remote_cache(realm_id)
return per_request_realm_filters_cache[realm_id]
@cache_with_key(get_realm_filters_cache_key, timeout=3600*24*7)
def realm_filters_for_realm_remote_cache(realm_id: int) -> List[Tuple[str, str, int]]:
filters = []
for realm_filter in RealmFilter.objects.filter(realm_id=realm_id):
filters.append((realm_filter.pattern, realm_filter.url_format_string, realm_filter.id))
return filters
def all_realm_filters() -> Dict[int, List[Tuple[str, str, int]]]:
filters = defaultdict(list) # type: DefaultDict[int, List[Tuple[str, str, int]]]
for realm_filter in RealmFilter.objects.all():
filters[realm_filter.realm_id].append((realm_filter.pattern,
realm_filter.url_format_string,
realm_filter.id))
return filters
def flush_realm_filter(sender: Any, **kwargs: Any) -> None:
realm_id = kwargs['instance'].realm_id
cache_delete(get_realm_filters_cache_key(realm_id))
try:
per_request_realm_filters_cache.pop(realm_id)
except KeyError:
pass
post_save.connect(flush_realm_filter, sender=RealmFilter)
post_delete.connect(flush_realm_filter, sender=RealmFilter)
class UserProfile(AbstractBaseUser, PermissionsMixin):
USERNAME_FIELD = 'email'
MAX_NAME_LENGTH = 100
MIN_NAME_LENGTH = 2
API_KEY_LENGTH = 32
NAME_INVALID_CHARS = ['*', '`', "\\", '>', '"', '@']
DEFAULT_BOT = 1
"""
Incoming webhook bots are limited to only sending messages via webhooks.
Thus, it is less of a security risk to expose their API keys to third-party services,
since they can't be used to read messages.
"""
INCOMING_WEBHOOK_BOT = 2
# This value is also being used in static/js/settings_bots.js.
# On updating it here, update it there as well.
OUTGOING_WEBHOOK_BOT = 3
"""
Embedded bots run within the Zulip server itself; events are added to the
embedded_bots queue and then handled by a QueueProcessingWorker.
"""
EMBEDDED_BOT = 4
BOT_TYPES = {
DEFAULT_BOT: 'Generic bot',
INCOMING_WEBHOOK_BOT: 'Incoming webhook',
OUTGOING_WEBHOOK_BOT: 'Outgoing webhook',
EMBEDDED_BOT: 'Embedded bot',
}
SERVICE_BOT_TYPES = [
OUTGOING_WEBHOOK_BOT,
EMBEDDED_BOT,
]
# The display email address, used for Zulip APIs, etc. This field
# should never be used for actually emailing someone because it
# will be invalid for various values of
# Realm.email_address_visibility; for that, see delivery_email.
email = models.EmailField(blank=False, db_index=True) # type: str
# delivery_email is just used for sending emails. In almost all
# organizations, it matches `email`; this field is part of our
# transition towards supporting organizations where email
# addresses are not public.
delivery_email = models.EmailField(blank=False, db_index=True) # type: str
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
full_name = models.CharField(max_length=MAX_NAME_LENGTH) # type: str
# short_name is currently unused.
short_name = models.CharField(max_length=MAX_NAME_LENGTH) # type: str
date_joined = models.DateTimeField(default=timezone_now) # type: datetime.datetime
tos_version = models.CharField(null=True, max_length=10) # type: Optional[str]
api_key = models.CharField(max_length=API_KEY_LENGTH) # type: str
# pointer points to Message.id, NOT UserMessage.id.
pointer = models.IntegerField() # type: int
last_pointer_updater = models.CharField(max_length=64) # type: str
# Whether the user has access to server-level administrator pages, like /activity
is_staff = models.BooleanField(default=False) # type: bool
# For a normal user, this is True unless the user or an admin has
# deactivated their account. The name comes from Django; this field
# isn't related to presence or to whether the user has recently used Zulip.
#
# See also `long_term_idle`.
is_active = models.BooleanField(default=True, db_index=True) # type: bool
is_realm_admin = models.BooleanField(default=False, db_index=True) # type: bool
is_billing_admin = models.BooleanField(default=False, db_index=True) # type: bool
# Guest users are limited users without default access to public streams (etc.)
is_guest = models.BooleanField(default=False, db_index=True) # type: bool
is_bot = models.BooleanField(default=False, db_index=True) # type: bool
bot_type = models.PositiveSmallIntegerField(null=True, db_index=True) # type: Optional[int]
bot_owner = models.ForeignKey('self', null=True, on_delete=models.SET_NULL) # type: Optional[UserProfile]
# Whether the user has been "soft-deactivated" due to weeks of inactivity.
# For these users we avoid doing UserMessage table work, as an optimization
# for large Zulip organizations with lots of single-visit users.
long_term_idle = models.BooleanField(default=False, db_index=True) # type: bool
# When we last added basic UserMessage rows for a long_term_idle user.
last_active_message_id = models.IntegerField(null=True) # type: Optional[int]
# Mirror dummies are fake (!is_active) users used to provide
# message senders in our cross-protocol Zephyr<->Zulip content
# mirroring integration, so that we can display mirrored content
# like native Zulip messages (with a name + avatar, etc.).
is_mirror_dummy = models.BooleanField(default=False) # type: bool
# API super users are allowed to forge messages as sent by another
# user and to send to private streams; also used for Zephyr/Jabber mirroring.
is_api_super_user = models.BooleanField(default=False, db_index=True) # type: bool
### Notifications settings. ###
# Stream notifications.
enable_stream_desktop_notifications = models.BooleanField(default=False) # type: bool
enable_stream_email_notifications = models.BooleanField(default=False) # type: bool
enable_stream_push_notifications = models.BooleanField(default=False) # type: bool
enable_stream_audible_notifications = models.BooleanField(default=False) # type: bool
notification_sound = models.CharField(max_length=20, default='zulip') # type: str
# PM + @-mention notifications.
enable_desktop_notifications = models.BooleanField(default=True) # type: bool
pm_content_in_desktop_notifications = models.BooleanField(default=True) # type: bool
enable_sounds = models.BooleanField(default=True) # type: bool
enable_offline_email_notifications = models.BooleanField(default=True) # type: bool
message_content_in_email_notifications = models.BooleanField(default=True) # type: bool
enable_offline_push_notifications = models.BooleanField(default=True) # type: bool
enable_online_push_notifications = models.BooleanField(default=False) # type: bool
DESKTOP_ICON_COUNT_DISPLAY_MESSAGES = 1
DESKTOP_ICON_COUNT_DISPLAY_NOTIFIABLE = 2
desktop_icon_count_display = models.PositiveSmallIntegerField(
default=DESKTOP_ICON_COUNT_DISPLAY_MESSAGES) # type: int
enable_digest_emails = models.BooleanField(default=True) # type: bool
enable_login_emails = models.BooleanField(default=True) # type: bool
realm_name_in_notifications = models.BooleanField(default=False) # type: bool
# Words that trigger a mention for this user, formatted as a json-serialized list of strings
alert_words = models.TextField(default=u'[]') # type: str
# Used for rate-limiting certain automated messages generated by bots
last_reminder = models.DateTimeField(default=None, null=True) # type: Optional[datetime.datetime]
# Minutes to wait before warning a bot owner that their bot sent a message
# to a nonexistent stream
BOT_OWNER_STREAM_ALERT_WAITPERIOD = 1
# API rate limits, formatted as a comma-separated list of range:max pairs
rate_limits = models.CharField(default=u"", max_length=100) # type: str
# Hours to wait before sending another email to a user
EMAIL_REMINDER_WAITPERIOD = 24
# Default streams for some deprecated/legacy classes of bot users.
default_sending_stream = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE) # type: Optional[Stream]
default_events_register_stream = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE) # type: Optional[Stream]
default_all_public_streams = models.BooleanField(default=False) # type: bool
# UI vars
enter_sends = models.NullBooleanField(default=False) # type: Optional[bool]
left_side_userlist = models.BooleanField(default=False) # type: bool
# display settings
default_language = models.CharField(default=u'en', max_length=MAX_LANGUAGE_ID_LENGTH) # type: str
dense_mode = models.BooleanField(default=True) # type: bool
fluid_layout_width = models.BooleanField(default=False) # type: bool
high_contrast_mode = models.BooleanField(default=False) # type: bool
night_mode = models.BooleanField(default=False) # type: bool
translate_emoticons = models.BooleanField(default=False) # type: bool
twenty_four_hour_time = models.BooleanField(default=False) # type: bool
starred_message_counts = models.BooleanField(default=False) # type: bool
# UI setting controlling Zulip's behavior of demoting in the sort
# order and graying out streams with no recent traffic. The
# default behavior, automatic, enables this behavior once a user
# is subscribed to 30+ streams in the webapp.
DEMOTE_STREAMS_AUTOMATIC = 1
DEMOTE_STREAMS_ALWAYS = 2
DEMOTE_STREAMS_NEVER = 3
DEMOTE_STREAMS_CHOICES = [
DEMOTE_STREAMS_AUTOMATIC,
DEMOTE_STREAMS_ALWAYS,
DEMOTE_STREAMS_NEVER
]
demote_inactive_streams = models.PositiveSmallIntegerField(default=DEMOTE_STREAMS_AUTOMATIC)
# A timezone name from the `tzdata` database, as found in pytz.all_timezones.
#
# The longest existing name is 32 characters long, so max_length=40 seems
# like a safe choice.
#
# In Django, the convention is to use an empty string instead of NULL/None
# for text-based fields. For more information, see
# https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.Field.null.
timezone = models.CharField(max_length=40, default=u'') # type: str
# Emojisets
GOOGLE_EMOJISET = 'google'
GOOGLE_BLOB_EMOJISET = 'google-blob'
TEXT_EMOJISET = 'text'
TWITTER_EMOJISET = 'twitter'
EMOJISET_CHOICES = ((GOOGLE_EMOJISET, "Google modern"),
(GOOGLE_BLOB_EMOJISET, "Google classic"),
(TWITTER_EMOJISET, "Twitter"),
(TEXT_EMOJISET, "Plain text"))
emojiset = models.CharField(default=GOOGLE_BLOB_EMOJISET, choices=EMOJISET_CHOICES, max_length=20) # type: str
AVATAR_FROM_GRAVATAR = u'G'
AVATAR_FROM_USER = u'U'
AVATAR_SOURCES = (
(AVATAR_FROM_GRAVATAR, 'Hosted by Gravatar'),
(AVATAR_FROM_USER, 'Uploaded by user'),
)
avatar_source = models.CharField(default=AVATAR_FROM_GRAVATAR, choices=AVATAR_SOURCES, max_length=1) # type: str
avatar_version = models.PositiveSmallIntegerField(default=1) # type: int
avatar_hash = models.CharField(null=True, max_length=64) # type: Optional[str]
TUTORIAL_WAITING = u'W'
TUTORIAL_STARTED = u'S'
TUTORIAL_FINISHED = u'F'
TUTORIAL_STATES = ((TUTORIAL_WAITING, "Waiting"),
(TUTORIAL_STARTED, "Started"),
(TUTORIAL_FINISHED, "Finished"))
tutorial_status = models.CharField(default=TUTORIAL_WAITING, choices=TUTORIAL_STATES, max_length=1) # type: str
# Contains serialized JSON of the form:
# [("step 1", true), ("step 2", false)]
# where the second element of each tuple is if the step has been
# completed.
onboarding_steps = models.TextField(default=u'[]') # type: str
objects = UserManager() # type: UserManager
# Define the types of the various automatically managed properties
property_types = dict(
default_language=str,
demote_inactive_streams=int,
dense_mode=bool,
emojiset=str,
fluid_layout_width=bool,
high_contrast_mode=bool,
left_side_userlist=bool,
night_mode=bool,
starred_message_counts=bool,
timezone=str,
translate_emoticons=bool,
twenty_four_hour_time=bool,
)
notification_setting_types = dict(
enable_desktop_notifications=bool,
enable_digest_emails=bool,
enable_login_emails=bool,
enable_offline_email_notifications=bool,
enable_offline_push_notifications=bool,
enable_online_push_notifications=bool,
enable_sounds=bool,
enable_stream_desktop_notifications=bool,
enable_stream_email_notifications=bool,
enable_stream_push_notifications=bool,
enable_stream_audible_notifications=bool,
message_content_in_email_notifications=bool,
notification_sound=str,
pm_content_in_desktop_notifications=bool,
desktop_icon_count_display=int,
realm_name_in_notifications=bool,
)
class Meta:
unique_together = (('realm', 'email'),)
@property
def profile_data(self) -> ProfileData:
values = CustomProfileFieldValue.objects.filter(user_profile=self)
user_data = {v.field_id: {"value": v.value, "rendered_value": v.rendered_value} for v in values}
data = [] # type: ProfileData
for field in custom_profile_fields_for_realm(self.realm_id):
field_values = user_data.get(field.id, None)
if field_values:
value, rendered_value = field_values.get("value"), field_values.get("rendered_value")
else:
value, rendered_value = None, None
field_type = field.field_type
if value is not None:
converter = field.FIELD_CONVERTERS[field_type]
value = converter(value)
field_data = field.as_dict()
field_data['value'] = value
field_data['rendered_value'] = rendered_value
data.append(field_data)
return data
def can_admin_user(self, target_user: 'UserProfile') -> bool:
"""Returns whether this user has permission to modify target_user"""
if target_user.bot_owner == self:
return True
elif self.is_realm_admin and self.realm == target_user.realm:
return True
else:
return False
def __str__(self) -> str:
return "<UserProfile: %s %s>" % (self.email, self.realm)
@property
def is_incoming_webhook(self) -> bool:
return self.bot_type == UserProfile.INCOMING_WEBHOOK_BOT
@property
def allowed_bot_types(self) -> List[int]:
allowed_bot_types = []
if self.is_realm_admin or \
not self.realm.bot_creation_policy == Realm.BOT_CREATION_LIMIT_GENERIC_BOTS:
allowed_bot_types.append(UserProfile.DEFAULT_BOT)
allowed_bot_types += [
UserProfile.INCOMING_WEBHOOK_BOT,
UserProfile.OUTGOING_WEBHOOK_BOT,
]
if settings.EMBEDDED_BOTS_ENABLED:
allowed_bot_types.append(UserProfile.EMBEDDED_BOT)
return allowed_bot_types
@staticmethod
def emojiset_choices() -> Dict[str, str]:
return OrderedDict((emojiset[0], emojiset[1]) for emojiset in UserProfile.EMOJISET_CHOICES)
@staticmethod
def emails_from_ids(user_ids: Sequence[int]) -> Dict[int, str]:
rows = UserProfile.objects.filter(id__in=user_ids).values('id', 'email')
return {row['id']: row['email'] for row in rows}
def can_create_streams(self) -> bool:
if self.is_realm_admin:
return True
if self.realm.create_stream_policy == Realm.CREATE_STREAM_POLICY_ADMINS:
return False
if self.is_guest:
return False
if self.realm.create_stream_policy == Realm.CREATE_STREAM_POLICY_MEMBERS:
return True
diff = (timezone_now() - self.date_joined).days
if diff >= self.realm.waiting_period_threshold:
return True
return False
def can_subscribe_other_users(self) -> bool:
if self.is_realm_admin:
return True
if self.realm.invite_to_stream_policy == Realm.INVITE_TO_STREAM_POLICY_ADMINS:
return False
if self.is_guest:
return False
if self.realm.invite_to_stream_policy == Realm.INVITE_TO_STREAM_POLICY_MEMBERS:
return True
assert self.realm.invite_to_stream_policy == Realm.INVITE_TO_STREAM_POLICY_WAITING_PERIOD
diff = (timezone_now() - self.date_joined).days
if diff >= self.realm.waiting_period_threshold:
return True
return False
def can_access_public_streams(self) -> bool:
return not (self.is_guest or self.realm.is_zephyr_mirror_realm)
def can_access_all_realm_members(self) -> bool:
return not (self.realm.is_zephyr_mirror_realm or self.is_guest)
def major_tos_version(self) -> int:
if self.tos_version is not None:
return int(self.tos_version.split('.')[0])
else:
return -1
class UserGroup(models.Model):
name = models.CharField(max_length=100)
members = models.ManyToManyField(UserProfile, through='UserGroupMembership')
realm = models.ForeignKey(Realm, on_delete=CASCADE)
description = models.TextField(default=u'') # type: str
class Meta:
unique_together = (('realm', 'name'),)
class UserGroupMembership(models.Model):
user_group = models.ForeignKey(UserGroup, on_delete=CASCADE)
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE)
class Meta:
unique_together = (('user_group', 'user_profile'),)
def receives_offline_push_notifications(user_profile: UserProfile) -> bool:
return (user_profile.enable_offline_push_notifications and
not user_profile.is_bot)
def receives_offline_email_notifications(user_profile: UserProfile) -> bool:
return (user_profile.enable_offline_email_notifications and
not user_profile.is_bot)
def receives_online_notifications(user_profile: UserProfile) -> bool:
return (user_profile.enable_online_push_notifications and
not user_profile.is_bot)
def receives_stream_notifications(user_profile: UserProfile) -> bool:
return (user_profile.enable_stream_push_notifications and
not user_profile.is_bot)
def remote_user_to_email(remote_user: str) -> str:
if settings.SSO_APPEND_DOMAIN is not None:
remote_user += "@" + settings.SSO_APPEND_DOMAIN
return remote_user
# Make sure we flush the UserProfile object from our remote cache
# whenever we save it.
post_save.connect(flush_user_profile, sender=UserProfile)
class PreregistrationUser(models.Model):
# Data on a partially created user, before the completion of
# registration. This is used in at least three major code paths:
# * Realm creation, in which case realm is None.
#
# * Invitations, in which case referred_by will always be set.
#
# * Social authentication signup, where it's used to store data
# from the authentication step and pass it to the registration
# form.
email = models.EmailField() # type: str
referred_by = models.ForeignKey(UserProfile, null=True, on_delete=CASCADE) # type: Optional[UserProfile]
streams = models.ManyToManyField('Stream') # type: Manager
invited_at = models.DateTimeField(auto_now=True) # type: datetime.datetime
realm_creation = models.BooleanField(default=False)
# Indicates whether the user needs a password. Users who were
# created via SSO style auth (e.g. GitHub/Google) generally do not.
password_required = models.BooleanField(default=True)
# status: whether an object has been confirmed.
# if confirmed, set to confirmation.settings.STATUS_ACTIVE
status = models.IntegerField(default=0) # type: int
# The realm should only ever be None for PreregistrationUser
# objects created as part of realm creation.
realm = models.ForeignKey(Realm, null=True, on_delete=CASCADE) # type: Optional[Realm]
# Changes to INVITED_AS should also be reflected in
# settings_invites.invited_as_values in
# static/js/settings_invites.js
INVITE_AS = dict(
MEMBER = 1,
REALM_ADMIN = 2,
GUEST_USER = 3,
)
invited_as = models.PositiveSmallIntegerField(default=INVITE_AS['MEMBER']) # type: int
class MultiuseInvite(models.Model):
referred_by = models.ForeignKey(UserProfile, on_delete=CASCADE) # Optional[UserProfile]
streams = models.ManyToManyField('Stream') # type: Manager
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
invited_as = models.PositiveSmallIntegerField(default=PreregistrationUser.INVITE_AS['MEMBER']) # type: int
class EmailChangeStatus(models.Model):
new_email = models.EmailField() # type: str
old_email = models.EmailField() # type: str
updated_at = models.DateTimeField(auto_now=True) # type: datetime.datetime
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
# status: whether an object has been confirmed.
# if confirmed, set to confirmation.settings.STATUS_ACTIVE
status = models.IntegerField(default=0) # type: int
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
class AbstractPushDeviceToken(models.Model):
APNS = 1
GCM = 2
KINDS = (
(APNS, 'apns'),
(GCM, 'gcm'),
)
kind = models.PositiveSmallIntegerField(choices=KINDS) # type: int
# The token is a unique device-specific token that is
# sent to us from each device:
# - APNS token if kind == APNS
# - GCM registration id if kind == GCM
token = models.CharField(max_length=4096, db_index=True) # type: bytes
# TODO: last_updated should be renamed date_created, since it is
# no longer maintained as a last_updated value.
last_updated = models.DateTimeField(auto_now=True) # type: datetime.datetime
# [optional] Contains the app id of the device if it is an iOS device
ios_app_id = models.TextField(null=True) # type: Optional[str]
class Meta:
abstract = True
class PushDeviceToken(AbstractPushDeviceToken):
# The user who's device this is
user = models.ForeignKey(UserProfile, db_index=True, on_delete=CASCADE) # type: UserProfile
class Meta:
unique_together = ("user", "kind", "token")
def generate_email_token_for_stream() -> str:
return generate_random_token(32)
class Stream(models.Model):
MAX_NAME_LENGTH = 60
MAX_DESCRIPTION_LENGTH = 1024
name = models.CharField(max_length=MAX_NAME_LENGTH, db_index=True) # type: str
realm = models.ForeignKey(Realm, db_index=True, on_delete=CASCADE) # type: Realm
date_created = models.DateTimeField(default=timezone_now) # type: datetime.datetime
deactivated = models.BooleanField(default=False) # type: bool
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH, default=u'') # type: str
rendered_description = models.TextField(default=u'') # type: str
invite_only = models.NullBooleanField(default=False) # type: Optional[bool]
history_public_to_subscribers = models.BooleanField(default=False) # type: bool
# Whether this stream's content should be published by the web-public archive features
is_web_public = models.BooleanField(default=False) # type: bool
# Whether only organization administrators can send messages to this stream
is_announcement_only = models.BooleanField(default=False) # type: bool
# The unique thing about Zephyr public streams is that we never list their
# users. We may try to generalize this concept later, but for now
# we just use a concrete field. (Zephyr public streams aren't exactly like
# invite-only streams--while both are private in terms of listing users,
# for Zephyr we don't even list users to stream members, yet membership
# is more public in the sense that you don't need a Zulip invite to join.
# This field is populated directly from UserProfile.is_zephyr_mirror_realm,
# and the reason for denormalizing field is performance.
is_in_zephyr_realm = models.BooleanField(default=False) # type: bool
# Used by the e-mail forwarder. The e-mail RFC specifies a maximum
# e-mail length of 254, and our max stream length is 30, so we
# have plenty of room for the token.
email_token = models.CharField(
max_length=32, default=generate_email_token_for_stream, unique=True) # type: str
# For old messages being automatically deleted
message_retention_days = models.IntegerField(null=True, default=None) # type: Optional[int]
# The very first message ID in the stream. Used to help clients
# determine whether they might need to display "more topics" for a
# stream based on what messages they have cached.
first_message_id = models.IntegerField(null=True, db_index=True) # type: Optional[int]
def __str__(self) -> str:
return "<Stream: %s>" % (self.name,)
def is_public(self) -> bool:
# All streams are private in Zephyr mirroring realms.
return not self.invite_only and not self.is_in_zephyr_realm
def is_history_realm_public(self) -> bool:
return self.is_public()
def is_history_public_to_subscribers(self) -> bool:
return self.history_public_to_subscribers
class Meta:
unique_together = ("name", "realm")
# This is stream information that is sent to clients
def to_dict(self) -> Dict[str, Any]:
return dict(
name=self.name,
stream_id=self.id,
description=self.description,
rendered_description=self.rendered_description,
invite_only=self.invite_only,
is_web_public=self.is_web_public,
is_announcement_only=self.is_announcement_only,
history_public_to_subscribers=self.history_public_to_subscribers,
first_message_id=self.first_message_id,
)
post_save.connect(flush_stream, sender=Stream)
post_delete.connect(flush_stream, sender=Stream)
# The Recipient table is used to map Messages to the set of users who
# received the message. It is implemented as a set of triples (id,
# type_id, type). We have 3 types of recipients: Huddles (for group
# private messages), UserProfiles (for 1:1 private messages), and
# Streams. The recipient table maps a globally unique recipient id
# (used by the Message table) to the type-specific unique id (the
# stream id, user_profile id, or huddle id).
class Recipient(models.Model):
type_id = models.IntegerField(db_index=True) # type: int
type = models.PositiveSmallIntegerField(db_index=True) # type: int
# Valid types are {personal, stream, huddle}
PERSONAL = 1
STREAM = 2
HUDDLE = 3
class Meta:
unique_together = ("type", "type_id")
# N.B. If we used Django's choice=... we would get this for free (kinda)
_type_names = {
PERSONAL: 'personal',
STREAM: 'stream',
HUDDLE: 'huddle'}
def type_name(self) -> str:
# Raises KeyError if invalid
return self._type_names[self.type]
def __str__(self) -> str:
display_recipient = get_display_recipient(self)
return "<Recipient: %s (%d, %s)>" % (display_recipient, self.type_id, self.type)
class MutedTopic(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE)
stream = models.ForeignKey(Stream, on_delete=CASCADE)
recipient = models.ForeignKey(Recipient, on_delete=CASCADE)
topic_name = models.CharField(max_length=MAX_TOPIC_NAME_LENGTH)
class Meta:
unique_together = ('user_profile', 'stream', 'topic_name')
def __str__(self) -> str:
return "<MutedTopic: (%s, %s, %s)>" % (self.user_profile.email, self.stream.name, self.topic_name)
class Client(models.Model):
name = models.CharField(max_length=30, db_index=True, unique=True) # type: str
def __str__(self) -> str:
return "<Client: %s>" % (self.name,)
get_client_cache = {} # type: Dict[str, Client]
def get_client(name: str) -> Client:
# Accessing KEY_PREFIX through the module is necessary
# because we need the updated value of the variable.
cache_name = cache.KEY_PREFIX + name
if cache_name not in get_client_cache:
result = get_client_remote_cache(name)
get_client_cache[cache_name] = result
return get_client_cache[cache_name]
def get_client_cache_key(name: str) -> str:
return u'get_client:%s' % (make_safe_digest(name),)
@cache_with_key(get_client_cache_key, timeout=3600*24*7)
def get_client_remote_cache(name: str) -> Client:
(client, _) = Client.objects.get_or_create(name=name)
return client
@cache_with_key(get_stream_cache_key, timeout=3600*24*7)
def get_realm_stream(stream_name: str, realm_id: int) -> Stream:
return Stream.objects.select_related("realm").get(
name__iexact=stream_name.strip(), realm_id=realm_id)
def stream_name_in_use(stream_name: str, realm_id: int) -> bool:
return Stream.objects.filter(
name__iexact=stream_name.strip(),
realm_id=realm_id
).exists()
def get_active_streams(realm: Optional[Realm]) -> QuerySet:
# TODO: Change return type to QuerySet[Stream]
# NOTE: Return value is used as a QuerySet, so cannot currently be Sequence[QuerySet]
"""
Return all streams (including invite-only streams) that have not been deactivated.
"""
return Stream.objects.filter(realm=realm, deactivated=False)
def get_stream(stream_name: str, realm: Realm) -> Stream:
'''
Callers that don't have a Realm object already available should use
get_realm_stream directly, to avoid unnecessarily fetching the
Realm object.
'''
return get_realm_stream(stream_name, realm.id)
def get_stream_by_id_in_realm(stream_id: int, realm: Realm) -> Stream:
return Stream.objects.select_related().get(id=stream_id, realm=realm)
def bulk_get_streams(realm: Realm, stream_names: STREAM_NAMES) -> Dict[str, Any]:
def fetch_streams_by_name(stream_names: List[str]) -> Sequence[Stream]:
#
# This should be just
#
# Stream.objects.select_related("realm").filter(name__iexact__in=stream_names,
# realm_id=realm_id)
#
# But chaining __in and __iexact doesn't work with Django's
# ORM, so we have the following hack to construct the relevant where clause
if len(stream_names) == 0:
return []
upper_list = ", ".join(["UPPER(%s)"] * len(stream_names))
where_clause = "UPPER(zerver_stream.name::text) IN (%s)" % (upper_list,)
return get_active_streams(realm.id).select_related("realm").extra(
where=[where_clause],
params=stream_names)
return generic_bulk_cached_fetch(lambda stream_name: get_stream_cache_key(stream_name, realm.id),
fetch_streams_by_name,
[stream_name.lower() for stream_name in stream_names],
id_fetcher=lambda stream: stream.name.lower())
def get_recipient_cache_key(type: int, type_id: int) -> str:
return u"%s:get_recipient:%s:%s" % (cache.KEY_PREFIX, type, type_id,)
@cache_with_key(get_recipient_cache_key, timeout=3600*24*7)
def get_recipient(type: int, type_id: int) -> Recipient:
return Recipient.objects.get(type_id=type_id, type=type)
def get_stream_recipient(stream_id: int) -> Recipient:
return get_recipient(Recipient.STREAM, stream_id)
def get_personal_recipient(user_profile_id: int) -> Recipient:
return get_recipient(Recipient.PERSONAL, user_profile_id)
def get_huddle_recipient(user_profile_ids: Set[int]) -> Recipient:
# The caller should ensure that user_profile_ids includes
# the sender. Note that get_huddle hits the cache, and then
# we hit another cache to get the recipient. We may want to
# unify our caching strategy here.
huddle = get_huddle(list(user_profile_ids))
return get_recipient(Recipient.HUDDLE, huddle.id)
def get_huddle_user_ids(recipient: Recipient) -> List[int]:
assert(recipient.type == Recipient.HUDDLE)
return Subscription.objects.filter(
recipient=recipient
).order_by('user_profile_id').values_list('user_profile_id', flat=True)
def bulk_get_recipients(type: int, type_ids: List[int]) -> Dict[int, Any]:
def cache_key_function(type_id: int) -> str:
return get_recipient_cache_key(type, type_id)
def query_function(type_ids: List[int]) -> Sequence[Recipient]:
# TODO: Change return type to QuerySet[Recipient]
return Recipient.objects.filter(type=type, type_id__in=type_ids)
return generic_bulk_cached_fetch(cache_key_function, query_function, type_ids,
id_fetcher=lambda recipient: recipient.type_id)
def get_stream_recipients(stream_ids: List[int]) -> List[Recipient]:
'''
We could call bulk_get_recipients(...).values() here, but it actually
leads to an extra query in test mode.
'''
return Recipient.objects.filter(
type=Recipient.STREAM,
type_id__in=stream_ids,
)
class AbstractMessage(models.Model):
sender = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
recipient = models.ForeignKey(Recipient, on_delete=CASCADE) # type: Recipient
# The message's topic.
#
# Early versions of Zulip called this concept a "subject", as in an email
# "subject line", before changing to "topic" in 2013 (commit dac5a46fa).
# UI and user documentation now consistently say "topic". New APIs and
# new code should generally also say "topic".
#
# See also the `topic_name` method on `Message`.
subject = models.CharField(max_length=MAX_TOPIC_NAME_LENGTH, db_index=True) # type: str
content = models.TextField() # type: str
rendered_content = models.TextField(null=True) # type: Optional[str]
rendered_content_version = models.IntegerField(null=True) # type: Optional[int]
pub_date = models.DateTimeField('date published', db_index=True) # type: datetime.datetime
sending_client = models.ForeignKey(Client, on_delete=CASCADE) # type: Client
last_edit_time = models.DateTimeField(null=True) # type: Optional[datetime.datetime]
# A JSON-encoded list of objects describing any past edits to this
# message, oldest first.
edit_history = models.TextField(null=True) # type: Optional[str]
has_attachment = models.BooleanField(default=False, db_index=True) # type: bool
has_image = models.BooleanField(default=False, db_index=True) # type: bool
has_link = models.BooleanField(default=False, db_index=True) # type: bool
class Meta:
abstract = True
def __str__(self) -> str:
display_recipient = get_display_recipient(self.recipient)
return "<%s: %s / %s / %s>" % (self.__class__.__name__, display_recipient,
self.subject, self.sender)
class ArchiveTransaction(models.Model):
timestamp = models.DateTimeField(default=timezone_now, db_index=True) # type: datetime.datetime
# Marks if the data archived in this transaction has been restored:
restored = models.BooleanField(default=False, db_index=True) # type: bool
type = models.PositiveSmallIntegerField(db_index=True) # type: int
# Valid types:
RETENTION_POLICY_BASED = 1 # Archiving was executed due to automated retention policies
MANUAL = 2 # Archiving was run manually, via move_messages_to_archive function
# ForeignKey to the realm with which objects archived in this transaction are associated.
# If type is set to MANUAL, this should be null.
realm = models.ForeignKey(Realm, null=True, on_delete=CASCADE) # type: Optional[Realm]
def __str__(self) -> str:
return "ArchiveTransaction id: {id}, type: {type}, realm: {realm}, timestamp: {timestamp}".format(
id=self.id,
type="MANUAL" if self.type == self.MANUAL else "RETENTION_POLICY_BASED",
realm=self.realm.string_id if self.realm else None,
timestamp=self.timestamp
)
class ArchivedMessage(AbstractMessage):
"""Used as a temporary holding place for deleted messages before they
are permanently deleted. This is an important part of a robust
'message retention' feature.
"""
archive_transaction = models.ForeignKey(ArchiveTransaction, on_delete=CASCADE) # type: ArchiveTransaction
class Message(AbstractMessage):
def topic_name(self) -> str:
"""
Please start using this helper to facilitate an
eventual switch over to a separate topic table.
"""
return self.subject
def set_topic_name(self, topic_name: str) -> None:
self.subject = topic_name
def is_stream_message(self) -> bool:
'''
Find out whether a message is a stream message by
looking up its recipient.type. TODO: Make this
an easier operation by denormalizing the message
type onto Message, either explicity (message.type)
or implicitly (message.stream_id is not None).
'''
return self.recipient.type == Recipient.STREAM
def get_realm(self) -> Realm:
return self.sender.realm
def save_rendered_content(self) -> None:
self.save(update_fields=["rendered_content", "rendered_content_version"])
@staticmethod
def need_to_render_content(rendered_content: Optional[str],
rendered_content_version: Optional[int],
bugdown_version: int) -> bool:
return (rendered_content is None or
rendered_content_version is None or
rendered_content_version < bugdown_version)
def to_log_dict(self) -> Dict[str, Any]:
return dict(
id = self.id,
sender_id = self.sender.id,
sender_email = self.sender.email,
sender_realm_str = self.sender.realm.string_id,
sender_full_name = self.sender.full_name,
sender_short_name = self.sender.short_name,
sending_client = self.sending_client.name,
type = self.recipient.type_name(),
recipient = get_display_recipient(self.recipient),
subject = self.topic_name(),
content = self.content,
timestamp = datetime_to_timestamp(self.pub_date))
def sent_by_human(self) -> bool:
"""Used to determine whether a message was sent by a full Zulip UI
style client (and thus whether the message should be treated
as sent by a human and automatically marked as read for the
sender). The purpose of this distinction is to ensure that
message sent to the user by e.g. a Google Calendar integration
using the user's own API key don't get marked as read
automatically.
"""
sending_client = self.sending_client.name.lower()
return (sending_client in ('zulipandroid', 'zulipios', 'zulipdesktop',
'zulipmobile', 'zulipelectron', 'zulipterminal', 'snipe',
'website', 'ios', 'android')) or (
'desktop app' in sending_client)
@staticmethod
def content_has_attachment(content: str) -> Match:
return re.search(r'[/\-]user[\-_]uploads[/\.-]', content)
@staticmethod
def content_has_image(content: str) -> bool:
return bool(re.search(r'[/\-]user[\-_]uploads[/\.-]\S+\.(bmp|gif|jpg|jpeg|png|webp)',
content, re.IGNORECASE))
@staticmethod
def content_has_link(content: str) -> bool:
return ('http://' in content or
'https://' in content or
'/user_uploads' in content or
(settings.ENABLE_FILE_LINKS and 'file:///' in content) or
'bitcoin:' in content)
@staticmethod
def is_status_message(content: str, rendered_content: str) -> bool:
"""
Returns True if content and rendered_content are from 'me_message'
"""
if content.startswith('/me '):
if rendered_content.startswith('<p>') and rendered_content.endswith('</p>'):
return True
return False
def update_calculated_fields(self) -> None:
# TODO: rendered_content could also be considered a calculated field
content = self.content
self.has_attachment = bool(Message.content_has_attachment(content))
self.has_image = bool(Message.content_has_image(content))
self.has_link = bool(Message.content_has_link(content))
@receiver(pre_save, sender=Message)
def pre_save_message(sender: Any, **kwargs: Any) -> None:
if kwargs['update_fields'] is None or "content" in kwargs['update_fields']:
message = kwargs['instance']
message.update_calculated_fields()
def get_context_for_message(message: Message) -> Sequence[Message]:
# TODO: Change return type to QuerySet[Message]
return Message.objects.filter(
recipient_id=message.recipient_id,
subject=message.subject,
id__lt=message.id,
pub_date__gt=message.pub_date - timedelta(minutes=15),
).order_by('-id')[:10]
post_save.connect(flush_message, sender=Message)
class AbstractSubMessage(models.Model):
# We can send little text messages that are associated with a regular
# Zulip message. These can be used for experimental widgets like embedded
# games, surveys, mini threads, etc. These are designed to be pretty
# generic in purpose.
sender = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
msg_type = models.TextField()
content = models.TextField()
class Meta:
abstract = True
class SubMessage(AbstractSubMessage):
message = models.ForeignKey(Message, on_delete=CASCADE) # type: Message
@staticmethod
def get_raw_db_rows(needed_ids: List[int]) -> List[Dict[str, Any]]:
fields = ['id', 'message_id', 'sender_id', 'msg_type', 'content']
query = SubMessage.objects.filter(message_id__in=needed_ids).values(*fields)
query = query.order_by('message_id', 'id')
return list(query)
class ArchivedSubMessage(AbstractSubMessage):
message = models.ForeignKey(ArchivedMessage, on_delete=CASCADE) # type: ArchivedMessage
post_save.connect(flush_submessage, sender=SubMessage)
class AbstractReaction(models.Model):
"""For emoji reactions to messages (and potentially future reaction types).
Emoji are surprisingly complicated to implement correctly. For details
on how this subsystem works, see:
https://zulip.readthedocs.io/en/latest/subsystems/emoji.html
"""
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
# The user-facing name for an emoji reaction. With emoji aliases,
# there may be multiple accepted names for a given emoji; this
# field encodes which one the user selected.
emoji_name = models.TextField() # type: str
UNICODE_EMOJI = u'unicode_emoji'
REALM_EMOJI = u'realm_emoji'
ZULIP_EXTRA_EMOJI = u'zulip_extra_emoji'
REACTION_TYPES = ((UNICODE_EMOJI, _("Unicode emoji")),
(REALM_EMOJI, _("Custom emoji")),
(ZULIP_EXTRA_EMOJI, _("Zulip extra emoji")))
reaction_type = models.CharField(default=UNICODE_EMOJI, choices=REACTION_TYPES, max_length=30) # type: str
# A string that uniquely identifies a particular emoji. The format varies
# by type:
#
# * For Unicode emoji, a dash-separated hex encoding of the sequence of
# Unicode codepoints that define this emoji in the Unicode
# specification. For examples, see "non_qualified" or "unified" in the
# following data, with "non_qualified" taking precedence when both present:
# https://raw.githubusercontent.com/iamcal/emoji-data/master/emoji_pretty.json
#
# * For realm emoji (aka user uploaded custom emoji), the ID
# (in ASCII decimal) of the RealmEmoji object.
#
# * For "Zulip extra emoji" (like :zulip:), the filename of the emoji.
emoji_code = models.TextField() # type: str
class Meta:
abstract = True
unique_together = ("user_profile", "message", "emoji_name")
class Reaction(AbstractReaction):
message = models.ForeignKey(Message, on_delete=CASCADE) # type: Message
@staticmethod
def get_raw_db_rows(needed_ids: List[int]) -> List[Dict[str, Any]]:
fields = ['message_id', 'emoji_name', 'emoji_code', 'reaction_type',
'user_profile__email', 'user_profile__id', 'user_profile__full_name']
return Reaction.objects.filter(message_id__in=needed_ids).values(*fields)
def __str__(self) -> str:
return "%s / %s / %s" % (self.user_profile.email, self.message.id, self.emoji_name)
class ArchivedReaction(AbstractReaction):
message = models.ForeignKey(ArchivedMessage, on_delete=CASCADE) # type: ArchivedMessage
# Whenever a message is sent, for each user subscribed to the
# corresponding Recipient object, we add a row to the UserMessage
# table indicating that that user received that message. This table
# allows us to quickly query any user's last 1000 messages to generate
# the home view.
#
# Additionally, the flags field stores metadata like whether the user
# has read the message, starred or collapsed the message, was
# mentioned in the message, etc.
#
# UserMessage is the largest table in a Zulip installation, even
# though each row is only 4 integers.
class AbstractUserMessage(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
# The order here is important! It's the order of fields in the bitfield.
ALL_FLAGS = [
'read',
'starred',
'collapsed',
'mentioned',
'wildcard_mentioned',
# These next 4 flags are from features that have since been removed.
'summarize_in_home',
'summarize_in_stream',
'force_expand',
'force_collapse',
# Whether the message contains any of the user's alert words.
'has_alert_word',
# The historical flag is used to mark messages which the user
# did not receive when they were sent, but later added to
# their history via e.g. starring the message. This is
# important accounting for the "Subscribed to stream" dividers.
'historical',
# Whether the message is a private message; this flag is a
# denormalization of message.recipient.type to support an
# efficient index on UserMessage for a user's private messages.
'is_private',
# Whether we've sent a push notification to the user's mobile
# devices for this message that has not been revoked.
'active_mobile_push_notification',
]
# Certain flags are used only for internal accounting within the
# Zulip backend, and don't make sense to expose to the API.
NON_API_FLAGS = {"is_private", "active_mobile_push_notification"}
# Certain additional flags are just set once when the UserMessage
# row is created.
NON_EDITABLE_FLAGS = {
# These flags are bookkeeping and don't make sense to edit.
"has_alert_word",
"mentioned",
"wildcard_mentioned",
"historical",
# Unused flags can't be edited.
"force_expand",
"force_collapse",
"summarize_in_home",
"summarize_in_stream",
}
flags = BitField(flags=ALL_FLAGS, default=0) # type: BitHandler
class Meta:
abstract = True
unique_together = ("user_profile", "message")
@staticmethod
def where_unread() -> str:
# Use this for Django ORM queries to access unread message.
# This custom SQL plays nice with our partial indexes. Grep
# the code for example usage.
return 'flags & 1 = 0'
@staticmethod
def where_starred() -> str:
# Use this for Django ORM queries to access starred messages.
# This custom SQL plays nice with our partial indexes. Grep
# the code for example usage.
#
# The key detail is that e.g.
# UserMessage.objects.filter(user_profile=user_profile, flags=UserMessage.flags.starred)
# will generate a query involving `flags & 2 = 2`, which doesn't match our index.
return 'flags & 2 <> 0'
@staticmethod
def where_active_push_notification() -> str:
# See where_starred for documentation.
return 'flags & 4096 <> 0'
def flags_list(self) -> List[str]:
flags = int(self.flags)
return self.flags_list_for_flags(flags)
@staticmethod
def flags_list_for_flags(val: int) -> List[str]:
'''
This function is highly optimized, because it actually slows down
sending messages in a naive implementation.
'''
flags = []
mask = 1
for flag in UserMessage.ALL_FLAGS:
if (val & mask) and flag not in AbstractUserMessage.NON_API_FLAGS:
flags.append(flag)
mask <<= 1
return flags
def __str__(self) -> str:
display_recipient = get_display_recipient(self.message.recipient)
return "<%s: %s / %s (%s)>" % (self.__class__.__name__, display_recipient,
self.user_profile.email, self.flags_list())
class UserMessage(AbstractUserMessage):
message = models.ForeignKey(Message, on_delete=CASCADE) # type: Message
def get_usermessage_by_message_id(user_profile: UserProfile, message_id: int) -> Optional[UserMessage]:
try:
return UserMessage.objects.select_related().get(user_profile=user_profile,
message__id=message_id)
except UserMessage.DoesNotExist:
return None
class ArchivedUserMessage(AbstractUserMessage):
"""Used as a temporary holding place for deleted UserMessages objects
before they are permanently deleted. This is an important part of
a robust 'message retention' feature.
"""
message = models.ForeignKey(ArchivedMessage, on_delete=CASCADE) # type: Message
class AbstractAttachment(models.Model):
file_name = models.TextField(db_index=True) # type: str
# path_id is a storage location agnostic representation of the path of the file.
# If the path of a file is http://localhost:9991/user_uploads/a/b/abc/temp_file.py
# then its path_id will be a/b/abc/temp_file.py.
path_id = models.TextField(db_index=True, unique=True) # type: str
owner = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
realm = models.ForeignKey(Realm, blank=True, null=True, on_delete=CASCADE) # type: Optional[Realm]
create_time = models.DateTimeField(default=timezone_now,
db_index=True) # type: datetime.datetime
size = models.IntegerField(null=True) # type: Optional[int]
# Whether this attachment has been posted to a public stream, and
# thus should be available to all non-guest users in the
# organization (even if they weren't a recipient of a message
# linking to it). This lets us avoid looking up the corresponding
# messages/streams to check permissions before serving these files.
is_realm_public = models.BooleanField(default=False) # type: bool
class Meta:
abstract = True
def __str__(self) -> str:
return "<%s: %s>" % (self.__class__.__name__, self.file_name,)
class ArchivedAttachment(AbstractAttachment):
"""Used as a temporary holding place for deleted Attachment objects
before they are permanently deleted. This is an important part of
a robust 'message retention' feature.
"""
messages = models.ManyToManyField(ArchivedMessage) # type: Manager
class Attachment(AbstractAttachment):
messages = models.ManyToManyField(Message) # type: Manager
def is_claimed(self) -> bool:
return self.messages.count() > 0
def to_dict(self) -> Dict[str, Any]:
return {
'id': self.id,
'name': self.file_name,
'path_id': self.path_id,
'size': self.size,
# convert to JavaScript-style UNIX timestamp so we can take
# advantage of client timezones.
'create_time': time.mktime(self.create_time.timetuple()) * 1000,
'messages': [{
'id': m.id,
'name': time.mktime(m.pub_date.timetuple()) * 1000
} for m in self.messages.all()]
}
post_save.connect(flush_used_upload_space_cache, sender=Attachment)
post_delete.connect(flush_used_upload_space_cache, sender=Attachment)
def validate_attachment_request(user_profile: UserProfile, path_id: str) -> Optional[bool]:
try:
attachment = Attachment.objects.get(path_id=path_id)
except Attachment.DoesNotExist:
return None
if user_profile == attachment.owner:
# If you own the file, you can access it.
return True
if (attachment.is_realm_public and attachment.realm == user_profile.realm and
user_profile.can_access_public_streams()):
# Any user in the realm can access realm-public files
return True
messages = attachment.messages.all()
if UserMessage.objects.filter(user_profile=user_profile, message__in=messages).exists():
# If it was sent in a private message or private stream
# message, then anyone who received that message can access it.
return True
# The user didn't receive any of the messages that included this
# attachment. But they might still have access to it, if it was
# sent to a stream they are on where history is public to
# subscribers.
# These are subscriptions to a stream one of the messages was sent to
relevant_stream_ids = Subscription.objects.filter(
user_profile=user_profile,
active=True,
recipient__type=Recipient.STREAM,
recipient__in=[m.recipient_id for m in messages]).values_list("recipient__type_id", flat=True)
if len(relevant_stream_ids) == 0:
return False
return Stream.objects.filter(id__in=relevant_stream_ids,
history_public_to_subscribers=True).exists()
def get_old_unclaimed_attachments(weeks_ago: int) -> Sequence[Attachment]:
# TODO: Change return type to QuerySet[Attachment]
delta_weeks_ago = timezone_now() - datetime.timedelta(weeks=weeks_ago)
old_attachments = Attachment.objects.filter(messages=None, create_time__lt=delta_weeks_ago)
return old_attachments
class Subscription(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
recipient = models.ForeignKey(Recipient, on_delete=CASCADE) # type: Recipient
# Whether the user has since unsubscribed. We mark Subscription
# objects as inactive, rather than deleting them, when a user
# unsubscribes, so we can preseve user customizations like
# notification settings, stream color, etc., if the user later
# resubscribes.
active = models.BooleanField(default=True) # type: bool
# Whether this user had muted this stream.
is_muted = models.NullBooleanField(default=False) # type: Optional[bool]
DEFAULT_STREAM_COLOR = u"#c2c2c2"
color = models.CharField(max_length=10, default=DEFAULT_STREAM_COLOR) # type: str
pin_to_top = models.BooleanField(default=False) # type: bool
# These fields are stream-level overrides for the user's default
# configuration for notification, configured in UserProfile. The
# default, None, means we just inherit the user-level default.
desktop_notifications = models.NullBooleanField(default=None) # type: Optional[bool]
audible_notifications = models.NullBooleanField(default=None) # type: Optional[bool]
push_notifications = models.NullBooleanField(default=None) # type: Optional[bool]
email_notifications = models.NullBooleanField(default=None) # type: Optional[bool]
class Meta:
unique_together = ("user_profile", "recipient")
def __str__(self) -> str:
return "<Subscription: %s -> %s>" % (self.user_profile, self.recipient)
@cache_with_key(user_profile_by_id_cache_key, timeout=3600*24*7)
def get_user_profile_by_id(uid: int) -> UserProfile:
return UserProfile.objects.select_related().get(id=uid)
@cache_with_key(user_profile_by_email_cache_key, timeout=3600*24*7)
def get_user_profile_by_email(email: str) -> UserProfile:
"""This should only be used by our unit tests and for manual manage.py
shell work; robust code must use get_user instead, because Zulip
supports multiple users with a given email address existing (in
different realms). Also, for many applications, we should prefer
get_user_by_delivery_email.
"""
return UserProfile.objects.select_related().get(delivery_email__iexact=email.strip())
@cache_with_key(user_profile_by_api_key_cache_key, timeout=3600*24*7)
def get_user_profile_by_api_key(api_key: str) -> UserProfile:
return UserProfile.objects.select_related().get(api_key=api_key)
def get_user_by_delivery_email(email: str, realm: Realm) -> UserProfile:
# Fetches users by delivery_email for use in
# authentication/registration contexts. Do not use for user-facing
# views (e.g. Zulip API endpoints); for that, you want get_user,
# both because it does lookup by email (not delivery_email) and
# because it correctly handles Zulip's support for multiple users
# with the same email address in different realms.
return UserProfile.objects.select_related().get(delivery_email__iexact=email.strip(), realm=realm)
@cache_with_key(user_profile_cache_key, timeout=3600*24*7)
def get_user(email: str, realm: Realm) -> UserProfile:
# Fetches the user by its visible-to-other users username (in the
# `email` field). For use in API contexts; do not use in
# authentication/registration contexts; for that, you need to use
# get_user_by_delivery_email.
return UserProfile.objects.select_related().get(email__iexact=email.strip(), realm=realm)
def get_active_user_by_delivery_email(email: str, realm: Realm) -> UserProfile:
user_profile = get_user_by_delivery_email(email, realm)
if not user_profile.is_active:
raise UserProfile.DoesNotExist()
return user_profile
def get_active_user(email: str, realm: Realm) -> UserProfile:
user_profile = get_user(email, realm)
if not user_profile.is_active:
raise UserProfile.DoesNotExist()
return user_profile
def get_user_profile_by_id_in_realm(uid: int, realm: Realm) -> UserProfile:
return UserProfile.objects.select_related().get(id=uid, realm=realm)
def get_user_including_cross_realm(email: str, realm: Optional[Realm]=None) -> UserProfile:
if is_cross_realm_bot_email(email):
return get_system_bot(email)
assert realm is not None
return get_user(email, realm)
@cache_with_key(bot_profile_cache_key, timeout=3600*24*7)
def get_system_bot(email: str) -> UserProfile:
return UserProfile.objects.select_related().get(email__iexact=email.strip())
def get_user_by_id_in_realm_including_cross_realm(
uid: int,
realm: Optional[Realm]
) -> UserProfile:
user_profile = get_user_profile_by_id(uid)
if user_profile.realm == realm:
return user_profile
# Note: This doesn't validate whether the `realm` passed in is
# None/invalid for the CROSS_REALM_BOT_EMAILS case.
if user_profile.email in settings.CROSS_REALM_BOT_EMAILS:
return user_profile
raise UserProfile.DoesNotExist()
@cache_with_key(realm_user_dicts_cache_key, timeout=3600*24*7)
def get_realm_user_dicts(realm_id: int) -> List[Dict[str, Any]]:
return UserProfile.objects.filter(
realm_id=realm_id,
).values(*realm_user_dict_fields)
@cache_with_key(active_user_ids_cache_key, timeout=3600*24*7)
def active_user_ids(realm_id: int) -> List[int]:
query = UserProfile.objects.filter(
realm_id=realm_id,
is_active=True
).values_list('id', flat=True)
return list(query)
@cache_with_key(active_non_guest_user_ids_cache_key, timeout=3600*24*7)
def active_non_guest_user_ids(realm_id: int) -> List[int]:
query = UserProfile.objects.filter(
realm_id=realm_id,
is_active=True,
is_guest=False,
).values_list('id', flat=True)
return list(query)
def get_source_profile(email: str, string_id: str) -> Optional[UserProfile]:
try:
return get_user_by_delivery_email(email, get_realm(string_id))
except (Realm.DoesNotExist, UserProfile.DoesNotExist):
return None
@cache_with_key(bot_dicts_in_realm_cache_key, timeout=3600*24*7)
def get_bot_dicts_in_realm(realm: Realm) -> List[Dict[str, Any]]:
return UserProfile.objects.filter(realm=realm, is_bot=True).values(*bot_dict_fields)
def is_cross_realm_bot_email(email: str) -> bool:
return email.lower() in settings.CROSS_REALM_BOT_EMAILS
# The Huddle class represents a group of individuals who have had a
# Group Private Message conversation together. The actual membership
# of the Huddle is stored in the Subscription table just like with
# Streams, and a hash of that list is stored in the huddle_hash field
# below, to support efficiently mapping from a set of users to the
# corresponding Huddle object.
class Huddle(models.Model):
# TODO: We should consider whether using
# CommaSeparatedIntegerField would be better.
huddle_hash = models.CharField(max_length=40, db_index=True, unique=True) # type: str
def get_huddle_hash(id_list: List[int]) -> str:
id_list = sorted(set(id_list))
hash_key = ",".join(str(x) for x in id_list)
return make_safe_digest(hash_key)
def huddle_hash_cache_key(huddle_hash: str) -> str:
return u"huddle_by_hash:%s" % (huddle_hash,)
def get_huddle(id_list: List[int]) -> Huddle:
huddle_hash = get_huddle_hash(id_list)
return get_huddle_backend(huddle_hash, id_list)
@cache_with_key(lambda huddle_hash, id_list: huddle_hash_cache_key(huddle_hash), timeout=3600*24*7)
def get_huddle_backend(huddle_hash: str, id_list: List[int]) -> Huddle:
with transaction.atomic():
(huddle, created) = Huddle.objects.get_or_create(huddle_hash=huddle_hash)
if created:
recipient = Recipient.objects.create(type_id=huddle.id,
type=Recipient.HUDDLE)
subs_to_create = [Subscription(recipient=recipient,
user_profile_id=user_profile_id)
for user_profile_id in id_list]
Subscription.objects.bulk_create(subs_to_create)
return huddle
def clear_database() -> None: # nocoverage # Only used in populate_db
pylibmc.Client(['127.0.0.1']).flush_all()
model = None # type: Any
for model in [Message, Stream, UserProfile, Recipient,
Realm, Subscription, Huddle, UserMessage, Client,
DefaultStream]:
model.objects.all().delete()
Session.objects.all().delete()
class UserActivity(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
client = models.ForeignKey(Client, on_delete=CASCADE) # type: Client
query = models.CharField(max_length=50, db_index=True) # type: str
count = models.IntegerField() # type: int
last_visit = models.DateTimeField('last visit') # type: datetime.datetime
class Meta:
unique_together = ("user_profile", "client", "query")
class UserActivityInterval(models.Model):
MIN_INTERVAL_LENGTH = datetime.timedelta(minutes=15)
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
start = models.DateTimeField('start time', db_index=True) # type: datetime.datetime
end = models.DateTimeField('end time', db_index=True) # type: datetime.datetime
class UserPresence(models.Model):
"""A record from the last time we heard from a given user on a given client.
This is a tricky subsystem, because it is highly optimized. See the docs:
https://zulip.readthedocs.io/en/latest/subsystems/presence.html
"""
class Meta:
unique_together = ("user_profile", "client")
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
client = models.ForeignKey(Client, on_delete=CASCADE) # type: Client
# The time we heard this update from the client.
timestamp = models.DateTimeField('presence changed') # type: datetime.datetime
# The user was actively using this Zulip client as of `timestamp` (i.e.,
# they had interacted with the client recently). When the timestamp is
# itself recent, this is the green "active" status in the webapp.
ACTIVE = 1
# There had been no user activity (keyboard/mouse/etc.) on this client
# recently. So the client was online at the specified time, but it
# could be the user's desktop which they were away from. Displayed as
# orange/idle if the timestamp is current.
IDLE = 2
# Information from the client about the user's recent interaction with
# that client, as of `timestamp`. Possible values above.
#
# There is no "inactive" status, because that is encoded by the
# timestamp being old.
status = models.PositiveSmallIntegerField(default=ACTIVE) # type: int
@staticmethod
def status_to_string(status: int) -> str:
if status == UserPresence.ACTIVE:
return 'active'
elif status == UserPresence.IDLE:
return 'idle'
else: # nocoverage # TODO: Add a presence test to cover this.
raise ValueError('Unknown status: %s' % (status,))
@staticmethod
def get_status_dict_by_user(user_profile: UserProfile) -> Dict[str, Dict[str, Any]]:
query = UserPresence.objects.filter(user_profile=user_profile).values(
'client__name',
'status',
'timestamp',
'user_profile__email',
'user_profile__id',
'user_profile__enable_offline_push_notifications',
)
presence_rows = list(query)
mobile_user_ids = set() # type: Set[int]
if PushDeviceToken.objects.filter(user=user_profile).exists(): # nocoverage
# TODO: Add a test, though this is low priority, since we don't use mobile_user_ids yet.
mobile_user_ids.add(user_profile.id)
return UserPresence.get_status_dicts_for_rows(presence_rows, mobile_user_ids)
@staticmethod
def get_status_dict_by_realm(realm_id: int) -> Dict[str, Dict[str, Any]]:
user_profile_ids = UserProfile.objects.filter(
realm_id=realm_id,
is_active=True,
is_bot=False
).order_by('id').values_list('id', flat=True)
user_profile_ids = list(user_profile_ids)
if not user_profile_ids: # nocoverage
# This conditional is necessary because query_for_ids
# throws an exception if passed an empty list.
#
# It's not clear this condition is actually possible,
# though, because it shouldn't be possible to end up with
# a realm with 0 active users.
return {}
two_weeks_ago = timezone_now() - datetime.timedelta(weeks=2)
query = UserPresence.objects.filter(
timestamp__gte=two_weeks_ago
).values(
'client__name',
'status',
'timestamp',
'user_profile__email',
'user_profile__id',
'user_profile__enable_offline_push_notifications',
)
query = query_for_ids(
query=query,
user_ids=user_profile_ids,
field='user_profile_id'
)
presence_rows = list(query)
mobile_query = PushDeviceToken.objects.distinct(
'user_id'
).values_list(
'user_id',
flat=True
)
mobile_query = query_for_ids(
query=mobile_query,
user_ids=user_profile_ids,
field='user_id'
)
mobile_user_ids = set(mobile_query)
return UserPresence.get_status_dicts_for_rows(presence_rows, mobile_user_ids)
@staticmethod
def get_status_dicts_for_rows(presence_rows: List[Dict[str, Any]],
mobile_user_ids: Set[int]) -> Dict[str, Dict[str, Any]]:
info_row_dct = defaultdict(list) # type: DefaultDict[str, List[Dict[str, Any]]]
for row in presence_rows:
email = row['user_profile__email']
client_name = row['client__name']
status = UserPresence.status_to_string(row['status'])
dt = row['timestamp']
timestamp = datetime_to_timestamp(dt)
push_enabled = row['user_profile__enable_offline_push_notifications']
has_push_devices = row['user_profile__id'] in mobile_user_ids
pushable = (push_enabled and has_push_devices)
info = dict(
client=client_name,
status=status,
dt=dt,
timestamp=timestamp,
pushable=pushable,
)
info_row_dct[email].append(info)
user_statuses = dict() # type: Dict[str, Dict[str, Any]]
for email, info_rows in info_row_dct.items():
# Note that datetime values have sub-second granularity, which is
# mostly important for avoiding test flakes, but it's also technically
# more precise for real users.
by_time = lambda row: row['dt']
most_recent_info = max(info_rows, key=by_time)
# We don't send datetime values to the client.
for r in info_rows:
del r['dt']
client_dict = {info['client']: info for info in info_rows}
user_statuses[email] = client_dict
# The word "aggegrated" here is possibly misleading.
# It's really just the most recent client's info.
user_statuses[email]['aggregated'] = dict(
client=most_recent_info['client'],
status=most_recent_info['status'],
timestamp=most_recent_info['timestamp'],
)
return user_statuses
@staticmethod
def to_presence_dict(client_name: str, status: int, dt: datetime.datetime, push_enabled: bool=False,
has_push_devices: bool=False) -> Dict[str, Any]:
presence_val = UserPresence.status_to_string(status)
timestamp = datetime_to_timestamp(dt)
return dict(
client=client_name,
status=presence_val,
timestamp=timestamp,
pushable=(push_enabled and has_push_devices),
)
def to_dict(self) -> Dict[str, Any]:
return UserPresence.to_presence_dict(
self.client.name,
self.status,
self.timestamp
)
@staticmethod
def status_from_string(status: str) -> Optional[int]:
if status == 'active':
status_val = UserPresence.ACTIVE # type: Optional[int] # See https://github.com/python/mypy/issues/2611
elif status == 'idle':
status_val = UserPresence.IDLE
else:
status_val = None
return status_val
class UserStatus(models.Model):
user_profile = models.OneToOneField(UserProfile, on_delete=CASCADE) # type: UserProfile
timestamp = models.DateTimeField() # type: datetime.datetime
client = models.ForeignKey(Client, on_delete=CASCADE) # type: Client
NORMAL = 0
AWAY = 1
status = models.PositiveSmallIntegerField(default=NORMAL) # type: int
status_text = models.CharField(max_length=255, default='') # type: str
class DefaultStream(models.Model):
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
stream = models.ForeignKey(Stream, on_delete=CASCADE) # type: Stream
class Meta:
unique_together = ("realm", "stream")
class DefaultStreamGroup(models.Model):
MAX_NAME_LENGTH = 60
name = models.CharField(max_length=MAX_NAME_LENGTH, db_index=True) # type: str
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
streams = models.ManyToManyField('Stream') # type: Manager
description = models.CharField(max_length=1024, default=u'') # type: str
class Meta:
unique_together = ("realm", "name")
def to_dict(self) -> Dict[str, Any]:
return dict(name=self.name,
id=self.id,
description=self.description,
streams=[stream.to_dict() for stream in self.streams.all()])
def get_default_stream_groups(realm: Realm) -> List[DefaultStreamGroup]:
return DefaultStreamGroup.objects.filter(realm=realm)
class AbstractScheduledJob(models.Model):
scheduled_timestamp = models.DateTimeField(db_index=True) # type: datetime.datetime
# JSON representation of arguments to consumer
data = models.TextField() # type: str
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
class Meta:
abstract = True
class ScheduledEmail(AbstractScheduledJob):
# Exactly one of users or address should be set. These are
# duplicate values, used to efficiently filter the set of
# ScheduledEmails for use in clear_scheduled_emails; the
# recipients used for actually sending messages are stored in the
# data field of AbstractScheduledJob.
users = models.ManyToManyField(UserProfile) # type: Manager
# Just the address part of a full "name <address>" email address
address = models.EmailField(null=True, db_index=True) # type: Optional[str]
# Valid types are below
WELCOME = 1
DIGEST = 2
INVITATION_REMINDER = 3
type = models.PositiveSmallIntegerField() # type: int
def __str__(self) -> str:
return "<ScheduledEmail: %s %s %s>" % (self.type,
self.address or list(self.users.all()),
self.scheduled_timestamp)
class ScheduledMessage(models.Model):
sender = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
recipient = models.ForeignKey(Recipient, on_delete=CASCADE) # type: Recipient
subject = models.CharField(max_length=MAX_TOPIC_NAME_LENGTH) # type: str
content = models.TextField() # type: str
sending_client = models.ForeignKey(Client, on_delete=CASCADE) # type: Client
stream = models.ForeignKey(Stream, null=True, on_delete=CASCADE) # type: Optional[Stream]
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
scheduled_timestamp = models.DateTimeField(db_index=True) # type: datetime.datetime
delivered = models.BooleanField(default=False) # type: bool
SEND_LATER = 1
REMIND = 2
DELIVERY_TYPES = (
(SEND_LATER, 'send_later'),
(REMIND, 'remind'),
)
delivery_type = models.PositiveSmallIntegerField(choices=DELIVERY_TYPES,
default=SEND_LATER) # type: int
def topic_name(self) -> str:
return self.subject
def set_topic_name(self, topic_name: str) -> None:
self.subject = topic_name
def __str__(self) -> str:
display_recipient = get_display_recipient(self.recipient)
return "<ScheduledMessage: %s %s %s %s>" % (display_recipient,
self.subject, self.sender,
self.scheduled_timestamp)
EMAIL_TYPES = {
'followup_day1': ScheduledEmail.WELCOME,
'followup_day2': ScheduledEmail.WELCOME,
'digest': ScheduledEmail.DIGEST,
'invitation_reminder': ScheduledEmail.INVITATION_REMINDER,
}
class RealmAuditLog(models.Model):
"""
RealmAuditLog tracks important changes to users, streams, and
realms in Zulip. It is intended to support both
debugging/introspection (e.g. determining when a user's left a
given stream?) as well as help with some database migrations where
we might be able to do a better data backfill with it. Here are a
few key details about how this works:
* acting_user is the user who initiated the state change
* modified_user (if present) is the user being modified
* modified_stream (if present) is the stream being modified
For example:
* When a user subscribes another user to a stream, modified_user,
acting_user, and modified_stream will all be present and different.
* When an administrator changes an organization's realm icon,
acting_user is that administrator and both modified_user and
modified_stream will be None.
"""
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
acting_user = models.ForeignKey(UserProfile, null=True, related_name='+', on_delete=CASCADE) # type: Optional[UserProfile]
modified_user = models.ForeignKey(UserProfile, null=True, related_name='+', on_delete=CASCADE) # type: Optional[UserProfile]
modified_stream = models.ForeignKey(Stream, null=True, on_delete=CASCADE) # type: Optional[Stream]
event_last_message_id = models.IntegerField(null=True) # type: Optional[int]
event_time = models.DateTimeField(db_index=True) # type: datetime.datetime
# If True, event_time is an overestimate of the true time. Can be used
# by migrations when introducing a new event_type.
backfilled = models.BooleanField(default=False) # type: bool
extra_data = models.TextField(null=True) # type: Optional[str]
STRIPE_CUSTOMER_CREATED = 'stripe_customer_created'
STRIPE_CARD_CHANGED = 'stripe_card_changed'
STRIPE_PLAN_CHANGED = 'stripe_plan_changed'
STRIPE_PLAN_QUANTITY_RESET = 'stripe_plan_quantity_reset'
CUSTOMER_CREATED = 'customer_created'
CUSTOMER_PLAN_CREATED = 'customer_plan_created'
USER_CREATED = 'user_created'
USER_ACTIVATED = 'user_activated'
USER_DEACTIVATED = 'user_deactivated'
USER_REACTIVATED = 'user_reactivated'
USER_SOFT_ACTIVATED = 'user_soft_activated'
USER_SOFT_DEACTIVATED = 'user_soft_deactivated'
USER_PASSWORD_CHANGED = 'user_password_changed'
USER_AVATAR_SOURCE_CHANGED = 'user_avatar_source_changed'
USER_FULL_NAME_CHANGED = 'user_full_name_changed'
USER_EMAIL_CHANGED = 'user_email_changed'
USER_TOS_VERSION_CHANGED = 'user_tos_version_changed'
USER_API_KEY_CHANGED = 'user_api_key_changed'
USER_BOT_OWNER_CHANGED = 'user_bot_owner_changed'
REALM_DEACTIVATED = 'realm_deactivated'
REALM_REACTIVATED = 'realm_reactivated'
REALM_SCRUBBED = 'realm_scrubbed'
REALM_PLAN_TYPE_CHANGED = 'realm_plan_type_changed'
REALM_LOGO_CHANGED = 'realm_logo_changed'
REALM_EXPORTED = 'realm_exported'
SUBSCRIPTION_CREATED = 'subscription_created'
SUBSCRIPTION_ACTIVATED = 'subscription_activated'
SUBSCRIPTION_DEACTIVATED = 'subscription_deactivated'
event_type = models.CharField(max_length=40) # type: str
def __str__(self) -> str:
if self.modified_user is not None:
return "<RealmAuditLog: %s %s %s %s>" % (
self.modified_user, self.event_type, self.event_time, self.id)
if self.modified_stream is not None:
return "<RealmAuditLog: %s %s %s %s>" % (
self.modified_stream, self.event_type, self.event_time, self.id)
return "<RealmAuditLog: %s %s %s %s>" % (
self.realm, self.event_type, self.event_time, self.id)
class UserHotspot(models.Model):
user = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
hotspot = models.CharField(max_length=30) # type: str
timestamp = models.DateTimeField(default=timezone_now) # type: datetime.datetime
class Meta:
unique_together = ("user", "hotspot")
def check_valid_user_ids(realm_id: int, user_ids: List[int],
allow_deactivated: bool=False) -> Optional[str]:
error = check_list(check_int)("User IDs", user_ids)
if error:
return error
realm = Realm.objects.get(id=realm_id)
for user_id in user_ids:
# TODO: Structurally, we should be doing a bulk fetch query to
# get the users here, not doing these in a loop. But because
# this is a rarely used feature and likely to never have more
# than a handful of users, it's probably mostly OK.
try:
user_profile = get_user_profile_by_id_in_realm(user_id, realm)
except UserProfile.DoesNotExist:
return _('Invalid user ID: %d') % (user_id)
if not allow_deactivated:
if not user_profile.is_active:
return _('User with ID %d is deactivated') % (user_id)
if (user_profile.is_bot):
return _('User with ID %d is a bot') % (user_id)
return None
class CustomProfileField(models.Model):
"""Defines a form field for the per-realm custom profile fields feature.
See CustomProfileFieldValue for an individual user's values for one of
these fields.
"""
HINT_MAX_LENGTH = 80
NAME_MAX_LENGTH = 40
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
name = models.CharField(max_length=NAME_MAX_LENGTH) # type: str
hint = models.CharField(max_length=HINT_MAX_LENGTH, default='', null=True) # type: Optional[str]
order = models.IntegerField(default=0) # type: int
SHORT_TEXT = 1
LONG_TEXT = 2
CHOICE = 3
DATE = 4
URL = 5
USER = 6
EXTERNAL_ACCOUNT = 7
# These are the fields whose validators require more than var_name
# and value argument. i.e. CHOICE require field_data, USER require
# realm as argument.
CHOICE_FIELD_TYPE_DATA = [
(CHOICE, str(_('List of options')), validate_choice_field, str, "CHOICE"),
] # type: List[ExtendedFieldElement]
USER_FIELD_TYPE_DATA = [
(USER, str(_('Person picker')), check_valid_user_ids, eval, "USER"),
] # type: List[UserFieldElement]
CHOICE_FIELD_VALIDATORS = {
item[0]: item[2] for item in CHOICE_FIELD_TYPE_DATA
} # type: Dict[int, ExtendedValidator]
USER_FIELD_VALIDATORS = {
item[0]: item[2] for item in USER_FIELD_TYPE_DATA
} # type: Dict[int, RealmUserValidator]
FIELD_TYPE_DATA = [
# Type, Display Name, Validator, Converter, Keyword
(SHORT_TEXT, str(_('Short text')), check_short_string, str, "SHORT_TEXT"),
(LONG_TEXT, str(_('Long text')), check_long_string, str, "LONG_TEXT"),
(DATE, str(_('Date picker')), check_date, str, "DATE"),
(URL, str(_('Link')), check_url, str, "URL"),
(EXTERNAL_ACCOUNT, str(_('External account')), check_short_string, str, "EXTERNAL_ACCOUNT"),
] # type: List[FieldElement]
ALL_FIELD_TYPES = [*FIELD_TYPE_DATA, *CHOICE_FIELD_TYPE_DATA, *USER_FIELD_TYPE_DATA]
FIELD_VALIDATORS = {item[0]: item[2] for item in FIELD_TYPE_DATA} # type: Dict[int, Validator]
FIELD_CONVERTERS = {item[0]: item[3] for item in ALL_FIELD_TYPES} # type: Dict[int, Callable[[Any], Any]]
FIELD_TYPE_CHOICES = [(item[0], item[1]) for item in ALL_FIELD_TYPES] # type: List[Tuple[int, str]]
FIELD_TYPE_CHOICES_DICT = {
item[4]: {"id": item[0], "name": item[1]} for item in ALL_FIELD_TYPES
} # type: Dict[str, Dict[str, Union[str, int]]]
field_type = models.PositiveSmallIntegerField(choices=FIELD_TYPE_CHOICES,
default=SHORT_TEXT) # type: int
# A JSON blob of any additional data needed to define the field beyond
# type/name/hint.
#
# The format depends on the type. Field types SHORT_TEXT, LONG_TEXT,
# DATE, URL, and USER leave this null. Fields of type CHOICE store the
# choices' descriptions.
#
# Note: There is no performance overhead of using TextField in PostgreSQL.
# See https://www.postgresql.org/docs/9.0/static/datatype-character.html
field_data = models.TextField(default='', null=True) # type: Optional[str]
class Meta:
unique_together = ('realm', 'name')
def as_dict(self) -> ProfileDataElement:
return {
'id': self.id,
'name': self.name,
'type': self.field_type,
'hint': self.hint,
'field_data': self.field_data,
'order': self.order,
}
def is_renderable(self) -> bool:
if self.field_type in [CustomProfileField.SHORT_TEXT, CustomProfileField.LONG_TEXT]:
return True
return False
def __str__(self) -> str:
return "<CustomProfileField: %s %s %s %d>" % (self.realm, self.name, self.field_type, self.order)
def custom_profile_fields_for_realm(realm_id: int) -> List[CustomProfileField]:
return CustomProfileField.objects.filter(realm=realm_id).order_by('order')
class CustomProfileFieldValue(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
field = models.ForeignKey(CustomProfileField, on_delete=CASCADE) # type: CustomProfileField
value = models.TextField() # type: str
rendered_value = models.TextField(null=True, default=None) # type: Optional[str]
class Meta:
unique_together = ('user_profile', 'field')
def __str__(self) -> str:
return "<CustomProfileFieldValue: %s %s %s>" % (self.user_profile, self.field, self.value)
# Interfaces for services
# They provide additional functionality like parsing message to obtain query url, data to be sent to url,
# and parsing the response.
GENERIC_INTERFACE = u'GenericService'
SLACK_INTERFACE = u'SlackOutgoingWebhookService'
# A Service corresponds to either an outgoing webhook bot or an embedded bot.
# The type of Service is determined by the bot_type field of the referenced
# UserProfile.
#
# If the Service is an outgoing webhook bot:
# - name is any human-readable identifier for the Service
# - base_url is the address of the third-party site
# - token is used for authentication with the third-party site
#
# If the Service is an embedded bot:
# - name is the canonical name for the type of bot (e.g. 'xkcd' for an instance
# of the xkcd bot); multiple embedded bots can have the same name, but all
# embedded bots with the same name will run the same code
# - base_url and token are currently unused
class Service(models.Model):
name = models.CharField(max_length=UserProfile.MAX_NAME_LENGTH) # type: str
# Bot user corresponding to the Service. The bot_type of this user
# deterines the type of service. If non-bot services are added later,
# user_profile can also represent the owner of the Service.
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
base_url = models.TextField() # type: str
token = models.TextField() # type: str
# Interface / API version of the service.
interface = models.PositiveSmallIntegerField(default=1) # type: int
# Valid interfaces are {generic, zulip_bot_service, slack}
GENERIC = 1
SLACK = 2
ALLOWED_INTERFACE_TYPES = [
GENERIC,
SLACK,
]
# N.B. If we used Django's choice=... we would get this for free (kinda)
_interfaces = {
GENERIC: GENERIC_INTERFACE,
SLACK: SLACK_INTERFACE,
} # type: Dict[int, str]
def interface_name(self) -> str:
# Raises KeyError if invalid
return self._interfaces[self.interface]
def get_bot_services(user_profile_id: str) -> List[Service]:
return list(Service.objects.filter(user_profile__id=user_profile_id))
def get_service_profile(user_profile_id: str, service_name: str) -> Service:
return Service.objects.get(user_profile__id=user_profile_id, name=service_name)
class BotStorageData(models.Model):
bot_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
key = models.TextField(db_index=True) # type: str
value = models.TextField() # type: str
class Meta:
unique_together = ("bot_profile", "key")
class BotConfigData(models.Model):
bot_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
key = models.TextField(db_index=True) # type: str
value = models.TextField() # type: str
class Meta(object):
unique_together = ("bot_profile", "key")
|
tommyip/zulip
|
zerver/models.py
|
Python
|
apache-2.0
| 120,452
|
[
"VisIt"
] |
01b6d345b931b053b48da958de9d1e91eb33306347bd8eb560bf5271e8371249
|
"""
=======================================
Signal processing (:mod:`scipy.signal`)
=======================================
Convolution
===========
.. autosummary::
:toctree: generated/
convolve -- N-dimensional convolution.
correlate -- N-dimensional correlation.
fftconvolve -- N-dimensional convolution using the FFT.
convolve2d -- 2-dimensional convolution (more options).
correlate2d -- 2-dimensional correlation (more options).
sepfir2d -- Convolve with a 2-D separable FIR filter.
B-splines
=========
.. autosummary::
:toctree: generated/
bspline -- B-spline basis function of order n.
cubic -- B-spline basis function of order 3.
quadratic -- B-spline basis function of order 2.
gauss_spline -- Gaussian approximation to the B-spline basis function.
cspline1d -- Coefficients for 1-D cubic (3rd order) B-spline.
qspline1d -- Coefficients for 1-D quadratic (2nd order) B-spline.
cspline2d -- Coefficients for 2-D cubic (3rd order) B-spline.
qspline2d -- Coefficients for 2-D quadratic (2nd order) B-spline.
cspline1d_eval -- Evaluate a cubic spline at the given points.
qspline1d_eval -- Evaluate a quadratic spline at the given points.
spline_filter -- Smoothing spline (cubic) filtering of a rank-2 array.
Filtering
=========
.. autosummary::
:toctree: generated/
order_filter -- N-dimensional order filter.
medfilt -- N-dimensional median filter.
medfilt2d -- 2-dimensional median filter (faster).
wiener -- N-dimensional wiener filter.
symiirorder1 -- 2nd-order IIR filter (cascade of first-order systems).
symiirorder2 -- 4th-order IIR filter (cascade of second-order systems).
lfilter -- 1-dimensional FIR and IIR digital linear filtering.
lfiltic -- Construct initial conditions for `lfilter`.
lfilter_zi -- Compute an initial state zi for the lfilter function that
-- corresponds to the steady state of the step response.
filtfilt -- A forward-backward filter.
savgol_filter -- Filter a signal using the Savitzky-Golay filter.
deconvolve -- 1-d deconvolution using lfilter.
sosfilt -- 1-dimensional IIR digital linear filtering using
-- a second-order-sections filter representation.
sosfilt_zi -- Compute an initial state zi for the sosfilt function that
-- corresponds to the steady state of the step response.
hilbert -- Compute 1-D analytic signal, using the Hilbert transform.
hilbert2 -- Compute 2-D analytic signal, using the Hilbert transform.
decimate -- Downsample a signal.
detrend -- Remove linear and/or constant trends from data.
resample -- Resample using Fourier method.
Filter design
=============
.. autosummary::
:toctree: generated/
bilinear -- Digital filter from an analog filter using
-- the bilinear transform.
findfreqs -- Find array of frequencies for computing filter response.
firwin -- Windowed FIR filter design, with frequency response
-- defined as pass and stop bands.
firwin2 -- Windowed FIR filter design, with arbitrary frequency
-- response.
freqs -- Analog filter frequency response.
freqz -- Digital filter frequency response.
iirdesign -- IIR filter design given bands and gains.
iirfilter -- IIR filter design given order and critical frequencies.
kaiser_atten -- Compute the attenuation of a Kaiser FIR filter, given
-- the number of taps and the transition width at
-- discontinuities in the frequency response.
kaiser_beta -- Compute the Kaiser parameter beta, given the desired
-- FIR filter attenuation.
kaiserord -- Design a Kaiser window to limit ripple and width of
-- transition region.
savgol_coeffs -- Compute the FIR filter coefficients for a Savitzky-Golay
-- filter.
remez -- Optimal FIR filter design.
unique_roots -- Unique roots and their multiplicities.
residue -- Partial fraction expansion of b(s) / a(s).
residuez -- Partial fraction expansion of b(z) / a(z).
invres -- Inverse partial fraction expansion for analog filter.
invresz -- Inverse partial fraction expansion for digital filter.
Lower-level filter design functions:
.. autosummary::
:toctree: generated/
abcd_normalize -- Check state-space matrices and ensure they are rank-2.
band_stop_obj -- Band Stop Objective Function for order minimization.
besselap -- Return (z,p,k) for analog prototype of Bessel filter.
buttap -- Return (z,p,k) for analog prototype of Butterworth filter.
cheb1ap -- Return (z,p,k) for type I Chebyshev filter.
cheb2ap -- Return (z,p,k) for type II Chebyshev filter.
cmplx_sort -- Sort roots based on magnitude.
ellipap -- Return (z,p,k) for analog prototype of elliptic filter.
lp2bp -- Transform a lowpass filter prototype to a bandpass filter.
lp2bs -- Transform a lowpass filter prototype to a bandstop filter.
lp2hp -- Transform a lowpass filter prototype to a highpass filter.
lp2lp -- Transform a lowpass filter prototype to a lowpass filter.
normalize -- Normalize polynomial representation of a transfer function.
Matlab-style IIR filter design
==============================
.. autosummary::
:toctree: generated/
butter -- Butterworth
buttord
cheby1 -- Chebyshev Type I
cheb1ord
cheby2 -- Chebyshev Type II
cheb2ord
ellip -- Elliptic (Cauer)
ellipord
bessel -- Bessel (no order selection available -- try butterod)
Continuous-Time Linear Systems
==============================
.. autosummary::
:toctree: generated/
freqresp -- frequency response of a continuous-time LTI system.
lti -- linear time invariant system object.
lsim -- continuous-time simulation of output to linear system.
lsim2 -- like lsim, but `scipy.integrate.odeint` is used.
impulse -- impulse response of linear, time-invariant (LTI) system.
impulse2 -- like impulse, but `scipy.integrate.odeint` is used.
step -- step response of continous-time LTI system.
step2 -- like step, but `scipy.integrate.odeint` is used.
bode -- Calculate Bode magnitude and phase data.
Discrete-Time Linear Systems
============================
.. autosummary::
:toctree: generated/
dlsim -- simulation of output to a discrete-time linear system.
dimpulse -- impulse response of a discrete-time LTI system.
dstep -- step response of a discrete-time LTI system.
LTI Representations
===================
.. autosummary::
:toctree: generated/
tf2zpk -- transfer function to zero-pole-gain.
tf2sos -- transfer function to second-order sections.
tf2ss -- transfer function to state-space.
zpk2tf -- zero-pole-gain to transfer function.
zpk2sos -- zero-pole-gain to second-order sections.
zpk2ss -- zero-pole-gain to state-space.
ss2tf -- state-pace to transfer function.
ss2zpk -- state-space to pole-zero-gain.
sos2zpk -- second-order-sections to zero-pole-gain.
sos2tf -- second-order-sections to transfer function.
cont2discrete -- continuous-time to discrete-time LTI conversion.
Waveforms
=========
.. autosummary::
:toctree: generated/
chirp -- Frequency swept cosine signal, with several freq functions.
gausspulse -- Gaussian modulated sinusoid
max_len_seq -- Maximum length sequence
sawtooth -- Periodic sawtooth
square -- Square wave
sweep_poly -- Frequency swept cosine signal; freq is arbitrary polynomial
Window functions
================
.. autosummary::
:toctree: generated/
get_window -- Return a window of a given length and type.
barthann -- Bartlett-Hann window
bartlett -- Bartlett window
blackman -- Blackman window
blackmanharris -- Minimum 4-term Blackman-Harris window
bohman -- Bohman window
boxcar -- Boxcar window
chebwin -- Dolph-Chebyshev window
cosine -- Cosine window
flattop -- Flat top window
gaussian -- Gaussian window
general_gaussian -- Generalized Gaussian window
hamming -- Hamming window
hann -- Hann window
kaiser -- Kaiser window
nuttall -- Nuttall's minimum 4-term Blackman-Harris window
parzen -- Parzen window
slepian -- Slepian window
triang -- Triangular window
Wavelets
========
.. autosummary::
:toctree: generated/
cascade -- compute scaling function and wavelet from coefficients
daub -- return low-pass
morlet -- Complex Morlet wavelet.
qmf -- return quadrature mirror filter from low-pass
ricker -- return ricker wavelet
cwt -- perform continuous wavelet transform
Peak finding
============
.. autosummary::
:toctree: generated/
find_peaks_cwt -- Attempt to find the peaks in the given 1-D array
argrelmin -- Calculate the relative minima of data
argrelmax -- Calculate the relative maxima of data
argrelextrema -- Calculate the relative extrema of data
Spectral Analysis
=================
.. autosummary::
:toctree: generated/
periodogram -- Computes a (modified) periodogram
welch -- Compute a periodogram using Welch's method
lombscargle -- Computes the Lomb-Scargle periodogram
vectorstrength -- Computes the vector strength
"""
from __future__ import division, print_function, absolute_import
from . import sigtools
from .waveforms import *
from ._max_len_seq import max_len_seq
# The spline module (a C extension) provides:
# cspline2d, qspline2d, sepfir2d, symiirord1, symiirord2
from .spline import *
from .bsplines import *
from .cont2discrete import *
from .dltisys import *
from .filter_design import *
from .fir_filter_design import *
from .ltisys import *
from .windows import *
from .signaltools import *
from ._savitzky_golay import savgol_coeffs, savgol_filter
from .spectral import *
from .wavelets import *
from ._peak_finding import *
__all__ = [s for s in dir() if not s.startswith('_')]
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
|
dch312/scipy
|
scipy/signal/__init__.py
|
Python
|
bsd-3-clause
| 10,615
|
[
"Gaussian"
] |
1ddb1af1120c67efa832c96842c7bd0cecb2ec0d1fe79fd2b6540d2c0e379788
|
import random
def generate_haiku_name():
adjs = [
"autumn", "hidden", "bitter", "misty", "silent", "empty", "dry", "dark",
"summer", "icy", "delicate", "quiet", "white", "cool", "spring", "winter",
"patient", "twilight", "dawn", "crimson", "wispy", "weathered", "blue",
"billowing", "broken", "cold", "damp", "falling", "frosty", "green",
"long", "late", "lingering", "bold", "little", "morning", "muddy", "old",
"red", "rough", "still", "small", "sparkling", "throbbing", "shy",
"wandering", "withered", "wild", "black", "young", "holy", "solitary",
"fragrant", "aged", "snowy", "proud", "floral", "restless", "divine",
"polished", "ancient", "purple", "lively", "nameless", "teal", "charming",
"lush", "tropical", "stunning", "thriving", "fluffy", "gentle", "enigmatic"
]
nouns = [
"waterfall", "river", "breeze", "moon", "rain", "wind", "sea", "morning",
"snow", "lake", "sunset", "pine", "shadow", "leaf", "dawn", "glitter",
"forest", "hill", "cloud", "meadow", "sun", "glade", "bird", "brook",
"butterfly", "bush", "dew", "dust", "field", "fire", "flower", "firefly",
"feather", "grass", "haze", "mountain", "night", "pond", "darkness",
"snowflake", "silence", "sound", "sky", "shape", "surf", "thunder",
"violet", "water", "wildflower", "wave", "water", "resonance", "sun",
"wood", "dream", "cherry", "tree", "fog", "frost", "voice", "paper",
"frog", "smoke", "star"
]
adj = random.choice(adjs)
noun = random.choice(nouns)
rand_num = '{0:04}'.format(random.randint(1000, 10000))
haiku_name = "{0}-{1}-{2}".format(adj, noun, rand_num)
return haiku_name
|
amonapp/amon
|
amon/utils/haiku.py
|
Python
|
agpl-3.0
| 1,790
|
[
"Firefly"
] |
3f0c5d46473e732357a453a37c8deb79fd8f71fdcc7d1901fca1424ddbf97602
|
# -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON 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.
#
# HORTON 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/>
#
# --
import numpy as np, os
from nose.tools import assert_raises
from nose.plugins.attrib import attr
from horton import * # pylint: disable=wildcard-import,unused-wildcard-import
from horton.test.common import compare_operators
def test_shell_nbasis():
assert get_shell_nbasis(-3) == 7
assert get_shell_nbasis(-2) == 5
assert get_shell_nbasis( 0) == 1
assert get_shell_nbasis( 1) == 3
assert get_shell_nbasis( 2) == 6
assert get_shell_nbasis( 3) == 10
with assert_raises(ValueError):
get_shell_nbasis(-1)
def test_gobasis_consistency():
centers = np.random.uniform(-1, 1, (2, 3))
shell_map = np.array([0, 0, 0, 1, 1, 1, 1])
nprims = np.array([2, 3, 3, 5, 5, 5, 7])
shell_types = np.array([2, 1, 0, -2, 3, 0, 1])
alphas = np.random.uniform(0, 1, nprims.sum())
con_coeffs = np.random.uniform(-1, 1, nprims.sum())
gobasis = GOBasis(centers, shell_map, nprims, shell_types, alphas, con_coeffs)
assert gobasis.nbasis == 29
assert gobasis.max_shell_type == 3
scales = gobasis.get_scales()
assert abs(scales[0] - gob_cart_normalization(alphas[0], np.array([2, 0, 0]))) < 1e-10
assert (gobasis.basis_offsets == np.array([0, 6, 9, 10, 15, 25, 26])).all()
assert (gobasis.shell_lookup == np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 3,
3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 5, 6, 6, 6])).all()
shell_types = np.array([1, 1, 0, -2, -2, 0, 1])
gobasis = GOBasis(centers, shell_map, nprims, shell_types, alphas, con_coeffs)
assert gobasis.nbasis == 21
assert gobasis.max_shell_type == 2
# The center indexes in the shell_map are out of range.
shell_map[0] = 2
with assert_raises(ValueError):
i2 = GOBasis(centers, shell_map, nprims, shell_types, alphas, con_coeffs)
shell_map[0] = 0
# The size of the array shell_types does not match the sum of nprims.
shell_types = np.array([1, 1])
with assert_raises(TypeError):
i2 = GOBasis(centers, shell_map, nprims, shell_types, alphas, con_coeffs)
shell_types = np.array([1, 1, 0, -2, -2, 0, 1])
# The elements of nprims should be at least 1.
nprims[1] = 0
with assert_raises(ValueError):
i2 = GOBasis(centers, shell_map, nprims, shell_types, alphas, con_coeffs)
nprims[1] = 3
# The size of the array alphas does not match the sum of nprims.
alphas = np.random.uniform(-1, 1, 2)
with assert_raises(TypeError):
i2 = GOBasis(centers, shell_map, nprims, shell_types, alphas, con_coeffs)
alphas = np.random.uniform(-1, 1, nprims.sum())
# Encountered the nonexistent shell_type -1.
shell_types[1] = -1
with assert_raises(ValueError):
i2 = GOBasis(centers, shell_map, nprims, shell_types, alphas, con_coeffs)
shell_types[1] = 1
# The size of con_coeffs does not match nprims.
con_coeffs = np.random.uniform(-1, 1, 3)
with assert_raises(TypeError):
i2 = GOBasis(centers, shell_map, nprims, shell_types, alphas, con_coeffs)
con_coeffs = np.random.uniform(-1, 1, nprims.sum())
# Exceeding the maximym shell type (above):
shell_types[0] = get_max_shell_type()+1
with assert_raises(ValueError):
i2 = GOBasis(centers, shell_map, nprims, shell_types, alphas, con_coeffs)
shell_types[0] = 2
# Exceeding the maximym shell type (below):
shell_types[0] = -get_max_shell_type()-1
with assert_raises(ValueError):
i2 = GOBasis(centers, shell_map, nprims, shell_types, alphas, con_coeffs)
shell_types[0] = 2
def test_load_basis():
for go_basis_family in go_basis_families.itervalues():
assert os.path.basename(go_basis_family.filename).islower()
go_basis_family.load()
def test_grid_lih_321g_hf_density_some_points():
ref = np.array([ # from cubegen
[0.0, 0.0, 0.0, 0.037565082428],
[0.1, 0.0, 0.0, 0.034775306876],
[0.0, 0.1, 0.0, 0.034775306876],
[0.0, 0.0, 1.0, 0.186234028507],
[0.4, 0.2, 0.1, 0.018503681370],
])
ref[:,:3] *= angstrom
mol = IOData.from_file(context.get_fn('test/li_h_3-21G_hf_g09.fchk'))
# check for one point the compute_grid_point1 method
output = np.zeros(mol.obasis.nbasis, float)
point = np.array([0.0, 0.0, 1.0])*angstrom
grid_fn = GB1DMGridDensityFn(mol.obasis.max_shell_type)
mol.obasis.compute_grid_point1(output, point, grid_fn)
# first basis function is contraction of three s-type gaussians
assert mol.obasis.nprims[0] == 3
scales = mol.obasis.get_scales()
total = 0.0
for i in xrange(3):
alpha = mol.obasis.alphas[i]
coeff = mol.obasis.con_coeffs[i]
nrml = gob_cart_normalization(alpha, np.zeros(3, int))
# check scale
assert abs(scales[i] - nrml) < 1e-10
# check that we are on the first atom
assert mol.obasis.shell_map[i] == 0
dsq = np.linalg.norm(point - mol.coordinates[0])**2
gauss = nrml*np.exp(-alpha*dsq)
total += coeff*gauss
assert abs(total - output[0]) < 1e-10
# check density matrix value
dm_full = mol.get_dm_full()
assert abs(dm_full._array[0,0] - 1.96589709) < 1e-7
points = ref[:,:3].copy()
rhos = mol.obasis.compute_grid_density_dm(dm_full, points)
assert abs(rhos - ref[:,3]).max() < 1e-5
def check_grid_rho(fn, ref, eps):
mol = IOData.from_file(context.get_fn(fn))
points = ref[:,:3].copy()
dm_full = mol.get_dm_full()
rhos = mol.obasis.compute_grid_density_dm(dm_full, points)
assert abs(rhos - ref[:,3]).max() < eps
def test_grid_co_ccpv5z_cart_hf_density_some_points():
ref = np.array([ # from cubegen
[ 0.0, 0.0, 0.0, 4.54392441417],
[ 0.1, 0.0, 0.0, 2.87874696902],
[ 0.0, 0.1, 0.0, 2.90909931711],
[ 0.0, 0.0, 1.0, 0.00563354926],
[ 0.4, 0.2, 0.1, 0.15257439924],
[-0.4, 0.2, 0.1, 0.14408104500],
[ 0.4, -0.2, 0.1, 0.14627065655],
[ 0.4, 0.2, -0.1, 0.11912840380],
])
ref[:,:3] *= angstrom
check_grid_rho('test/co_ccpv5z_cart_hf_g03.fchk', ref, 3e-3)
def test_grid_co_ccpv5z_pure_hf_density_some_points():
ref = np.array([ # from cubegen
[ 0.0, 0.0, 0.0, 4.54338939220],
[ 0.1, 0.0, 0.0, 2.87742753163],
[ 0.0, 0.1, 0.0, 2.90860415538],
[ 0.0, 0.0, 1.0, 0.00285462032],
[ 0.4, 0.2, 0.1, 0.15399703660],
[-0.4, 0.2, 0.1, 0.14425254494],
[ 0.4, -0.2, 0.1, 0.14409038614],
[ 0.4, 0.2, -0.1, 0.11750780363],
])
ref[:,:3] *= angstrom
check_grid_rho('test/co_ccpv5z_pure_hf_g03.fchk', ref, 3e-3)
def check_grid_gradient(fn, ref, eps):
mol = IOData.from_file(context.get_fn(fn))
points = ref[:,:3].copy()
dm_full = mol.get_dm_full()
gradients = mol.obasis.compute_grid_gradient_dm(dm_full, points)
assert abs(gradients - ref[:,3:]).max() < eps
def test_grid_lih_321g_hf_gradient_some_points():
ref = np.array([ # from cubegen
[0.0, 0.0, 0.0, 0.000000000000, 0.000000000000, 0.179349665782],
[0.1, 0.0, 0.0, -0.028292898754, 0.000000000000, 0.164582727812],
[0.0, 0.1, 0.0, 0.000000000000, -0.028292898754, 0.164582727812],
[0.0, 0.0, 1.0, 0.000000000000, 0.000000000000, -0.929962409854],
[0.4, 0.2, 0.1, -0.057943497876, -0.028971748938, 0.069569174116],
])
ref[:,:3] *= angstrom
check_grid_gradient('test/li_h_3-21G_hf_g09.fchk', ref, 1e-6)
def test_grid_co_ccpv5z_cart_hf_gradient_some_points():
ref = np.array([ # from cubegen
[ 0.0, 0.0, 0.0, -0.26805895992, -0.03725931097, 26.06939895580],
[ 0.1, 0.0, 0.0, -11.66097634913, -0.02427222636, 11.49946087301],
[ 0.0, 0.1, 0.0, -0.18730587145, -11.60371334591, 11.60046471817],
[ 0.0, 0.0, 1.0, 0.00350647376, -0.00151630329, -0.00944412097],
[ 0.4, 0.2, 0.1, -0.46814335442, -0.28380627268, -0.02592227656],
[-0.4, 0.2, 0.1, 0.63742782898, -0.32989678808, 0.00444361306],
[ 0.4, -0.2, 0.1, -0.50464249640, 0.29978538874, -0.01244489023],
[ 0.4, 0.2, -0.1, -0.21837773815, -0.16855926400, 0.15518115326],
])
ref[:,:3] *= angstrom
check_grid_gradient('test/co_ccpv5z_cart_hf_g03.fchk', ref, 1e-2) # cubegen output somehow not reliable?
def test_grid_co_ccpv5z_pure_hf_gradient_some_points():
ref = np.array([ # from cubegen
[ 0.0, 0.0, 0.0, -0.27796827654, -0.03971005800, 26.06788123216],
[ 0.1, 0.0, 0.0, -11.65999871789, -0.02706024561, 11.49763108605],
[ 0.0, 0.1, 0.0, -0.19499030621, -11.60235682832, 11.60235521243],
[ 0.0, 0.0, 1.0, 0.00184843964, 0.00026806115, -0.01003272687],
[ 0.4, 0.2, 0.1, -0.46500454519, -0.27516942731, -0.01707049479],
[-0.4, 0.2, 0.1, 0.63911725484, -0.32989616481, 0.00229353087],
[ 0.4, -0.2, 0.1, -0.51099806603, 0.29961935521, -0.00979594206],
[ 0.4, 0.2, -0.1, -0.21849813344, -0.16098019809, 0.16093849962],
])
ref[:,:3] *= angstrom
check_grid_gradient('test/co_ccpv5z_pure_hf_g03.fchk', ref, 1e-4)
def check_grid_esp(fn, ref, eps):
mol = IOData.from_file(context.get_fn(fn))
points = ref[:,:3].copy()
dm_full = mol.get_dm_full()
esps = mol.obasis.compute_grid_esp_dm(dm_full, mol.coordinates, mol.pseudo_numbers, points)
assert abs(esps - ref[:,3]).max() < eps
def test_grid_lih_321g_hf_esp_some_points():
ref = np.array([ # from cubegen
[0.0, 0.0, 0.0, 0.906151727538],
[0.1, 0.0, 0.0, 0.891755005233],
[0.0, 0.1, 0.0, 0.891755005233],
[0.0, 0.0, 1.0, 1.422294470114],
[0.4, 0.2, 0.1, 0.796490099689],
])
ref[:,:3] *= angstrom
check_grid_esp('test/li_h_3-21G_hf_g09.fchk', ref, 1e-8)
@attr('slow')
def test_grid_co_ccpv5z_cart_hf_esp_some_points():
ref = np.array([ # from cubegen
[ 0.0, 0.0, 0.0, 10.69443507172],
[ 0.1, 0.0, 0.0, 6.43122889229],
[ 0.0, 0.1, 0.0, 6.43406765938],
[ 0.0, 0.0, 1.0, 0.27023448629],
[ 0.4, 0.2, 0.1, 0.82646540602],
[-0.4, 0.2, 0.1, 0.93595072191],
[ 0.4, -0.2, 0.1, 0.83432301119],
[ 0.4, 0.2, -0.1, 0.68524674809],
])
ref[:,:3] *= angstrom
check_grid_esp('test/co_ccpv5z_cart_hf_g03.fchk', ref, 1e-3) # cubegen output somehow not reliable?
@attr('slow')
def test_grid_co_ccpv5z_pure_hf_esp_some_points():
ref = np.array([ # from cubegen
[ 0.0, 0.0, 0.0, 10.69443507172],
[ 0.1, 0.0, 0.0, 6.43122889229],
[ 0.0, 0.1, 0.0, 6.43406765938],
[ 0.0, 0.0, 1.0, 0.27023448629],
[ 0.4, 0.2, 0.1, 0.82646540602],
[-0.4, 0.2, 0.1, 0.93595072191],
[ 0.4, -0.2, 0.1, 0.83432301119],
[ 0.4, 0.2, -0.1, 0.68524674809],
])
ref[:,:3] *= angstrom
check_grid_esp('test/co_ccpv5z_pure_hf_g03.fchk', ref, 1e-5)
def test_grid_two_index_ne():
mol = IOData.from_file(context.get_fn('test/li_h_3-21G_hf_g09.fchk'))
rtf = ExpRTransform(1e-3, 2e1, 100)
rgrid = RadialGrid(rtf)
grid = BeckeMolGrid(mol.coordinates, mol.numbers, mol.pseudo_numbers, (rgrid, 110), random_rotate=False)
dist0 = np.sqrt(((grid.points - mol.coordinates[0])**2).sum(axis=1))
dist1 = np.sqrt(((grid.points - mol.coordinates[1])**2).sum(axis=1))
pot = -mol.numbers[0]/dist0 - mol.numbers[1]/dist1
na_ana = mol.lf.create_two_index()
mol.obasis.compute_nuclear_attraction(mol.coordinates, mol.pseudo_numbers, na_ana)
na_grid = mol.lf.create_two_index()
mol.obasis.compute_grid_density_fock(grid.points, grid.weights, pot, na_grid)
# compare grid-based operator with analytical result
assert abs(na_grid._array).max() > 8.0
assert abs(na_ana._array-na_grid._array).max() < 2e-3
# check symmetry
assert na_grid.is_symmetric()
def test_gob_normalization():
assert abs(gob_pure_normalization(0.09515, 0) - 0.122100288) < 1e-5
assert abs(gob_pure_normalization(0.1687144, 1) - 0.154127551) < 1e-5
assert abs(gob_cart_normalization(0.344, np.array([1,1,0])) - 0.440501466) < 1e-8
assert abs(gob_cart_normalization(0.246, np.array([1,1,1])) - 0.242998767) < 1e-8
assert abs(gob_cart_normalization(0.238, np.array([2,1,1])) - 0.127073818) < 1e-8
assert abs(gob_pure_normalization(0.3, 0) - gob_cart_normalization(0.3, np.array([0, 0, 0]))) < 1e-10
assert abs(gob_pure_normalization(0.7, 0) - gob_cart_normalization(0.7, np.array([0, 0, 0]))) < 1e-10
assert abs(gob_pure_normalization(1.9, 0) - gob_cart_normalization(1.9, np.array([0, 0, 0]))) < 1e-10
assert abs(gob_pure_normalization(0.3, 1) - gob_cart_normalization(0.3, np.array([1, 0, 0]))) < 1e-10
assert abs(gob_pure_normalization(0.7, 1) - gob_cart_normalization(0.7, np.array([0, 1, 0]))) < 1e-10
assert abs(gob_pure_normalization(1.9, 1) - gob_cart_normalization(1.9, np.array([0, 0, 1]))) < 1e-10
def test_cart_pure_switch():
mol = IOData.from_file(context.get_fn('test/water.xyz'))
obasis = get_gobasis(mol.coordinates, mol.numbers, 'aug-cc-pvdz')
assert obasis.nbasis == 41
obasis = get_gobasis(mol.coordinates, mol.numbers, 'aug-cc-pvdz', pure=False)
assert obasis.nbasis == 43
def get_olp(ob):
lf = DenseLinalgFactory(ob.nbasis)
olp = lf.create_two_index()
ob.compute_overlap(olp)
return olp._array
def test_concatenate1():
mol = IOData.from_file(context.get_fn('test/water.xyz'))
obtmp = get_gobasis(mol.coordinates, mol.numbers, '3-21g')
ob = GOBasis.concatenate(obtmp, obtmp)
assert ob.ncenter == 3*2
assert ob.nbasis == 13*2
a = get_olp(ob)
assert abs(a[:13,:13] - a[:13,13:]).max() < 1e-15
assert (a[:13,:13] == a[13:,13:]).all()
assert abs(a[:13,:13] - a[13:,:13]).max() < 1e-15
def test_concatenate2():
mol = IOData.from_file(context.get_fn('test/water.xyz'))
obasis1 = get_gobasis(mol.coordinates, mol.numbers, '3-21g')
obasis2 = get_gobasis(mol.coordinates, mol.numbers, 'sto-3g')
obasis = GOBasis.concatenate(obasis1, obasis2)
assert obasis.ncenter == 3*2
assert obasis.nbasis == obasis1.nbasis + obasis2.nbasis
a = get_olp(obasis)
a11 = get_olp(obasis1)
a22 = get_olp(obasis2)
N = obasis1.nbasis
assert (a[:N,:N] == a11).all()
assert (a[N:,N:] == a22).all()
def test_abstract():
with assert_raises(NotImplementedError):
centers = np.zeros((1,3), float)
shell_map = np.zeros(2, int)
nprims = np.array([1, 2])
shell_types = np.array([0, 1])
alphas = np.array([1.0, 1.1, 1.2])
con_coeffs = np.array([0.1, 0.2, 0.3])
from horton.gbasis.cext import GBasis
gb = GBasis(centers, shell_map, nprims, shell_types, alphas, con_coeffs)
def test_gobasis_desc_element_map():
gobd = GOBasisDesc('3-21G', {'H': 'sto-3g', 2: 'cc-pVQZ'})
coordinates = np.zeros([3, 3])
numbers = np.array([1, 2, 3])
obasis = gobd.apply_to(coordinates, numbers)
assert obasis.centers.shape == (3, 3)
# H
assert obasis.shell_map[0] == 0
assert obasis.nprims[0] == 3
# He
assert (obasis.shell_map[1:11] == 1).all()
assert (obasis.nprims[1:11] == [4, 1, 1, 1, 1, 1, 1, 1, 1, 1]).all()
# Li
assert (obasis.shell_map[11:] == 2).all()
assert (obasis.nprims[11:] == [3, 2, 2, 1, 1]).all()
def test_gobasis_desc_index_map():
gobd = GOBasisDesc('3-21G', index_map={1: 'sto-3g', 2: 'cc-pVQZ'})
coordinates = np.zeros([3, 3])
numbers = np.array([1, 1, 1])
obasis = gobd.apply_to(coordinates, numbers)
assert obasis.centers.shape == (3, 3)
# H
assert (obasis.shell_map[:2] == 0).all()
assert (obasis.nprims[:2] == [2, 1]).all()
# He
assert (obasis.shell_map[2:3] == 1).all()
assert (obasis.nprims[2:3] == 3).all()
# Li
assert (obasis.shell_map[3:] == 2).all()
assert (obasis.nprims[3:] == [3, 1, 1, 1, 1, 1, 1, 1, 1, 1]).all()
def test_gobasis_output_args_overlap():
mol = IOData.from_file(context.get_fn('test/water.xyz'))
obasis = get_gobasis(mol.coordinates, mol.numbers, '3-21g')
lf = DenseLinalgFactory(obasis.nbasis)
olp1 = lf.create_two_index(obasis.nbasis)
obasis.compute_overlap(olp1)
olp2 = obasis.compute_overlap(lf)
compare_operators(olp1, olp2)
def test_gobasis_output_args_kinetic():
mol = IOData.from_file(context.get_fn('test/water.xyz'))
obasis = get_gobasis(mol.coordinates, mol.numbers, '3-21g')
lf = DenseLinalgFactory(obasis.nbasis)
kin1 = lf.create_two_index(obasis.nbasis)
obasis.compute_kinetic(kin1)
kin2 = obasis.compute_kinetic(lf)
compare_operators(kin1, kin2)
def test_gobasis_output_args_nuclear_attraction():
mol = IOData.from_file(context.get_fn('test/water.xyz'))
obasis = get_gobasis(mol.coordinates, mol.numbers, '3-21g')
lf = DenseLinalgFactory(obasis.nbasis)
nai1 = lf.create_two_index(obasis.nbasis)
obasis.compute_nuclear_attraction(mol.coordinates, mol.pseudo_numbers, nai1)
nai2 = obasis.compute_nuclear_attraction(mol.coordinates, mol.pseudo_numbers, lf)
compare_operators(nai1, nai2)
def test_gobasis_output_args_electron_repulsion():
mol = IOData.from_file(context.get_fn('test/water.xyz'))
obasis = get_gobasis(mol.coordinates, mol.numbers, '3-21g')
lf = DenseLinalgFactory(obasis.nbasis)
er1 = lf.create_four_index(obasis.nbasis)
obasis.compute_electron_repulsion(er1)
er2 = obasis.compute_electron_repulsion(lf)
compare_operators(er1, er2)
def test_gobasis_output_args_grid_orbitals_exp():
mol = IOData.from_file(context.get_fn('test/water_hfs_321g.fchk'))
points = np.random.uniform(-5, 5, (100, 3))
iorbs = np.array([2, 3])
orbs1 = np.zeros((100, 2), float)
mol.obasis.compute_grid_orbitals_exp(mol.exp_alpha, points, iorbs, orbs1)
orbs2 = mol.obasis.compute_grid_orbitals_exp(mol.exp_alpha, points, iorbs)
assert (orbs1 == orbs2).all()
def test_gobasis_output_args_grid_density_dm():
mol = IOData.from_file(context.get_fn('test/water_hfs_321g.fchk'))
points = np.random.uniform(-5, 5, (100, 3))
rhos1 = np.zeros(100, float)
dm_full = mol.get_dm_full()
mol.obasis.compute_grid_density_dm(dm_full, points, rhos1)
rhos2 = mol.obasis.compute_grid_density_dm(dm_full, points)
assert (rhos1 == rhos2).all()
def test_gobasis_output_args_grid_gradient_dm():
mol = IOData.from_file(context.get_fn('test/water_hfs_321g.fchk'))
points = np.random.uniform(-5, 5, (100, 3))
gradrhos1 = np.zeros((100, 3), float)
dm_full = mol.get_dm_full()
mol.obasis.compute_grid_gradient_dm(dm_full, points, gradrhos1)
gradrhos2 = mol.obasis.compute_grid_gradient_dm(dm_full, points)
assert (gradrhos1 == gradrhos2).all()
def test_gobasis_output_args_grid_hartree_dm():
mol = IOData.from_file(context.get_fn('test/water_hfs_321g.fchk'))
points = np.random.uniform(-5, 5, (100, 3))
pots1 = np.zeros(100, float)
dm_full = mol.get_dm_full()
mol.obasis.compute_grid_hartree_dm(dm_full, points, pots1)
pots2 = mol.obasis.compute_grid_hartree_dm(dm_full, points)
assert (pots1 == pots2).all()
def test_subset_simple():
mol = IOData.from_file(context.get_fn('test/water_hfs_321g.fchk'))
# select a basis set for the first hydrogen atom
sub_obasis, ibasis_list = mol.obasis.get_subset([0,1])
assert sub_obasis.ncenter == 1
assert sub_obasis.nshell == 2
assert (sub_obasis.centers[0] == mol.obasis.centers[0]).all()
assert (sub_obasis.shell_map == mol.obasis.shell_map[:2]).all()
assert (sub_obasis.nprims == mol.obasis.nprims[:2]).all()
assert (sub_obasis.shell_types == mol.obasis.shell_types[:2]).all()
assert sub_obasis.nprim_total == 3
assert (sub_obasis.alphas == mol.obasis.alphas[:3]).all()
assert (sub_obasis.con_coeffs == mol.obasis.con_coeffs[:3]).all()
assert (ibasis_list == [0, 1]).all()
def test_subset_simple_reverse():
mol = IOData.from_file(context.get_fn('test/water_hfs_321g.fchk'))
# select a basis set for the first hydrogen atom
sub_obasis, ibasis_list = mol.obasis.get_subset([1,0])
assert sub_obasis.ncenter == 1
assert sub_obasis.nshell == 2
assert (sub_obasis.centers[0] == mol.obasis.centers[0]).all()
assert (sub_obasis.shell_map == mol.obasis.shell_map[1::-1]).all()
assert (sub_obasis.nprims == mol.obasis.nprims[1::-1]).all()
assert (sub_obasis.shell_types == mol.obasis.shell_types[1::-1]).all()
assert sub_obasis.nprim_total == 3
assert (sub_obasis.alphas[:1] == mol.obasis.alphas[2:3]).all()
assert (sub_obasis.alphas[1:] == mol.obasis.alphas[:2]).all()
assert (sub_obasis.con_coeffs[:1] == mol.obasis.con_coeffs[2:3]).all()
assert (sub_obasis.con_coeffs[1:] == mol.obasis.con_coeffs[:2]).all()
assert (ibasis_list == [1, 0]).all()
def test_subset():
mol = IOData.from_file(context.get_fn('test/water_hfs_321g.fchk'))
# select a basis set for the first hydrogen atom
sub_obasis, ibasis_list = mol.obasis.get_subset([7, 3, 4, 8])
assert sub_obasis.ncenter == 2
assert sub_obasis.nshell == 4
assert (sub_obasis.centers[0] == mol.obasis.centers[1]).all()
assert (sub_obasis.centers[1] == mol.obasis.centers[2]).all()
assert (sub_obasis.shell_map == mol.obasis.shell_map[[7, 3, 4, 8]]-1).all()
assert (sub_obasis.nprims == mol.obasis.nprims[[7, 3, 4, 8]]).all()
assert (sub_obasis.shell_types == mol.obasis.shell_types[[7, 3, 4, 8]]).all()
assert sub_obasis.nprim_total == 7
for b0, e0, b1, e1 in (12, 14, 0, 2), (6, 8, 2, 4), (8, 10, 4, 6), (14, 15, 6, 7):
assert (sub_obasis.alphas[b1:e1] == mol.obasis.alphas[b0:e0]).all()
assert (sub_obasis.con_coeffs[b1:e1] == mol.obasis.con_coeffs[b0:e0]).all()
assert (ibasis_list == [11, 3, 4, 5, 6, 12]).all()
def test_basis_atoms():
mol = IOData.from_file(context.get_fn('test/water_hfs_321g.fchk'))
basis_atoms = mol.obasis.get_basis_atoms(mol.coordinates)
assert len(basis_atoms) == 3
icenter = 0
ibasis_all = []
for sub_obasis, ibasis_list in basis_atoms:
assert sub_obasis.ncenter == 1
assert (sub_obasis.centers[0] == mol.obasis.centers[icenter]).all()
icenter += 1
ibasis_all.extend(ibasis_list)
assert ibasis_all == range(mol.obasis.nbasis)
def check_normalization(number, basis):
"""Helper function to test the normalization of contracted basis sets.
Parameters
----------
number : int
Element to test. (Keep in mind that not all elements are supported in most
basis sets.)
basis : str
The basis set, e.g. cc-pvdz.
"""
# Run test on a Helium atom
mol = IOData(coordinates=np.array([[0.0, 0.0, 0.0]]), numbers=np.array([number]))
# Create a Gaussian basis set
obasis = get_gobasis(mol.coordinates, mol.numbers, basis)
# Create a linalg factory
lf = DenseLinalgFactory(obasis.nbasis)
# Compute Gaussian integrals
olp = obasis.compute_overlap(lf)
np.testing.assert_almost_equal(np.diag(olp._array), 1.0)
def test_normalization_ccpvdz():
for number in xrange(1, 18+1):
check_normalization(number, 'cc-pvdz')
|
crisely09/horton
|
horton/gbasis/test/test_gobasis.py
|
Python
|
gpl-3.0
| 24,212
|
[
"Gaussian"
] |
89b47249cd1909b11758de80d5818675b8cbc8131478d11d164aec3670c1a282
|
#!/usr/bin/env python3
from .sht import sht, isht
from . import utils
from . import grids
# Try importing the plot module. This will fail if mayavi isn't installed.
# But requiring mayavi is too much overhead for the other sht modules. The plot
# module will work automatically if mayavi is installed.
# FIXME This creates a problem with scripts that need to import sht, but
# which are run on a machine that don't have access to an X-server. These
# scripts crash with "cannot connect to X server". We need to give scripts the
# option to not import the plot module. Until we figure out how to do that,
# this will be commented out.
#try:
# from . import plot
#except ImportError:
# pass
|
praveenv253/sht
|
sht/__init__.py
|
Python
|
mit
| 698
|
[
"Mayavi"
] |
622579b5426595dbd47a9797492521bbc96b378f9115379973edb165b4ee6fbf
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013 Canaima GNU/Linux
<desarrolladores@canaima.softwarelibre.gob.ve>
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
@author: Francisco Javier Vásquez Guerrero <franjvasquezg@gmail.com>
'''
import atk
def atk_acc(objeto, etiqueta):
'''
Este metodo es utilizado para relacionar una etiqueta a un objeto como \
por ejemplo Botones y Deslizadores etc.
'''
atk_obj = objeto.get_accessible()
atk_l = etiqueta.get_accessible()
relation_set = atk_l.ref_relation_set()
relation = atk.Relation((atk_obj,), atk.RELATION_LABEL_FOR)
relation_set.add(relation)
def atk_acc_vd(objeto, descrip):
'''
Metodo para asignar descripciones a objetos por ejemplo ventana de \
desplazamiento(gtk.ScrolledWindow) la descripción debe venir entre \
comillas simples
'''
atk_vd = objeto.get_accessible()
atk_vd.set_description(descrip)
def atk_label(etiqueta):
'''
Metodo para activar el foco de las etiquetas (gtk.label) de esta manera, \
orca las leerá
'''
etiqueta.set_selectable(True)
|
willicab/instalador
|
instalador/mod_accesible.py
|
Python
|
gpl-2.0
| 1,754
|
[
"ORCA"
] |
44c6a281eba9c15912cd7c94c0dc63fd1135a51469cd3ff1ffa92d4aafbb1ff0
|
"""Various tests for the Crystal class and its methods.
"""
import numpy as np
import pytest
from operator import mod
from itertools import product
from pydft.crystal import *
from pydft.bases.planewave import *
from numpy.fft import fftn, ifftn
def test_I_matrix():
"""Verify the I matrix acting on the N matrix is the same as the discrete
3D Fourier transform of N.
"""
LC = 1.
ndims = 3
axes = (0,1,2)
min_index = 2
max_index = 5
rs = [[LC,0,0], [LC,LC,0], [LC,LC,-LC]]
for r1 in rs:
R = makeR(r1)
# Place the origin at the center of the cell
origin = np.sum(R, 1)*1./2
for i,j,k in product(range(min_index, max_index+1),repeat=3):
S = [i,j,k]
crystal = Crystal(R, S, LC)
n = []
for ri in crystal._r:
n.append(gauss_charge_dist(ri, origin, 1))
Imat = np.exp(-1j*2*np.pi*np.dot(crystal._N/S,
np.transpose(crystal._M)))
In = np.dot(Imat, n)
n = np.reshape(n, S, order="F")
Infft = np.reshape(fftn(n), np.prod(S), order="F")
assert np.allclose(In, Infft) == True
# Make sure that the matrix and vector methods both work by comparing them.
LC = 1.
R = makeR([LC, 0., 0.])
S = [3,3,3]
crystal = Crystal(R,S,LC)
v = np.random.random_sample((27,3))
IvMatrix = I(crystal, v)
IvVectors = np.empty(np.shape(v))
for column in range(np.shape(v)[1]):
IvVectors[:,column] = I(crystal, v[:,column])
assert np.allclose(IvMatrix, IvVectors)
def test_g():
"""Assert the matrix returned by G_matrix passes a couple explicit
examples and has the expected properties.
"""
# Try two explicit cases.
LC1 = 1.
S1 = [2,2,2]
r1 = [LC1,0,0]
R1 = makeR(r1)
crystal1 = Crystal(R1, S1, LC1)
g(crystal1)
M1 = crystal1._M
N1 = crystal1._N
assert np.allclose(2*np.pi*N1, crystal1._g) == True
LC2 = 2.
S2 = [2,2,2]
r2 = [LC2,0,0]
R2 = makeR(r2)
crystal2 = Crystal(R2, S2, LC2)
g(crystal2)
M2 = crystal2._M
N2 = crystal2._N
assert np.allclose(np.pi*N2, crystal2._g) == True
# Check that various properites of G are satisfied.
c1 = [0]
c2 = [0, 1]
c3 = [0, 1, -1]
c4 = [0, 1, 2, -1]
c5 = [0, 1, 2, -2, -1]
c6 = [0, 1, 2, 3, -2, -1]
c7 = [0, 1, 2, 3, -3, -2, -1]
c8 = [0, 1, 2, 3, 4, -3, -2, -1]
c9 = [0, 1, 2, 3, 4, -4, -3, -2, -1]
columns = {1:c1, 2:c2, 3:c3, 4:c4, 5:c5, 6:c6, 7:c7, 8:c8, 9:c9}
min_index = 2
max_index = 6
# Verify the G matrix elements are correct by constructing it another
# way.
LC = 1.
rs = [[LC,0,0], [LC,LC,0], [LC,LC,-LC]]
for r1 in rs:
R = makeR(r1)
for i,j,k in product(range(min_index, max_index+1),repeat=3):
S = [i,j,k]
crystal = Crystal(R, S, LC)
M = crystal._M
N = crystal._N
G = crystal._G # Q
g(crystal) # G
gs = crystal._g
nc0 = np.array(columns[S[0]]*(S[1]*S[2]), dtype="int")
nc1 = np.array(list(np.repeat(columns[S[1]], S[0]))*S[2],
dtype="int")
nc2 = np.array(np.repeat(columns[S[2]], S[0]*S[1]), dtype="int")
N_test= np.transpose([nc0, nc1, nc2])
g_test = np.array([G[:,0]*i + G[:,1]*j + G[:,2]*k for i,j,k in N_test])
assert np.allclose(gs, g_test) == True
def test_L():
ss = range(2,10)
LC = 1.
rs = [[LC,0,0],[LC,LC,0],[LC,LC,-LC]]
for si in ss:
S = [si,si,si]
for ri in rs:
R = makeR(ri)
crystal = Crystal(R, S, LC)
g(crystal)
v = crystal._N[:,1] +np.random.random()
Lv = L(crystal, v)
for i in range(len(v)):
assert np.isclose(Lv[i],
-np.linalg.det(R)*
np.linalg.norm(crystal._g[i])**2*v[i]) ==True
# Make sure that the matrix and vector methods both work by comparing them.
LC = 1.
R = makeR([LC, 0., 0.])
S = [3,3,3]
crystal = Crystal(R,S,LC)
g(crystal)
v = np.random.random_sample((27,3))
LvMatrix = L(crystal, v)
LvVectors = np.empty(np.shape(v))
for column in range(np.shape(v)[1]):
LvVectors[:,column] = L(crystal, v[:,column])
assert np.allclose(LvMatrix, LvVectors)
def test_Linv():
ss = range(2,10)
LC = 1.
rs = [[LC,0,0],[LC,LC,0],[LC,LC,-LC]]
for si in ss:
S = [si,si,si]
for ri in rs:
R = makeR(ri)
crystal = Crystal(R, S, LC)
g(crystal)
v = crystal._N[:,1] +np.random.random()
Liv = Linv(crystal, v)
for i in range(len(v)):
if i == 0:
assert Liv[i] == 0.
else:
assert np.isclose(Liv[i],
-1./np.linalg.det(R)*
np.linalg.norm(crystal._g[i])**-2*v[i]) ==True
def test_HCI():
"""Verify the operators satisfy the identities that define the Hermitian
conjugate.
"""
# Vector case
LC = 1.
R = makeR([LC, 0., 0.])
S = [3,3,3]
crystal = Crystal(R,S,LC)
a = np.random.random_sample(27) + 1j*np.random.random_sample(27)
ad = np.conj(a)
b = np.random.random_sample(27) + 1j*np.random.random_sample(27)
bd = np.conj(b)
assert np.allclose(np.conj(np.dot(ad, I(crystal,b))),
np.dot(bd, Idag(crystal, a))) is True
assert np.allclose(np.conj(np.dot(ad, J(crystal,b))),
np.dot(bd, Jdag(crystal, a))) is True
# Matrix case
q = np.empty((27,3))
w = np.empty((27,3))
for column in range(np.shape(q)[1]):
q[:,column] = np.random.random_sample(np.shape(q)[0]) + (
1j*np.random.random_sample(np.shape(q)[0]))
w[:,column] = np.random.random_sample(np.shape(w)[0]) + (
1j*np.random.random_sample(np.shape(w)[0]))
qd = np.conj(q)
wd = np.conj(w)
for col in range(np.shape(q)[1]):
assert np.allclose(np.conj(np.dot(wd[:,col], I(crystal,q)[:,col])),
np.dot(qd[:,col], Idag(crystal, w)[:,col])) is True
assert np.allclose(np.conj(np.dot(wd[:,col], J(crystal,q)[:,col])),
np.dot(qd[:,col], Jdag(crystal, w)[:,col])) is True
|
jerjorg/dft
|
tests/planewave_tests.py
|
Python
|
gpl-3.0
| 6,585
|
[
"CRYSTAL"
] |
0bdc4d723eb341853b53182a6cb6a7979f4c9edee84c8cc5fc1be33457fd8768
|
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
# pylint: disable=too-many-branches,too-many-locals, invalid-name
from __future__ import (absolute_import, division, print_function)
from mantid.simpleapi import *
from mantid.kernel import *
from mantid.api import *
from scipy.io import netcdf
import numpy as np
import re
import time
class AngularAutoCorrelationsTwoAxes(PythonAlgorithm):
def category(self):
return "Simulation"
def summary(self):
return ("Calculates the angular auto-correlations of molecules in a simulation along two user-defined axes. "
"The first axis is defined by the vector connecting the average position of species two and the average position "
"of species one (user input). The second axis is perpendicular to axis 1 and is constructed by considering one "
"arbitrary atom of species 3 (user input). Timestep must be specified in femtoseconds.")
def PyInit(self):
self.declareProperty(FileProperty('InputFile','',action=FileAction.Load),doc="Input .nc file with an MMTK trajectory")
self.declareProperty("Timestep", "1.0", direction=Direction.Input,
doc="Time step between two coordinates in the trajectory in femtoseconds")
self.declareProperty("SpeciesOne",'',direction=Direction.Input,doc="Specify the first species, e.g. H, He, Li...")
self.declareProperty("SpeciesTwo",'',direction=Direction.Input,doc="Specify the second species, e.g. H, He, Li...")
self.declareProperty("SpeciesThree",'',direction=Direction.Input,doc="Specify the third species, e.g. H, He, Li...")
self.declareProperty(WorkspaceProperty('OutputWorkspace','',direction=Direction.Output),doc="Output workspace name")
self.declareProperty(WorkspaceProperty('OutputWorkspaceFT','FT',direction=Direction.Output),doc="FT Output workspace name")
def PyExec(self):
# Get file path
file_name=self.getPropertyValue("InputFile")
# Get the user-specified species
types=[self.getPropertyValue("SpeciesOne").lower(),
self.getPropertyValue("SpeciesTwo").lower(),
self.getPropertyValue("SpeciesThree").lower()]
# Load trajectory file
trajectory=netcdf.netcdf_file(file_name,mode="r")
logger.information("Loading particle id's, molecule id's and coordinate array...")
start_time=time.time()
# netcdf object containing the particle id numbers
description=(trajectory.variables["description"])[:]
# Convert description object to string via for loop. The original object has strange formatting
particleID = ''
for i in description:
particleID += i.decode('UTF-8')
# Extract particle id's from string using regular expressions
p_atoms=re.findall(r"A\('[a-z]+\d+',\d+", particleID)
# Split the string s by molecules
molecules=particleID.split("AC")
# Remove first item of molecule list (contains initialisation of variable 'description')
del molecules[0]
# Many-to-one structures. Identify the set of atomic species present (list structure 'elements')
# in the simulation and repackage particles into a dictionary 'particles_to_species' with structure id number -> species
atoms_to_species={}
species_to_atoms={}
elements=[]
# Populate the particles_to_species dictionary and the elements list
for j in p_atoms:
key=re.findall(r"',\d+",j)[0]
key=int(re.findall(r"\d+",key)[0])
element=re.findall(r"[a-z]+",j)[0]
if element not in elements:
elements.append(str(element))
atoms_to_species[key]=str(element)
# Check wether user-specified species present in the trajectory file
for i in range(3):
if types[i] not in elements:
raise RuntimeError('Species '+['one','two','three'][i]+' not found in the trajectory file. Please try again...')
# Initialise lists in the species_to_particles dictionary
for j in elements:
species_to_atoms[j]=[]
# Populate the species_to_particles dictionary
for j in p_atoms:
key=re.findall(r"',\d+",j)[0]
key=int(re.findall(r"\d+",key)[0])
element=re.findall(r"[a-z]+",j)[0]
species_to_atoms[element].append(key)
# Many-to-one structures. Assign atom indices to molecule indices using a dictionaries
# with structures atom id -> molecule id and molecule id -> list of atoms ids
atoms_to_molecules={}
molecules_to_atoms={}
# Initialise lists in the molecule_to_atom dictionary
for k in range(len(molecules)):
molecules_to_atoms[k]=[]
# Populate the dictionaries with atoms & molecules
for k in range(len(molecules)):
r_atoms=re.findall(r"A\('[a-z]+\d+',\d+",molecules[k])
for i in r_atoms:
key=re.findall(r"',\d+",i)[0]
key=int(re.findall(r"\d+",key)[0])
atoms_to_molecules[key]=k
molecules_to_atoms[k].append(key)
# Coordinate array. Shape: timesteps x (# of particles) x (# of spatial dimensions)
configuration=trajectory.variables["configuration"]
# Extract useful simulation parameters
# Number of species present in the simulation
# n_species=len(elements)
# Number of particles present in the simulation
n_particles=len(p_atoms)
# Number of molecules present in the simulation
n_molecules=len(molecules)
# Number of timesteps in the simulation
n_timesteps=int(configuration.shape[0])
# Number of spatial dimensions
n_dimensions=int(configuration.shape[2])
logger.information(str(time.time()-start_time) + " s")
logger.information("Transforming coordinates...")
start_time=time.time()
# Box size for each timestep. Shape: timesteps x (3 consecutive 3-vectors)
box_size=trajectory.variables["box_size"]
# Reshape the paralellepipeds into 3x3 tensors for coordinate transformations.
# Shape: (# of timesteps) x (3-vectors) x (# of spatial dimensions)
box_size_tensors=10.0*np.array([box_size[j].reshape((3,3)) for j in range(n_timesteps)])
# Extract box dimensions (assuming orthorhombic simulation cell, diagonal matrix)
box_size_x=np.array([box_size_tensors[i,0,0] for i in range(n_timesteps)])
box_size_y=np.array([box_size_tensors[i,1,1] for i in range(n_timesteps)])
box_size_z=np.array([box_size_tensors[i,2,2] for i in range(n_timesteps)])
# Copy the configuration object into a numpy array
configuration_copy=np.array([configuration[i] for i in range(n_timesteps)])
# Swap the time and particle axes
configuration_copy=np.swapaxes(configuration_copy,0,1)
# Transform particle trajectories (configuration array) to Cartesian coordinates at each time step.
cartesian_configuration=np.array([[np.dot(box_size_tensors[j],np.transpose(configuration_copy[i,j]))
for j in range(n_timesteps)] for i in range(n_particles)])
logger.information(str(time.time()-start_time) + " s")
logger.information("Calculating orientation vectors...")
start_time=time.time()
# Initialise orientation vector array. Shape: (# of molecules) x (# of timesteps) x (# of dimensions)
orientation_vectors1=np.zeros((n_molecules,n_timesteps,n_dimensions))
orientation_vectors2=np.zeros((n_molecules,n_timesteps,n_dimensions))
for i in range(n_molecules):
# Retrieve constituents of the ith molecule
temp=molecules_to_atoms[i]
# Find which constituents belong to species one, species two and species three
species_one=[]
species_two=[]
species_three=[]
for j in temp:
if atoms_to_species[j]==types[0]:
species_one.append(j)
if atoms_to_species[j]==types[1]:
species_two.append(j)
if atoms_to_species[j]==types[2]:
species_three.append(j)
# Find the average positions of species one and two
sum_position_species_one=np.zeros((n_timesteps,n_dimensions))
sum_position_species_two=np.zeros((n_timesteps,n_dimensions))
for k in species_one:
sum_position_species_one+=cartesian_configuration[k]
for l in species_two:
sum_position_species_two+=cartesian_configuration[l]
avg_position_species_one=1.0*sum_position_species_one/float(len(species_one))
avg_position_species_two=1.0*sum_position_species_two/float(len(species_two))
# Choose the 1st element of species_three to build the 2nd vector
position_species_three=1.0*cartesian_configuration[species_three[0]]
# Find the vectors connecting average positions of species one and species two
vectors1=avg_position_species_two-avg_position_species_one
# Find the vector to the third atom
vectors2=position_species_three-avg_position_species_two
diffX1=np.divide(vectors1[:,0],box_size_x)
diffY1=np.divide(vectors1[:,1],box_size_y)
diffZ1=np.divide(vectors1[:,2],box_size_z)
diffX2=np.divide(vectors2[:,0],box_size_x)
diffY2=np.divide(vectors2[:,1],box_size_y)
diffZ2=np.divide(vectors2[:,2],box_size_z)
# Wrapping the vectors
vectorX1=np.array([(diffX1[k]-round(diffX1[k]))*box_size_x[k] for k in range(n_timesteps)])
vectorY1=np.array([(diffY1[k]-round(diffY1[k]))*box_size_y[k] for k in range(n_timesteps)])
vectorZ1=np.array([(diffZ1[k]-round(diffZ1[k]))*box_size_z[k] for k in range(n_timesteps)])
vectorX2=np.array([(diffX2[k]-round(diffX2[k]))*box_size_x[k] for k in range(n_timesteps)])
vectorY2=np.array([(diffY2[k]-round(diffY2[k]))*box_size_y[k] for k in range(n_timesteps)])
vectorZ2=np.array([(diffZ2[k]-round(diffZ2[k]))*box_size_z[k] for k in range(n_timesteps)])
# Normalisation
norm1=np.sqrt(vectorX1*vectorX1+vectorY1*vectorY1+vectorZ1*vectorZ1)
vectorX1=np.divide(vectorX1,norm1)
vectorY1=np.divide(vectorY1,norm1)
vectorZ1=np.divide(vectorZ1,norm1)
norm2=np.sqrt(vectorX2*vectorX2+vectorY2*vectorY2+vectorZ2*vectorZ2)
vectorX2=np.divide(vectorX2,norm2)
vectorY2=np.divide(vectorY2,norm2)
vectorZ2=np.divide(vectorZ2,norm2)
# Dot product
cosine=np.multiply(vectorX1,vectorX2)+np.multiply(vectorY1,vectorY2)+np.multiply(vectorZ1,vectorZ2)
# Gram-Schmidt orthogonalisation process
vectorX2=vectorX2-np.divide(vectorX1,cosine)
vectorY2=vectorY2-np.divide(vectorY1,cosine)
vectorZ2=vectorZ2-np.divide(vectorZ1,cosine)
# Renormalisation of the 2nd vector
norm2=np.sqrt(vectorX2*vectorX2+vectorY2*vectorY2+vectorZ2*vectorZ2)
vectorX2=np.divide(vectorX2,norm2)
vectorY2=np.divide(vectorY2,norm2)
vectorZ2=np.divide(vectorZ2,norm2)
# Store calculations in the orientation_vectors1 and orientation_vectors2 arrays
orientation_vectors1[i]=np.swapaxes(np.array([vectorX1,vectorY1,vectorZ1]),0,1)
orientation_vectors2[i]=np.swapaxes(np.array([vectorX2,vectorY2,vectorZ2]),0,1)
logger.information(str(time.time()-start_time) + " s")
logger.information("Calculating angular auto-correlations...")
start_time=time.time()
# First axis
R_avg_axis1=np.zeros(n_timesteps)
for i in range(n_molecules):
R_avg_axis1+=self.auto_correlation(orientation_vectors1[i])
R_avg_axis1=1.0*R_avg_axis1/n_molecules
# Second axis
R_avg_axis2=np.zeros(n_timesteps)
for i in range(n_molecules):
R_avg_axis2+=self.auto_correlation(orientation_vectors2[i])
R_avg_axis2=1.0*R_avg_axis2/n_molecules
logger.information(str(time.time()-start_time)+" s")
# Initialise & populate the output_ws workspace
nrows=2
step=float(self.getPropertyValue("Timestep"))
xvals=np.arange(0,np.ceil((n_timesteps)/2.0))*step/1000.0
yvals=np.empty(0)
yvals=np.append(yvals,self.fold_correlation(R_avg_axis1))
yvals=np.append(yvals,self.fold_correlation(R_avg_axis2))
evals=np.zeros(np.shape(yvals))
output_name=self.getPropertyValue("OutputWorkspace")
output_ws=CreateWorkspace(OutputWorkspace=output_name,DataX=xvals,UnitX="ps",DataY=yvals,
DataE=evals,NSpec=nrows,VerticalAxisUnit="Text",VerticalAxisValues=["Axis 1","Axis 2"])
# Set output workspace to output_ws
self.setProperty('OutputWorkspace',output_ws)
# Fourier transform output to workspace
nrows=2
yvals=np.empty(0)
yvals=np.append(yvals,np.fft.rfft(R_avg_axis1))
yvals=np.append(yvals,np.fft.rfft(R_avg_axis2))
evals=np.zeros(np.shape(yvals))
xvals=np.arange(0,np.shape(yvals)[0])
FT_output_name=self.getPropertyValue("OutputWorkspaceFT")
FT_output_ws=CreateWorkspace(OutputWorkspace=FT_output_name,DataX=xvals,UnitX="1/fs",DataY=yvals,
DataE=evals,NSpec=nrows,VerticalAxisUnit="Text",VerticalAxisValues=["FT Axis 1","FT Axis 2"])
self.setProperty("OutputWorkspaceFT",FT_output_ws)
def auto_correlation(self, vector):
# Returns angular auto-correlation of a normalised time-dependent 3-vector
num=np.shape(vector)[0]
norm=np.arange(np.ceil(num/2.0),num+1)
norm=np.append(norm,(np.arange(int(num/2)+1,num)[::-1]))
# x dimension
autoCorr=np.divide(np.correlate(vector[:,0],vector[:,0],"same"),norm)
# y dimension
autoCorr+=np.divide(np.correlate(vector[:,1],vector[:,1],"same"),norm)
# z dimension
autoCorr+=np.divide(np.correlate(vector[:,2],vector[:,2],"same"),norm)
return autoCorr
def fold_correlation(self,omega):
# Folds an array with symmetrical values into half by averaging values around the centre
right_half=omega[int(len(omega))//2:]
left_half=omega[:int(np.ceil(len(omega)/2.0))][::-1]
return (left_half+right_half)/2.0
# Subscribe algorithm to Mantid software
AlgorithmFactory.subscribe(AngularAutoCorrelationsTwoAxes)
|
mganeva/mantid
|
Framework/PythonInterface/plugins/algorithms/AngularAutoCorrelationsTwoAxes.py
|
Python
|
gpl-3.0
| 15,116
|
[
"NetCDF"
] |
eebf0a3cdc5486d22fdd710f74154de99cdca5b5ad2ef3be632ed9b6d7d2fd56
|
import scipy.io
import numpy as np
from scipy.spatial.distance import pdist, squareform, cdist
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from numpy.linalg import inv, norm
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
#Assignment 1 (a): Plotting the kernel function
#Gaussian kernel
s = 0.1
Xv = np.linspace(0,1,100)
Yv = np.linspace(0,1,100)
Xv, Yv = np.meshgrid(Xv,Yv)
#Calculate the kernel matrix by calculating pairwise distances
gaussian_kernel = scipy.exp(-(Yv-Xv)** 2 / s ** 2)
sigmoid_kernel = np.tanh(Xv*Yv)
print gaussian_kernel.shape
plt.figure()
plt.pcolor(Xv, Yv, gaussian_kernel, cmap=plt.cm.coolwarm)
plt.colorbar()
plt.title('Gaussian Kernel Matrix')
plt.figure()
plt.pcolor(Xv, Yv, sigmoid_kernel, cmap=plt.cm.coolwarm)
plt.colorbar()
plt.title('Sigmoid Kernel Matrix')
plt.show()
|
RationalAsh/pattern_recognition_assignments
|
assignment-1/python_sol-1a.py
|
Python
|
mit
| 878
|
[
"Gaussian"
] |
a7452461f4442ea2c0aa90f26f22abcc341fe6b343655688526883830c615d9d
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 Michael Hull.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------
from morphforge.simulation.neuron.objects import NEURONCell
from morphforge.simulation.neuron.core.neuronsimulation import NEURONSimulation
from morphforge.simulation.neuron.core.neuronsimulationsettings import NEURONSimulationSettings
|
mikehulluk/morphforge
|
src/morphforge/simulation/neuron/core/__init__.py
|
Python
|
bsd-2-clause
| 1,777
|
[
"NEURON"
] |
6320c9dedda7759e3d90295f39d2e75af50c153b1339819859a8ed610e2e2a51
|
#!/usr/bin/python
#
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
# Avi Version: 17.1.1
#
# Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: avi_networksecuritypolicy
author: Gaurav Rastogi (grastogi@avinetworks.com)
short_description: Module for setup of NetworkSecurityPolicy Avi RESTful Object
description:
- This module is used to configure NetworkSecurityPolicy object
- more examples at U(https://github.com/avinetworks/devops)
requirements: [ avisdk ]
version_added: "2.4"
options:
state:
description:
- The state that should be applied on the entity.
default: present
choices: ["absent", "present"]
avi_api_update_method:
description:
- Default method for object update is HTTP PUT.
- Setting to patch will override that behavior to use HTTP PATCH.
version_added: "2.5"
default: put
choices: ["put", "patch"]
avi_api_patch_op:
description:
- Patch operation to use when using avi_api_update_method as patch.
version_added: "2.5"
choices: ["add", "replace", "delete"]
cloud_config_cksum:
description:
- Checksum of cloud configuration for network sec policy.
- Internally set by cloud connector.
created_by:
description:
- Creator name.
description:
description:
- User defined description for the object.
name:
description:
- Name of the object.
rules:
description:
- List of networksecurityrule.
tenant_ref:
description:
- It is a reference to an object of type tenant.
url:
description:
- Avi controller URL of the object.
uuid:
description:
- Unique object identifier of the object.
extends_documentation_fragment:
- avi
'''
EXAMPLES = """
- name: Create a network security policy to block clients represented by ip group known_attackers
avi_networksecuritypolicy:
controller: '{{ controller }}'
username: '{{ username }}'
password: '{{ password }}'
name: vs-gurutest-ns
rules:
- action: NETWORK_SECURITY_POLICY_ACTION_TYPE_DENY
age: 0
enable: true
index: 1
log: false
match:
client_ip:
group_refs:
- Demo:known_attackers
match_criteria: IS_IN
name: Rule 1
tenant_ref: Demo
"""
RETURN = '''
obj:
description: NetworkSecurityPolicy (api/networksecuritypolicy) object
returned: success, changed
type: dict
'''
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.network.avi.avi import (
avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ImportError:
HAS_AVI = False
def main():
argument_specs = dict(
state=dict(default='present',
choices=['absent', 'present']),
avi_api_update_method=dict(default='put',
choices=['put', 'patch']),
avi_api_patch_op=dict(choices=['add', 'replace', 'delete']),
cloud_config_cksum=dict(type='str',),
created_by=dict(type='str',),
description=dict(type='str',),
name=dict(type='str',),
rules=dict(type='list',),
tenant_ref=dict(type='str',),
url=dict(type='str',),
uuid=dict(type='str',),
)
argument_specs.update(avi_common_argument_spec())
module = AnsibleModule(
argument_spec=argument_specs, supports_check_mode=True)
if not HAS_AVI:
return module.fail_json(msg=(
'Avi python API SDK (avisdk>=17.1) is not installed. '
'For more details visit https://github.com/avinetworks/sdk.'))
return avi_ansible_api(module, 'networksecuritypolicy',
set([]))
if __name__ == '__main__':
main()
|
alexlo03/ansible
|
lib/ansible/modules/network/avi/avi_networksecuritypolicy.py
|
Python
|
gpl-3.0
| 4,303
|
[
"VisIt"
] |
efafd5b7bed4819b604d18805fe377259c4678f08d432c650a561e61c6b5e470
|
#!/usr/bin/env python
'''
GOAL:
- read catalog of spirals that is generated by LCSmergespiralscats.py
- make plots for paper
- run correlation/KS tests
- print latex tables with resulting KS statistics. these are written to SamplePlots directory
USAGE:
- in ipython
%run LCSanalysespirals.py
- all spirals are s.XXX
- sample that does not include coma is nc.XXX
- Example commands from w/in ipython:
s.compare_color()
nc.compare_color()
- To generate latex tables with KS statistics:
print_tables()
print_tables_nc()
- latex tables with resulting KS statistics are written to SamplePlots directory
- file ks.tex in ~/Dropbox/Research/MyPapers/LCSpaper1 merges all tables into one latex file
- to compile, in LCSpaper1 directory, type
> pdflatex ks
REQUIRED MODULES:
- mystuff.py
- astropy.py
- LCScommon
**************************
written by Rose A. Finn
Jan 2014
**************************
'''
from LCScommon import *
import pylab as pl
import numpy as np
import os
import mystuff as my
from astropy.io import fits
from astropy.table import Table
from astropy.table import Column
from astropy.cosmology import WMAP9 as cosmo
import astrofuncs
import chary_elbaz_24um as chary
import anderson
from scipy.stats import scoreatpercentile
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from matplotlib.mlab import PCA as mlabPCA
from scipy.optimize import leastsq
minsize_kpc=1.3 # one mips pixel at distance of hercules
#minsize_kpc=2*minsize_kpc
minmass=9.5 #log of M*
mstarmin=9.3
mstarmax=11
ssfrmin=-12.
ssfrmax=-9
spiralcut=0.8
truncation_ratio=0.5
field=.68
colors=['r','b','c','g','m','y','k','r','0.5']
shapes=['o','*','p','d','s','^','>','<','v']
truncated=array([113107,140175,79360,79394,79551,79545,82185,166185,166687,162832,146659,99508,170903,18236,43796,43817,43821,70634,104038,104181],'i')
# figure setup
plotsize_single=(6.8,5)
plotsize_2panel=(10,5)
params = {'backend': 'ps',
'axes.labelsize': 24,
'text.fontsize': 20,
'legend.fontsize': 12,
'xtick.labelsize': 14,
'ytick.labelsize': 14,
#'figure.titlesize': 20,
'text.usetex': False,
'figure.figsize': plotsize_single}
pl.rcParams.update(params)
def pair(data, labels=None,norm=True,scale=True,namesAlongDiagonal=True,showTicks=False):
""" Generate something similar to R `pair` """
nVariables = data.shape[1]
if labels is None:
labels = ['var%d'%i for i in range(nVariables)]
fig = pl.figure()
if not(namesAlongDiagonal):
fig.subplots_adjust(left=.2)
for i in range(nVariables):
for j in range(nVariables):
nSub = i * nVariables + j + 1
ax = fig.add_subplot(nVariables, nVariables, nSub)
if not(showTicks):
if i != (nVariables - 1):
ax.set_xticks([])
if j != 0:
ax.set_yticks([])
if not(namesAlongDiagonal):
if i == 0:
ax.set_title(labels[j])
if j == 0:
ax.text(-.4,.5,labels[i],transform=ax.transAxes,horizontalalignment='right')
if i == j:
if namesAlongDiagonal:
ax.text(.5,.5,labels[i],transform=ax.transAxes,horizontalalignment='center',verticalalignment='center')
else:
if i == j:
ax.hist(data[:,i],color='0.5',normed=True)
else:
if norm & scale:
ax.plot((data[:,j]-np.mean(data[:,j]))/np.std(data[:,j]), (data[:,i]-np.mean(data[:,i]))/np.std(data[:,i]), '.k')
elif norm & ~scale:
ax.plot(data[:,j]-np.mean(data[:,j]), data[:,i]-np.mean(data[:,i]), '.k')
else:
ax.plot(data[:,j], data[:,i], '.k')
return fig
def comparedata(rdata, cdata,rlabels=None,clabels=None,norm=False,scale=False,showTicks=True):
""" Generate something similar to R `pair` """
nrows = rdata.shape[1]
ncols = cdata.shape[1]
if rlabels is None:
rlabels = ['var%d'%i for i in range(nrows)]
if clabels is None:
clabels = ['var%d'%i for i in range(ncols)]
fig = pl.figure()
for i in range(nrows):
for j in range(ncols):
nSub = i * ncols + j + 1
ax = fig.add_subplot(nrows, ncols, nSub)
if not(showTicks):
if i != (nrows - 1):
ax.set_xticks([])
if j != 0:
ax.set_yticks([])
if i == (nrows-1):
ax.set_xlabel(clabels[j])
if j == 0:
ax.set_ylabel(rlabels[i])
if norm & scale:
ax.plot((cdata[:,j]-np.mean(cdata[:,j]))/np.std(cdata[:,j]), (rdata[:,i]-np.mean(rdata[:,i]))/np.std(rdata[:,i]), '.k')
elif norm & ~scale:
ax.plot(cdata[:,j]-np.mean(cdata[:,j]), rdata[:,i]-np.mean(rdata[:,i]), '.k')
else:
ax.plot(cdata[:,j], rdata[:,i], '.k')
return fig
def pairs(data, names):
"Quick&dirty scatterplot matrix"
d = len(data)
fig, paxes = subplots(nrows=d, ncols=d, sharex='col', sharey='row')
print paxes.size
for i in range(d):
for j in range(d):
ax = paxes[i,j]
#subplot(d,d,i+j+1)
if i == j:
ax.text(0.5, 0.5, names[i], transform=ax.transAxes,
horizontalalignment='center', verticalalignment='center',
fontsize=16)
else:
print 'plotting data!'
ax.scatter(np.array(data[j]), np.array(data[i]))
#ax.axhline(y=0)
#ax.axvline(x=0)
#show()
ax.axis([min(data[j]),max(data[j]),min(data[i]),max(data[i])])
#print i,j,data[j]
#print i,j,data[i]
#ax.plot(data[j],data[i],'k.')
#figure()
#plot(data[j],data[i],'bo')
def fit_intercept(x,y):
fitfunc = lambda intercept, x: x + intercept
errfunc = lambda intercept, x, y: fitfunc(intercept,x)-y
p1,success = leastsq(errfunc,0, args = (x,y))
return p1
def fit_slope(x,y,yerr=None,yerrflag=0):
fitfunc = lambda p1, x: p1*x
if yerrflag:
errfunc = lambda p1, x, y: (fitfunc(p1,x)-y)/yerr
else:
errfunc = lambda p1, x, y: fitfunc(p1,x)-y
p2,success = leastsq(errfunc,.7, args = (x,y))
return p2
def calculate_sfsb(redshift,sbcutobs=20.):
'''
calculate the limiting sfr/kpc^2 from the surface brightness cut in mag/sq arcsec
'''
flux_zp_AB = 3631.
flux = flux_zp_AB*10.**(-1.*sbcutobs/2.5)
# convert to micro-Jy when sending to chary-elbaz
lircut,sfrcut=chary.chary_elbaz_24um(redshift,flux*1.e6)
# get arcsec -> kpc conversion
# DA returns kpc/arcsec
da= cosmo.angular_diameter_distance(redshift).value*Mpcrad_kpcarcsec
sfrsb=sfrcut/da**2
lirsb=lircut/da**2
return sfrsb,lirsb
class ellipticals():
def __init__(self):
hdulist=fits.open(homedir+'research/LocalClusters/NSAmastertables/LCS_notSpirals_all.fits')
self.s=hdulist[1].data
hdulist.close()
# convert flags to boolean
self.AGNKAUFF=self.s['AGNKAUFF'] & (self.s.HAEW > 0.)
self.AGNKEWLEY=self.s['AGNKEWLEY']& (self.s.HAEW > 0.)
self.AGNSTASIN=self.s['AGNSTASIN']& (self.s.HAEW > 0.)
self.gim2dflag=self.s['matchflag']
self.cnumerical_error_flag24=self.s['cnumerical_error_flag24']
self.fcnumerical_error_flag24=self.s['fcnumerical_error_flag24']
self.mipsflag=self.s.MATCHFLAG24 == 1.
class spirals():
def __init__(self,infile,usecoma=True,useherc=True,onlycoma=False,prefix='all'):
self.prefix=prefix
hdulist=fits.open(homedir+'research/LocalClusters/NSAmastertables/LCS_Spirals_all_fsps_v2.4_miles_chab_charlot_sfhgrid01.fits')
self.jmass=hdulist[1].data
hdulist.close()
# use jmass.mstar_50 and jmass.mstar_err
hdulist=fits.open(homedir+'research/LocalClusters/NSAmastertables/LCS_Spirals_isorad.fits')
self.isorad=hdulist[1].data
hdulist.close()
hdulist=fits.open(homedir+'research/LocalClusters/NSAmastertables/LCS_Spirals_AGC.fits')
self.agc=hdulist[1].data
hdulist.close()
hdulist=fits.open(infile)
self.s=hdulist[1].data
cols=self.s.columns
cnames=cols.names
hdulist.close()
self.logstellarmassTaylor=1.15+0.70*(self.s.ABSMAG[:,3]-self.s.ABSMAG[:,5]) -0.4*(self.s.ABSMAG[:,5]+ 5.*log10(h))
bad_imag=self.logstellarmassTaylor < 5.
newi=(self.s.ABSMAG[:,4]+self.s.ABSMAG[:,6])/2.
#print len(newi)
self.logstellarmassTaylor[bad_imag]=1.15+0.70*(self.s.ABSMAG[:,3][bad_imag]-newi[bad_imag]) -0.4*(newi[bad_imag]+ 5.*log10(h))
if usecoma == False:
self.s=self.s[self.s.CLUSTER != 'Coma']
try:
self.jmass=self.jmass[self.s.CLUSTER != 'Coma']
self.isorad=self.isorad[self.s.CLUSTER != 'Coma']
self.agc=self.agc[self.s.CLUSTER != 'Coma']
except:
print 'WARNING: problem matching to moustakas MSTAR_50 - probably ok'
#self.agnflag=self.agnflag[self.s.CLUSTER != 'Coma']
self.logstellarmassTaylor=self.logstellarmassTaylor[self.s.CLUSTER != 'Coma']
self.comaflag=False
if onlycoma == True:
self.s=self.s[self.s.CLUSTER == 'Coma']
#self.jmass=self.jmass[self.s.CLUSTER == 'Coma']
#self.isorad=self.isorad[self.s.CLUSTER == 'Coma']
#self.agc=self.agc[self.s.CLUSTER == 'Coma']
if useherc == False:
self.s=self.s[self.s.CLUSTER != 'Hercules']
#self.jmass=self.jmass[self.s.CLUSTER != 'Hercules']
#self.isorad=self.isorad[self.s.CLUSTER != 'Hercules']
#self.agc=self.agc[self.s.CLUSTER != 'Hercules']
self.logstellarmassTaylor=self.logstellarmassTaylor[self.s.CLUSTER != 'Hercules']
self.AGNKAUFF=self.s['AGNKAUFF']
self.AGNKEWLEY=self.s['AGNKEWLEY']
self.AGNSTASIN=self.s['AGNSTASIN']
self.AGNKAUFF=self.s['AGNKAUFF'] & (self.s.HAEW > 0.)
self.AGNKEWLEY=self.s['AGNKEWLEY']& (self.s.HAEW > 0.)
self.AGNSTASIN=self.s['AGNSTASIN']& (self.s.HAEW > 0.)
self.cnumerical_error_flag24=self.s['fnumerical_error_flag24']
self.fcnumerical_error_flag24=self.s['fcnumerical_error_flag24']
self.AGNKAUFF= ((log10(self.s.O3FLUX/self.s.HBFLUX) > (.61/(log10(self.s.N2FLUX/self.s.HAFLUX)-.05)+1.3)) | (log10(self.s.N2FLUX/self.s.HAFLUX) > 0.))
#y=(.61/(x-.47)+1.19)
self.AGNKEWLEY= ((log10(self.s.O3FLUX/self.s.HBFLUX) > (.61/(log10(self.s.N2FLUX/self.s.HAFLUX)-.47)+1.19)) | (log10(self.s.N2FLUX/self.s.HAFLUX) > 0.3))
self.upperlimit=self.s['RE_UPPERLIMIT'] # converts this to proper boolean array
self.pointsource=self.s['POINTSOURCE'] # converts this to proper boolean array
self.gim2dflag=self.s['matchflag']
self.zooflag=self.s['match_flag']
self.nerrorflag=self.s['fcnumerical_error_flag24']
# convert flags to boolean arrays
for col in cnames:
if (col.find('flag') > -1) | (col.find('AGN') > -1):
#print col
self.s.field(col)[:]=np.array(self.s[col],'bool')
self.nsadict=dict((a,b) for a,b in zip(self.s.NSAID,arange(len(self.s.NSAID))))
self.logstellarmass = self.s.MSTAR_50 # self.logstellarmassTaylor # or
#self.logstellarmass = self.logstellarmassTaylor # or
#self.define_supersize()
# calculating magnitudes from fluxes provided from NSA
#
# m = 22.5 - 2.5 log_10 (flux_nanomaggies)
# from http://www.sdss3.org/dr8/algorithms/magnitudes.php#nmgy
self.nsamag=22.5-2.5*log10(self.s.NMGY)
self.badfits=zeros(len(self.s.RA),'bool')
#badfits=array([166134, 166185, 103789, 104181],'i')'
nearbystar=[142655, 143485, 99840, 80878] # bad NSA fit; 24um is ok
nearbygalaxy=[103927,143485,146607, 166638,99877,103933,99056]#,140197] # either NSA or 24um fit is unreliable
badNSA=[166185,142655,99644,103825,145998]
badfits=badNSA + nearbygalaxy#+nearbystar+nearbygalaxy
badfits=array(badfits,'i')
for gal in badfits:
self.badfits[where(self.s.NSAID == gal)] = 1
self.sdssspecflag=(self.s.ISDSS > -1)
self.emissionflag=((self.s.HAFLUX != 0.) & (self.s.HAFLUX != -9999.) & (self.s.N2FLUX != 0.)) | self.sdssspecflag
self.alfalfaflag=(self.s.IALFALFA > -1)
self.mipsflag=(self.s.LIR_ZDIST > 0.)
self.mipsflag=(self.s.FLUX_RADIUS1 > 0.)
self.wiseflag = (self.s.W1FLG_3 < 2) & (self.s.W2FLG_3 < 2) & (self.s.W3FLG_3 < 2) & (self.s.W4FLG_3 < 2)
# this allows for source confusion and the presence of some bad pixels within the aperture.
self.wiseagn=(self.s.W1MAG_3 - self.s.W2MAG_3) > 0.8
self.agnflag = self.AGNKAUFF | self.wiseagn
#self.agnkauff=self.s.AGNKAUFF > .1
#self.agnkewley=self.s.AGNKEWLEY > .1
#self.agnstasin=self.s.AGNSTASIN > .1
self.dv = (self.s.ZDIST - self.s.CLUSTER_REDSHIFT)*3.e5/self.s.CLUSTER_SIGMA
self.dvflag = abs(self.dv) < 3.
#self.agnflag = self.agnkauff
#self.galfitflag=(self.s.galfitflag > .1) #| (self.s.fcmag1 < .1)
#self.galfitflag[(self.s.fcmag1 < .1)]=zeros(sum(self.s.fcmag1<.1))
#self.agnflag = self.s.agnflag > .1
#self.zooflag = self.s.match_flag > .1
# self.gim2dflag = self.s.matchflag > .1
self.membflag = (self.s.DR_R200 < 1.) & (abs(self.dv) < 3.)
#self.membflag = abs(self.dv) < (-1.25*self.s.DR_R200 + 1.5)
#self.nearfieldflag = (self.s.DR_R200 > 1.) & (abs(self.dv) < 3.)
self.nearfieldflag = ~self.membflag & (abs(self.dv) < 3.)
self.fieldflag = (abs(self.dv) > 3.)
#environmental zones
self.zone1=(self.s.DR_R200 < .5) & (abs(self.dv) < 3.)
self.zone2=(self.s.DR_R200 > .5) & (self.s.DR_R200 < 1) & (abs(self.dv) < 3.)
self.zone3=(self.s.DR_R200 > 1) & (abs(self.dv) < 3.)
self.zone4= (abs(self.dv) > 3.)
self.HIflag = self.s.HIMASS > 0.
self.sumagnflag=self.s.AGNKAUFF + self.s.AGNKEWLEY + self.s.AGNSTASIN
self.da=zeros(len(self.s.ZDIST),'f')
q=.2
baflag=self.s.SERSIC_BA < q
self.incl=arccos(sqrt((self.s.SERSIC_BA**2-q**2)/(1.-q**2)))*(~baflag)+baflag*pi/2. # in radians
# correct for inclination
#self.isorad.NSA=self.isorad.NSA*cos(self.incl)
#self.isorad.MIPS=self.isorad.MIPS*cos(self.incl)
self.mag24=23.9-2.5*log10(self.s.FLUX24)
self.NUV24color=(self.nsamag[:,2])-self.mag24
self.mag24se=18.526-2.5*log10(self.s.SE_FLUX_AUTO)
#self.gi_corr=(self.nsamag[:,3]-self.nsamag[:,5])-(.17*(1-cos(self.incl))*((self.jmass.MSTAR_50)-8.19))
self.gi_corr=(self.nsamag[:,3]-self.nsamag[:,5])-(.17*(1-cos(self.incl))*((self.logstellarmass)-8.19))
for i in range(len(self.s.ZDIST)):
self.da[i] = cosmo.angular_diameter_distance(self.s.ZDIST[i]).value
self.da=cosmo.angular_diameter_distance(self.s.ZDIST).value*Mpcrad_kpcarcsec # kpc/arcsec
self.spiralflag=(self.s.p_cs > spiralcut) #| (self.s.p_cs == 0)
for c in clusternames:
if (c == 'Coma') & (usecoma == False):
continue
else:
for id in spiral_100_nozoo[c]:
try:
self.spiralflag[self.nsadict[id]]=1
except:
print 'did not find ',id
self.dist3d=sqrt((self.dv-3.)**2 + (self.s.DR_R200)**2)
self.sb_obs=zeros(len(self.s.RA))
flag= (~self.s['fcnumerical_error_flag24'])
self.sb_obs[flag]=self.s.fcmag1[flag] + 2.5*log10(pi*((self.s.fcre1[flag]*mipspixelscale)**2)*self.s.fcaxisratio1[flag])
self.DA=zeros(len(self.s.SERSIC_TH50))
for i in range(len(self.DA)):
if self.membflag[i]:
self.DA[i] = cosmo.angular_diameter_distance(self.s.CLUSTER_REDSHIFT[i]).value*Mpcrad_kpcarcsec
else:
self.DA[i] = cosmo.angular_diameter_distance(self.s.ZDIST[i]).value*Mpcrad_kpcarcsec
self.sizeflag=(self.s.SERSIC_TH50*self.DA > minsize_kpc) #& (self.s.SERSIC_TH50 < 20.)
self.massflag=self.logstellarmass > minmass
self.lirflag=(self.s.LIR_ZDIST > 5.e8)
self.galfitflag = (self.s.fcmag1 > .1) & (self.sb_obs < 20.) & ~self.nerrorflag #& (self.s.SIZE_RATIOERR < .2)
self.sbflag=self.sb_obs < 20.
self.sfsampleflag = self.sizeflag & self.massflag & self.lirflag & ~self.badfits
self.ur=self.s.ABSMAG[:,2]-self.s.ABSMAG[:,4]
self.redflag=(self.ur > 2.3)
self.greenflag=(self.ur > 1.8) & (self.ur < 2.3)
self.blueflag=(self.ur<1.8)
self.NUVr=self.s.ABSMAG[:,1] - self.s.ABSMAG[:,4]
self.blueflag2=self.NUVr < 4.1
# add galaxies with blue u-r colors but no galex data
self.blue_nogalex = (self.s.NMGY[:,1] == 0.) & (self.blueflag)
self.blueflag2[self.blue_nogalex] = np.ones(sum(self.blue_nogalex))
self.sampleflag = self.galfitflag & self.sizeflag & self.massflag & self.lirflag & ~self.badfits #& self.blueflag2
self.bluesampleflag = self.sampleflag & self.blueflag2
self.unknownagn= self.sizeflag & self.massflag & self.lirflag & ~self.emissionflag & ~self.wiseflag
self.virialflag = self.dv < (1.5-1.25*self.s.DR_R200)
self.limitedsample=self.sampleflag & (self.logstellarmass > 9.5) & (self.logstellarmass < 10.2) & self.gim2dflag & (self.s.B_T_r < 0.2) & self.dvflag
self.c90=self.s.FLUX_RADIUS2/self.s.fcre1
self.size_ratio_corr=self.s.SIZE_RATIO*(self.s.faxisratio1/self.s.SERSIC_BA)
self.truncflag=(self.s.SIZE_RATIO < 0.45) & self.sampleflag & ~self.agnflag
self.dL = self.s.ZDIST*3.e5/H0
self.distmod=25.+5.*log10(self.dL)
#best_distance=self.membflag * self.cdMpc + ~self.membflag*(self.n.ZDIST*3.e5/H0)
self.LIR_BEST = self.s.LIR_ZCLUST * self.membflag + ~self.membflag*(self.s.LIR_ZDIST)
self.SFR_BEST = self.s.SFR_ZCLUST * np.array(self.dvflag,'i') + np.array(~self.dvflag,'i')*(self.s.SFR_ZDIST)
self.ssfr=self.SFR_BEST/(10.**(self.logstellarmass))
self.ssfrerr=self.SFR_BEST/(10.**(self.logstellarmass))*(self.s.FLUX24ERR/self.s.FLUX24)
self.ssfrms=np.log10(self.ssfr*1.e9/.08)
self.sigma_ir=np.zeros(len(self.LIR_BEST),'d')
self.sigma_irerr=np.zeros(len(self.LIR_BEST),'d')
self.sigma_irerr[self.galfitflag]= np.sqrt(((self.LIR_BEST[self.galfitflag]*self.s.FLUX24ERR[self.galfitflag]/self.s.FLUX24ERR[self.galfitflag])/2/(np.pi*(self.s.fcre1[self.galfitflag]*self.DA[self.galfitflag])**2))**2+(2.*self.LIR_BEST[self.galfitflag]/2/(np.pi*(self.s.fcre1[self.galfitflag]*self.DA[self.galfitflag])**3)*self.s.fcre1err[self.galfitflag])**2)
self.sigma_ir[self.galfitflag]= self.LIR_BEST[self.galfitflag]/2/(np.pi*(self.s.fcre1[self.galfitflag]*self.DA[self.galfitflag])**2)
self.starburst = (self.ssfr*1.e9 > .16)
self.compact_starburst = (self.ssfr*1.e9 > .16) & (self.sigma_ir > 5.e9)
if usecoma == True:
n2ha=log10(self.s.N2FLUX/self.s.HAFLUX)
o3hb=log10(self.s.O3FLUX/self.s.HBFLUX)
flag=(self.sampleflag & self.dvflag & self.gim2dflag & (self.s.B_T_r == self.s.B_T_r) & (n2ha == n2ha) & (o3hb == o3hb) & (self.s.SIZE_RATIO < 4.) & (self.s.SIZE_RATIOERR < 0.3)) & ~self.agnflag & self.sdssspecflag & self.zooflag #& self.HIflag
pcaoutput=zeros([sum(flag),18])
pcaoutput[:,0]=self.s.SIZE_RATIO[flag]
pcaoutput[:,1]=self.logstellarmass[flag]
pcaoutput[:,2]=self.s.DR_R200[flag]
pcaoutput[:,3]=self.s.B_T_r[flag]
pcaoutput[:,4]=log10(self.SFR_BEST[flag])
pcaoutput[:,5]=self.s.SERSIC_TH50[flag]
pcaoutput[:,6]=self.s.SERSIC_N[flag]
pcaoutput[:,7]=log10(self.s.SIGMA_NN[flag])
pcaoutput[:,8]=log10(self.s.SIGMA_5[flag])
pcaoutput[:,9]=log10(self.s.SIGMA_10[flag])
pcaoutput[:,10]=self.s.CLUSTER_PHI[flag]
pcaoutput[:,11]=self.s.S2g_1[flag]
#pcaoutput[:,12]=n2ha[flag]
#pcaoutput[:,13]=o3hb[flag]
pcaoutput[:,12]=self.s.p_cs[flag]
pcaoutput[:,13]=log10(self.ssfr[flag]*1.e11)
pcaoutput[:,14]=(self.s.D4000[flag])
pcaoutput[:,15]=(self.s.AV[flag])
pcaoutput[:,16]=(self.nsamag[:,2][flag]-self.nsamag[:,3][flag])#u-g color
pcaoutput[:,17]=(self.s.AHDEW[flag])
#pcaoutput[:,19]=(self.s.HIDef[flag])
#pcaoutput[:,19]=(self.s.p_cs[flag])
outfile=homedir+'research/LocalClusters/Rdata/PCA.dat'
head='size \t Mstar \t dr \t BT \t SFR \t Rer \t nr \t sigmaNN \t sigma5 \t sigma10 \t clusterphi \t smoothness \t pcs \t ssfr \t D4000 \t AV \t ug \t HDEW'
savetxt(outfile,pcaoutput,header=head,fmt='%1.4e')
outfile=homedir+'research/LocalClusters/Rdata/PCA.tab'
savetxt(outfile,pcaoutput,delimiter='\t',header=head,comments='',fmt='%1.4e')
self.pcaoutput=pcaoutput
flag=(self.sampleflag & self.dvflag & self.gim2dflag & (self.s.B_T_r == self.s.B_T_r) & (n2ha == n2ha) & (o3hb == o3hb) & (self.s.SIZE_RATIO < 4.))
pcaoutput=zeros([sum(flag),21])
pcaoutput[:,0]=self.s.SIZE_RATIO[flag]
pcaoutput[:,1]=self.logstellarmass[flag]
pcaoutput[:,2]=self.s.DR_R200[flag]
pcaoutput[:,3]=self.s.B_T_r[flag]
pcaoutput[:,4]=log10(self.SFR_BEST[flag])
pcaoutput[:,5]=self.s.SERSIC_TH50[flag]
pcaoutput[:,6]=self.s.SERSIC_N[flag]
pcaoutput[:,7]=log10(self.s.SIGMA_NN[flag])
pcaoutput[:,8]=log10(self.s.SIGMA_5[flag])
pcaoutput[:,9]=log10(self.s.SIGMA_10[flag])
pcaoutput[:,10]=self.s.CLUSTER_SIGMA[flag]
pcaoutput[:,11]=self.s.S2g_1[flag]
pcaoutput[:,12]=n2ha[flag]
pcaoutput[:,13]=o3hb[flag]
pcaoutput[:,14]=log10(self.ssfr[flag]*1.e11)
pcaoutput[:,15]=(self.s.D4000[flag])
pcaoutput[:,16]=(self.s.AV[flag])
pcaoutput[:,17]=(self.nsamag[:,2][flag]-self.nsamag[:,3][flag])#u-g color
pcaoutput[:,18]=(self.s.AHDEW[flag])
#pcaoutput[:,19]=(self.upperlimit[flag])
#pcaoutput[:,20]=(self.s.HIDef[flag])
outfile=homedir+'research/LocalClusters/Rdata/censor.dat'
head='size M* dr B/T SFR Re_r n_r'
savetxt(outfile,pcaoutput,header=head,fmt='%1.4e')
self.pcaoutput=pcaoutput
self.agcdict=dict((a,b) for a,b in zip(self.s.AGCNUMBER,arange(len(self.s.AGCNUMBER))))
self.nsadict=dict((a,b) for a,b in zip(self.s.NSAID,arange(len(self.s.NSAID))))
self.massdensity=self.logstellarmass-log10(2*pi*(self.s.SERSIC_TH50*self.DA)**2)
#self.starburstflag = (self.ssfr/(.08e-9) > 2.)
'''
self.isosampleflag = (self.isorad.NSA > 0.) & (self.spiralflag) & (self.logstellarmass > minmass) & (self.s.SERSIC_BA > 0.2)#& (self.isorad.MIPS > 0.)
#self.ssfr=self.s.SFR_ZDIST/(10.**(self.jmass.MSTAR_50))
#print len(self.s.SFR_ZDIST),len(self.logstellarmassTaylor)
self.isotruncflag=(self.isorad.MIPS/self.isorad.NSA < .7) & self.isosampleflag
self.isosize=(self.isorad.MIPS/self.isorad.NSA)
self.r90size=(self.s.FLUX_RADIUS2*mipspixelscale/self.isorad.NSA)
self.r90size=(self.s.FLUX_RADIUS2*mipspixelscale/self.isorad.NSAR90)
self.outertruncflag=zeros(len(self.s.RA),'bool')
for i in range(len(self.s.RA)):
if self.s.NSAID[i] in truncated:
self.outertruncflag[i]=1
#self.massdensity=self.jmass.MSTAR_50+1.5*log10(self.s.SERSIC_TH50*self.DA)
#self.enhanced=((log10(self.s.SFR_ZDIST)-.25 -self.jmass.MSTAR_50) > (-0.35*(self.jmass.MSTAR_50-10)-10.)) & ~self.agnflag & self.isosampleflag & self.dvflag & (self.s.SIZE_RATIO < .5)
#self.normal=((log10(self.s.SFR_ZDIST)-.25-self.jmass.MSTAR_50) < (-0.35*((self.jmass.MSTAR_50)-10)-10.)) & ((log10(self.s.SFR_ZDIST)-.25-self.jmass.MSTAR_50) > (-0.35*((self.jmass.MSTAR_50)-10)-10.92)) & ~self.agnflag & self.isosampleflag & self.dvflag
#self.normalgalfit=((log10(self.s.SFR_ZDIST)-.25-self.jmass.MSTAR_50) < (-0.35*((self.jmass.MSTAR_50)-10)-10.)) & ((log10(self.s.SFR_ZDIST)-.25-self.jmass.MSTAR_50) > (-0.35*((self.jmass.MSTAR_50)-10)-10.92)) & ~self.agnflag & self.sampleflag & self.dvflag
#self.normaltrunc=((log10(self.s.SFR_ZDIST)-.25-self.jmass.MSTAR_50) < (-0.35*((self.jmass.MSTAR_50)-10)-10.)) & ((log10(self.s.SFR_ZDIST)-.25-self.jmass.MSTAR_50) > (-0.35*((self.jmass.MSTAR_50)-10)-10.92)) & ~self.agnflag & self.isosampleflag & self.dvflag & (self.isorad.MIPS*1.5 < self.isorad.NSA)
#self.normalconc=((log10(self.s.SFR_ZDIST)-.25-self.jmass.MSTAR_50) < (-0.35*((self.jmass.MSTAR_50)-10)-10.)) & ((log10(self.s.SFR_ZDIST)-.25-self.jmass.MSTAR_50) > (-0.35*((self.jmass.MSTAR_50)-10)-10.92)) & ~self.agnflag & self.sampleflag & self.dvflag & (self.s.SIZE_RATIO < .5)
#self.lowsfr=((log10(self.s.SFR_ZDIST)-.25-self.jmass.MSTAR_50) < (-0.35*((self.jmass.MSTAR_50)-10)-10.92)) & ((log10(self.s.SFR_ZDIST)-.25-self.jmass.MSTAR_50) > (-0.35*((self.jmass.MSTAR_50)-10)-11.4)) & ~self.agnflag & self.isosampleflag & self.dvflag
#self.depleted= ((log10(self.s.SFR_ZDIST)-.25-self.jmass.MSTAR_50) < (-0.35*((self.jmass.MSTAR_50)-10)-11.4)) & ~self.agnflag & self.isosampleflag & self.dvflag & ((log10(self.s.SFR_ZDIST)-.24-self.jmass.MSTAR_50) >-13)
'''
self.tdepletion=self.s.HIMASS/self.s.SFR_ZDIST
#print size(self.SFR_BEST),size(self.logstellarmassTaylor)
def calculate_clusterphi(self):
quad1=(self.s.DELTA_DEC > 0) & (self.s.DELTA_RA < 0)
quad2=(self.s.DELTA_DEC > 0) & (self.s.DELTA_RA > 0)
quad3=(self.s.DELTA_DEC < 0) & (self.s.DELTA_RA > 0)
quad4=(self.s.DELTA_DEC < 0) & (self.s.DELTA_RA < 0)
#self.theta=arctan(abs(self.delta_dec)/abs(self.delta_ra))*180./pi
# CALCULATE CLUSTER PHI
def phasespacestats(self):
# low Lx clusters
# size in virial region
# size outside R200
# high Lx clusters
# high Lx clusters without coma
print 'work in progress'
def printsize(self):
#flags=[self.membflag,self.nearfieldflag,self.fieldflag]
names=['$cluster$','$near \ field$','$field$']
outfile=open(homedir+'/Dropbox/Research/MyPapers/LCSpaper1/Table3.tex','w')
outfile.write('\\begin{deluxetable*}{lcccccc} \n')
outfile.write('\\tablecaption{Number and Size of SF and AGN By Environment \label{samplesizes}} \n')
outfile.write('\\tablehead{\\colhead{Category} & \\colhead{SF} &\\colhead{\\size} &\\colhead{AGN} & \\colhead{\\size} & \\colhead{Total} & \\colhead{\\size} } \n')
outfile.write('\startdata \n')
flags=[self.membflag & self.blueflag2,self.nearfieldflag & self.blueflag2,self.fieldflag & self.blueflag2]
names=['Cluster','Near Field','Field']
for i in range(len(names)):
tableline= '%s & %3i & %5.2f (%5.2f) $\pm$ %5.2f & %3i & %5.2f (%5.2f) $\pm$ %5.2f & %3i & %5.2f (%5.2f) $\pm$ %5.2f \\\\ \n' %(names[i],np.sum(flags[i] & self.sampleflag & ~self.agnflag),
np.mean(self.s.SIZE_RATIO[flags[i] & self.sampleflag & ~self.agnflag]),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag & ~self.agnflag]),
np.std(self.s.SIZE_RATIO[flags[i]& self.sampleflag & ~self.agnflag])/np.sqrt(np.sum(flags[i]& self.sampleflag & ~self.agnflag)),
np.sum(flags[i] & self.sampleflag & self.agnflag),
np.mean(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag]),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag]),
np.std(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag])/np.sqrt(np.sum(flags[i]& self.sampleflag & self.agnflag)),
np.sum(flags[i] & self.sampleflag),
np.mean(self.s.SIZE_RATIO[flags[i] & self.sampleflag ]),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag]),
np.std(self.s.SIZE_RATIO[flags[i] & self.sampleflag ])/np.sqrt(np.sum(flags[i]& self.sampleflag )))
outfile.write(tableline)
outfile.write('\enddata \n')
outfile.write('\end{deluxetable*} \n')
outfile.close()
for i in range(len(names)):
print '%s: \n \t N_SF = %3i, size = %5.2f (%5.2f) +/- %5.2f \n \t N_AGN = %3i, size = %5.2f (%5.2f) +/- %5.2f \n\t N_ALL = %3i, size = %5.2f (%5.2f) +/- %5.2f \n\n' %(names[i],np.sum(flags[i] & self.sampleflag & ~self.agnflag),
np.mean(self.s.SIZE_RATIO[flags[i] & self.sampleflag & ~self.agnflag]),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag & ~self.agnflag]),
np.std(self.s.SIZE_RATIO[flags[i]& self.sampleflag & ~self.agnflag])/np.sqrt(np.sum(flags[i]& self.sampleflag & ~self.agnflag)),
np.sum(flags[i] & self.sampleflag & self.agnflag),
np.mean(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag]),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag]),
np.std(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag])/np.sqrt(np.sum(flags[i]& self.sampleflag & self.agnflag)),
np.sum(flags[i] & self.sampleflag),
np.mean(self.s.SIZE_RATIO[flags[i] & self.sampleflag ]),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag]),
np.std(self.s.SIZE_RATIO[flags[i] & self.sampleflag ])/np.sqrt(np.sum(flags[i]& self.sampleflag )))
pl.figure()
pl.subplots_adjust(left=.15,bottom=.15)
allax=[]
#pl.subplot(2,1,1)
x=np.arange(3)
y=[np.mean(self.s.SIZE_RATIO[flags[0] & self.sampleflag & ~self.agnflag]),
np.mean(self.s.SIZE_RATIO[flags[1] & self.sampleflag & ~self.agnflag]),
np.mean(self.s.SIZE_RATIO[flags[2] & self.sampleflag & ~self.agnflag])]
yerror=[np.std(self.s.SIZE_RATIO[flags[0]& self.sampleflag & ~self.agnflag])/np.sqrt(np.sum(flags[0]& self.sampleflag & ~self.agnflag)),
np.std(self.s.SIZE_RATIO[flags[1]& self.sampleflag & ~self.agnflag])/np.sqrt(np.sum(flags[1]& self.sampleflag & ~self.agnflag)),
np.std(self.s.SIZE_RATIO[flags[2]& self.sampleflag & ~self.agnflag])/np.sqrt(np.sum(flags[2]& self.sampleflag & ~self.agnflag))]
errorbar(x,y,yerr=yerror,fmt='o',label='$SF \ Galaxies$',markersize=12,color='k')
allax.append(pl.gca())
#pl.subplot(2,1,2)
x=np.arange(3)
y=[np.mean(self.s.SIZE_RATIO[flags[0] & self.sampleflag & self.agnflag]),
np.mean(self.s.SIZE_RATIO[flags[1] & self.sampleflag & self.agnflag]),
np.mean(self.s.SIZE_RATIO[flags[2] & self.sampleflag & self.agnflag])]
yerror=[np.std(self.s.SIZE_RATIO[flags[0]& self.sampleflag & self.agnflag])/np.sqrt(np.sum(flags[0]& self.sampleflag & self.agnflag)),
np.std(self.s.SIZE_RATIO[flags[1]& self.sampleflag & self.agnflag])/np.sqrt(np.sum(flags[1]& self.sampleflag & self.agnflag)),
np.std(self.s.SIZE_RATIO[flags[2]& self.sampleflag & self.agnflag])/np.sqrt(np.sum(flags[2]& self.sampleflag & self.agnflag))]
#errorbar(x,y,yerr=yerror,fmt='^',label='$AGN$',markersize=12,color='k')
#allax.append(pl.gca())
titles=['$SF \ Galaxies $','$AGN $']
pl.legend(loc='upper left',numpoints=1)
pl.axis([-.4,2.4,0.4,.9])
pl.xticks(arange(3),names,fontsize=22)
#pl.gca().set_yscale('log')
pl.ylabel('$R_e(24)/R_e(r) $')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeenv.eps')
#pl.yticks(arange(0,2,.4))
'''
for i in range(len(allax)):
pl.sca(allax[i])
axis([-.4,2.4,0.,1.6])
pl.xticks(arange(3),names)
pl.yticks(arange(0,2,.4))
pl.text(.05,.8,titles[i],horizontalalignment='left',transform=allax[i].transAxes,fontsize=20)
np.mean(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag]),
np.mean(self.s.SIZE_RATIO[flags[i] & self.sampleflag ]),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag & ~self.agnflag]),
np.sum(flags[i] & self.sampleflag & self.agnflag),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag]),
np.std(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag])/np.sqrt(np.sum(flags[i]& self.sampleflag & self.agnflag)),
np.sum(flags[i] & self.sampleflag),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag]),
np.std(self.s.SIZE_RATIO[flags[i] & self.sampleflag ])/np.sqrt(np.sum(flags[i]& self.sampleflag )))
# plot field sizes
'''
def printsizeblue(self):
#flags=[self.membflag,self.nearfieldflag,self.fieldflag]
names=['$cluster$','$near \ field$','$field$']
outfile=open(homedir+'/Dropbox/Research/MyPapers/LCSsfrmass/Table3.tex','w')
outfile.write('\\begin{deluxetable*}{lcccccc} \n')
outfile.write('\\tablecaption{Number and Size of Star-forming and Starburst Galaxies By Environment \label{samplesizes}} \n')
outfile.write('\\tablehead{\\colhead{Category} & \\colhead{SF} &\\colhead{\\size} &\\colhead{Starburst} & \\colhead{\\size} & \\colhead{Total} & \\colhead{\\size} } \n')
outfile.write('\startdata \n')
flags=[self.membflag & self.blueflag2,self.nearfieldflag & self.blueflag2,self.fieldflag & self.blueflag2]
names=['Cluster','Near Field','Field']
for i in range(len(names)):
tableline= '%s & %3i & %5.2f (%5.2f) $\pm$ %5.2f & %3i & %5.2f (%5.2f) $\pm$ %5.2f & %3i & %5.2f (%5.2f) $\pm$ %5.2f \\\\ \n' %(names[i],np.sum(flags[i] & self.bluesampleflag & ~self.agnflag & ~self.starburst),
np.mean(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & ~self.agnflag & ~self.starburst]),
np.median(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & ~self.agnflag & ~self.starburst]),
np.std(self.s.SIZE_RATIO[flags[i]& self.bluesampleflag & ~self.agnflag & ~self.starburst])/np.sqrt(np.sum(flags[i]& self.bluesampleflag &~self.starburst & ~self.agnflag)),
np.sum(flags[i] & self.bluesampleflag & ~self.agnflag & self.starburst),
np.mean(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & ~self.agnflag & self.starburst]),
np.median(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & ~self.agnflag & self.starburst]),
np.std(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & ~self.agnflag & self.starburst])/np.sqrt(np.sum(flags[i]& self.bluesampleflag & ~self.agnflag & self.starburst)),
np.sum(flags[i] & self.bluesampleflag & ~self.agnflag),
np.mean(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & ~self.agnflag ]),
np.median(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & ~self.agnflag]),
np.std(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & ~self.agnflag ])/np.sqrt(np.sum(flags[i]& self.bluesampleflag & ~self.agnflag)))
outfile.write(tableline)
outfile.write('\enddata \n')
outfile.write('\end{deluxetable*} \n')
outfile.close()
#flags=[self.membflag,self.nearfieldflag,self.fieldflag]
names=['$cluster$','$near \ field$','$field$']
for i in range(len(names)):
print '%s: \n \t N_SF = %3i, size = %5.2f (%5.2f) +/- %5.2f \n \t N_AGN = %3i, size = %5.2f (%5.2f) +/- %5.2f \n\t N_ALL = %3i, size = %5.2f (%5.2f) +/- %5.2f \n\n' %(names[i],np.sum(flags[i] & self.bluesampleflag & ~self.agnflag),
np.mean(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & ~self.agnflag]),
np.median(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & ~self.agnflag]),
np.std(self.s.SIZE_RATIO[flags[i]& self.bluesampleflag & ~self.agnflag])/np.sqrt(np.sum(flags[i]& self.bluesampleflag & ~self.agnflag)),
np.sum(flags[i] & self.bluesampleflag & self.agnflag),
np.mean(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & self.agnflag]),
np.median(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & self.agnflag]),
np.std(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag & self.agnflag])/np.sqrt(np.sum(flags[i]& self.bluesampleflag & self.agnflag)),
np.sum(flags[i] & self.bluesampleflag),
np.mean(self.s.SIZE_RATIO[flags[i] & self.sampleflag ]),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag]),
np.std(self.s.SIZE_RATIO[flags[i] & self.bluesampleflag ])/np.sqrt(np.sum(flags[i]& self.bluesampleflag )))
pl.figure()
pl.subplots_adjust(left=.15,bottom=.15)
allax=[]
#pl.subplot(2,1,1)
x=np.arange(3)
y=[np.mean(self.s.SIZE_RATIO[flags[0] & self.bluesampleflag & ~self.agnflag & ~self.starburst]),
np.mean(self.s.SIZE_RATIO[flags[1] & self.bluesampleflag & ~self.agnflag & ~self.starburst]),
np.mean(self.s.SIZE_RATIO[flags[2] & self.bluesampleflag & ~self.agnflag & ~self.starburst])]
yerror=[np.std(self.s.SIZE_RATIO[flags[0]& self.bluesampleflag & ~self.agnflag & ~self.starburst])/np.sqrt(np.sum(flags[0]& self.bluesampleflag & ~self.agnflag & ~self.starburst)),
np.std(self.s.SIZE_RATIO[flags[1]& self.bluesampleflag & ~self.agnflag & ~self.starburst])/np.sqrt(np.sum(flags[1]& self.bluesampleflag & ~self.agnflag & ~self.starburst)),
np.std(self.s.SIZE_RATIO[flags[2]& self.bluesampleflag & ~self.agnflag & ~self.starburst])/np.sqrt(np.sum(flags[2]& self.bluesampleflag & ~self.agnflag & ~self.starburst))]
errorbar(x,y,yerr=yerror,fmt='o',label='$SF$',markersize=12,color='k')
allax.append(pl.gca())
#pl.subplot(2,1,2)
x=np.arange(3)
y=[np.mean(self.s.SIZE_RATIO[flags[0] & self.bluesampleflag & ~self.agnflag & self.starburst]),
np.mean(self.s.SIZE_RATIO[flags[1] & self.bluesampleflag & ~self.agnflag & self.starburst]),
np.mean(self.s.SIZE_RATIO[flags[2] & self.bluesampleflag & ~self.agnflag & self.starburst])]
yerror=[np.std(self.s.SIZE_RATIO[flags[0]& self.bluesampleflag & ~self.agnflag & self.starburst])/np.sqrt(np.sum(flags[0]& self.bluesampleflag & ~self.agnflag & self.starburst)),
np.std(self.s.SIZE_RATIO[flags[1]& self.bluesampleflag & ~self.agnflag & self.starburst])/np.sqrt(np.sum(flags[1]& self.bluesampleflag & ~self.agnflag & self.starburst)),
np.std(self.s.SIZE_RATIO[flags[2]& self.bluesampleflag & ~self.agnflag & self.starburst])/np.sqrt(np.sum(flags[2]& self.bluesampleflag & ~self.agnflag & self.starburst))]
errorbar(x,y,yerr=yerror,fmt='^',label='$Starburst$',markersize=12,color='k')
#allax.append(pl.gca())
titles=['$SF \ Galaxies $','$Starburst $']
pl.legend(loc='upper left',numpoints=1,fontsize=18)
pl.axis([-.4,2.4,0.2,.9])
pl.xticks(arange(3),names,fontsize=22)
#pl.gca().set_yscale('log')
pl.ylabel('$R_e(24)/R_e(r) $')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeenv.eps')
#pl.yticks(arange(0,2,.4))
'''
for i in range(len(allax)):
pl.sca(allax[i])
axis([-.4,2.4,0.,1.6])
pl.xticks(arange(3),names)
pl.yticks(arange(0,2,.4))
pl.text(.05,.8,titles[i],horizontalalignment='left',transform=allax[i].transAxes,fontsize=20)
np.mean(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag]),
np.mean(self.s.SIZE_RATIO[flags[i] & self.sampleflag ]),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag & ~self.agnflag]),
np.sum(flags[i] & self.sampleflag & self.agnflag),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag]),
np.std(self.s.SIZE_RATIO[flags[i] & self.sampleflag & self.agnflag])/np.sqrt(np.sum(flags[i]& self.sampleflag & self.agnflag)),
np.sum(flags[i] & self.sampleflag),
np.median(self.s.SIZE_RATIO[flags[i] & self.sampleflag]),
np.std(self.s.SIZE_RATIO[flags[i] & self.sampleflag ])/np.sqrt(np.sum(flags[i]& self.sampleflag )))
# plot field sizes
'''
def plotsizesample(self):
figure(figsize=(8,6))
subplots_adjust(left=.15,bottom=.15)
plot(self.s.p_cs[~self.nerrorflag],self.s.SIZE_RATIO[~self.nerrorflag],'ko')
plot(self.s.p_cs[self.nerrorflag],self.s.SIZE_RATIO[self.nerrorflag],'kx')
plot(self.s.p_cs[self.agnflag],self.s.SIZE_RATIO[self.agnflag],'ro',mfc='None',mec='r',markersize=10)
axis([-.05,1.05,1.e-4,30])
gca().set_yscale('log')
figure(figsize=(8,6))
subplots_adjust(left=.15,bottom=.15)
plot(self.ssfr[~self.nerrorflag],self.s.SIZE_RATIO[~self.nerrorflag],'k.')
errorbar(self.ssfr[~self.nerrorflag],self.s.SIZE_RATIO[~self.nerrorflag],self.s.SIZE_RATIOERR[~self.nerrorflag],fmt=None,ecolor='k')
plot(self.ssfr[self.nerrorflag],self.s.SIZE_RATIO[self.nerrorflag],'kx')
plot(self.ssfr[self.agnflag],self.s.SIZE_RATIO[self.agnflag],'ro',mfc='None',mec='r',markersize=8)
axhline(y=1,c='k')
axhline(y=.7,c='k',ls='--')
gca().set_yscale('log')
gca().set_xscale('log')
axis([1.e-13,1.e-8,1.e-4,30])
def plotsizesystematics(self,showTicks=False):
'''
plot Re(24) vs F24, nsersic, Re(r), M*
'''
#figure(figsize=(10,8))
#subplot(2,2,1)
flag = self.sampleflag & ~self.agnflag & self.dvflag
data=np.array([log10(self.s.FLUX24[flag]),self.s.SNR_SE[flag],log10(self.s.fcre1[flag]),self.s.fcnsersic1[flag],self.s.fcmag1[flag]]).T#,log10(self.s.SFR_ZDIST[flag])])
names=['SE \n FLUX24','SE \n SNR(24)','GALFIT \n Re','GALFIT \n N_SERSIC','GALFIT\n MODEL \n MAG']#,'SFR']
pair(data,names,showTicks=showTicks)
# self.s.SERSIC_TH50[flag],self.s.SERSIC_N[flag],
#err = zip(self.s.FLUX24ERR,self.s.fcre1err)
#errorbar(self.s.FLUX24[flag],self.s.fcre1[flag],xerr=self.s.FLUX24ERR[flag],yerr=self.s.fcre1err[flag],fmt='ko',ecolor='k')
#xticks(5)
savefig(homedir+'research/LocalClusters/SamplePlots/galfitSystematics.eps')
#flag = flag & (self.nsamag[:,4] > 14)
data24=np.array([(self.s.fcre1[flag]*mipspixelscale),self.s.fcnsersic1[flag],self.s.fcmag1[flag]])#,log10(self.s.SFR_ZDIST[flag])])
datar=np.array([(self.s.SERSIC_TH50[flag]),self.s.SERSIC_N[flag],self.nsamag[:,4][flag]])#,log10(self.s.SFR_ZDIST[flag])])
comparedata(data24.T,datar.T,rlabels=['Re(24)','N_SERSIC(24)','MODEL MAG'],clabels=['Re(r)','N_SERSIC(r)','MAG(r)'])
savefig(homedir+'research/LocalClusters/SamplePlots/galfitvsNSA.eps')
def plotRisovsRisoE0(self):
figure(figsize=(10,7))
plot(self.s.SERSIC_BA[self.isosampleflag],self.isorad.MIPS[self.isosampleflag]-self.isorad.MIPSE0[self.isosampleflag],'ko')
scale=sqrt(1-self.s.SERSIC_BA[self.isosampleflag]**2)
#scale=self.s.SERSIC_BA[self.isosampleflag]
plot(self.s.SERSIC_BA[self.isosampleflag],self.isorad.MIPS[self.isosampleflag]-self.isorad.MIPSE0[self.isosampleflag]/scale,'bo')
#plot(self.isorad.MIPS[self.isosampleflag],self.isorad.MIPSE0[self.isosampleflag]/self.s.SERSIC_BA[self.isosampleflag],'ro')
#xl=arange(70)
#plot(xl,xl,'k--')
#axis([0,150,0,150])
def plotRehist(self):
figure(figsize=(10,7))
subplots_adjust(bottom=.15)
mybins=arange(0,20.5,.5)
hist(self.s.SERSIC_TH50[~self.agnflag],bins=mybins,histtype='step',color='k', label='All Spirals')
#hist(self.s.SERSIC_TH50[~self.agnflag & self.sbflag],bins=mybins,histtype='step',color='k', hatch='//',label='SB Cut')
#hist(self.s.SERSIC_TH50[self.sampleflag],bins=mybins,histtype='step')
hist(self.s.SERSIC_TH50[self.sampleflag & self.sbflag],bins=mybins,histtype='stepfilled',color='0.8', label='Final Sample')
axvline(x=mipspixelscale,ls=':',color='k')
xlabel('$ R_e(NSA) \ (arcsec) $',fontsize=20)
ylabel('$ N_{galaxy}$',fontsize=20)
legend(loc='upper right')
savefig(homedir+'research/LocalClusters/SamplePlots/Rehist.eps')
savefig(homedir+'research/LocalClusters/SamplePlots/Rehist.png')
def plotf24hist(self):
figure(figsize=(9,7))
subplots_adjust(bottom=.15)
mybins=arange(-2,3,.25)
hist(log10(self.s.FLUX24[self.sampleflag & ~self.agnflag])-3.,bins=mybins,histtype='step',color='0.4', label='GALFIT Sample',hatch='\\',lw=2)
hist(log10(self.s.FLUX24[self.isosampleflag & ~self.agnflag])-3.,bins=mybins,histtype='step',color='k', label='Ellipse Sample',lw=2)
#hist(self.s.SERSIC_TH50[~self.agnflag & self.sbflag],bins=mybins,histtype='step',color='k', hatch='//',label='SB Cut')
#hist(self.s.SERSIC_TH50[self.sampleflag],bins=mybins,histtype='step')
#axvline(x=mipspixelscale,ls=':',color='k')
xlabel('$ log_{10}(F_{24} \ (mJy)) $',fontsize=28)
ylabel('$ N_{galaxy}$',fontsize=28)
legend(loc='upper right')
axis([-1.8,2.8,0,32])
gca().tick_params(axis='both', which='major', labelsize=16)
savefig(homedir+'research/LocalClusters/SamplePlots/f24hist.eps')
savefig(homedir+'research/LocalClusters/SamplePlots/f24hist.png')
def plotLIRhist(self):
figure(figsize=(9,7))
subplots_adjust(bottom=.15)
mybins=arange(6.5,12.5,.25)
hist(log10(self.s.LIR_ZDIST[self.sampleflag & ~self.agnflag]),bins=mybins,histtype='step',color='0.4', label='GALFIT Sample',hatch='\\',lw=2)
hist(log10(self.s.LIR_ZDIST[self.isosampleflag & ~self.agnflag]),bins=mybins,histtype='step',color='k', label='Ellipse Sample',lw=2)
#hist(self.s.SERSIC_TH50[~self.agnflag & self.sbflag],bins=mybins,histtype='step',color='k', hatch='//',label='SB Cut')
#hist(self.s.SERSIC_TH50[self.sampleflag],bins=mybins,histtype='step')
#axvline(x=mipspixelscale,ls=':',color='k')
xlabel('$ log_{10}(L_{IR}/L_\odot) $',fontsize=28)
ylabel('$ N_{galaxy}$',fontsize=28)
legend(loc='upper right')
axis([6.8,11.8,0,30])
gca().tick_params(axis='both', which='major', labelsize=16)
savefig(homedir+'research/LocalClusters/SamplePlots/LIRhist.eps')
savefig(homedir+'research/LocalClusters/SamplePlots/LIRhist.png')
def plotsizedvdr(self,plotsingle=1,reonly=1,onlycoma=0,plotHI=0,plotbadfits=1,lowmass=0,himass=0,cluster=None,plothexbin=False,hexbinmax=12,scalepoint=0,clustername=None,blueflag=False):
# log10(chabrier) = log10(Salpeter) - .25 (SFR estimate)
# log10(chabrier) = log10(diet Salpeter) - 0.1 (Stellar mass estimates)
if plotsingle:
figure(figsize=(10,6))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#axis([1.e9,1.e12,5.e-14,5.e-10])
#axis([9,12,-14.5,-10.5])
ylabel('$ \Delta v/\sigma $',fontsize=26)
xlabel('$ \Delta R/R_{200} $',fontsize=26)
legend(loc='upper left',numpoints=1)
colors=self.s.SIZE_RATIO
cbticks=[arange(.2,1.3,.4),arange(0,2.2,.5)]
clabel=['$R_e(24)/R_e(r)$','$R_{iso}(24)/R_{iso}(r)$']
cmaps=['jet_r','jet_r']
v1=[0.2,0.]
v2=[1.2,2]
nplot=1
x=(self.s.DR_R200)
y=abs(self.dv)
flag=self.sampleflag & self.dvflag
if blueflag:
flag=self.bluesampleflag & self.dvflag
if clustername != None:
flag = flag & (self.s.CLUSTER == clustername)
#flag=self.limitedsample & self.dvflag
if cluster != None:
flag = flag & (self.s.CLUSTER == cluster)
hexflag=self.dvflag
if cluster != None:
hexflag = hexflag & (self.s.CLUSTER == cluster)
nofitflag = self.sfsampleflag & ~self.sampleflag & self.dvflag
nofitflag = self.gim2dflag & (self.s.B_T_r < .2) & self.sfsampleflag & ~self.sampleflag & self.dvflag
if cluster != None:
nofitflag = nofitflag & (self.s.CLUSTER == cluster)
if lowmass:
flag = flag & (self.s.CLUSTER_LX < 1.)
hexflag = hexflag & (self.s.CLUSTER_LX < 1.)
nofitflag = nofitflag & (self.s.CLUSTER_LX < 1.)
if himass:
flag = flag & (self.s.CLUSTER_LX > 1.)
hexflag = hexflag & (self.s.CLUSTER_LX > 1.)
nofitflag = nofitflag & (self.s.CLUSTER_LX > 1.)
if onlycoma:
flag = flag & (self.s.CLUSTER == 'Coma')
if plothexbin:
sp=hexbin(x[hexflag],y[hexflag],gridsize=(24,8),alpha=.5,extent=(0,4,0,3),cmap='gray_r',vmin=0,vmax=hexbinmax)#,C=colors[flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i],gridsize=5,alpha=0.5,extent=(0,3.,0,2))
#flags=[self.sampleflag & self.dvflag ,self.sampleflag & self.agnflag]
subplots_adjust(bottom=.15,left=.15,right=.95,top=.95,hspace=.02,wspace=.02)
#xl=np.array([1.4,.35])
#yl=np.array([3.0,1.2])
#pl.plot(xl,yl,'k--',lw=2)
xl=np.array([0.01,1.2])
yl=np.array([1.5,0])
pl.plot(xl,yl,'k-',lw=2)
if reonly:
nplot=1
else:
nplot=2
if scalepoint:
size=(self.ssfrms[flag]+2)*40
else:
size=60
for i in range(nplot):
if not(reonly):
subplot(1,2,nplot)
nplot +=1
if plotbadfits:
scatter(x[nofitflag],y[nofitflag],marker='x',color='k',s=40)#markersize=8,mec='r',mfc='None',label='No Fit')
ax=gca()
#flag=flags[i]
#sp=hexbin(x[flag],y[flag],C=colors[flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i],gridsize=5,alpha=0.5,extent=(0,3.,0,2))
sp=scatter(x[flag],y[flag],c=colors[flag],s=size,cmap=cm.jet_r,vmin=0.1,vmax=1)
#print len(x[flag])
#flag2=self.spiralflag & ~self.sampleflag & self.dvflag & ~self.agnflag
#plot(x[flag2],y[flag2],'ko',color='0.5')
#flag2=flag & self.truncflag
#scatter(x[flag2],y[flag2]-x[flag2],c=colors[i][flag2],marker='*',s=120)
#scatter(x[self.sampleflag],y[self.outertruncflag]-x[self.outertruncflag],c=colors[i][self.outertruncflag],marker='*',s=120)
#axhline(y=0,ls='-',color='k')
axis([-.1,4.2,-.1,3])
if i > 0:
ax.set_yticklabels(([]))
ax.tick_params(axis='both', which='major', labelsize=16)
#ax.set_xscale('log')
#axins1 = inset_axes(ax,
# width="5%", # width = 10% of parent_bbox width
# height="50%", # height : 50%
# bbox_to_anchor=(.9,0.05,1,1),
# bbox_transform=ax.transAxes,
# borderpad=0,
# loc=3)
if plotsingle:
cb=colorbar(sp,fraction=0.08)#cax=axins1,ticks=cbticks[i])
text(.95,.9,clabel[i],transform=ax.transAxes,horizontalalignment='right',fontsize=20)
if plotHI:
f=flag & self.HIflag
pl.plot(x[f],y[f],'bs',mfc='None',mec='b',lw=2,markersize=20)
if not(reonly):
ax.text(0,-.1,'$ \Delta R/R_{200} $',fontsize=22,transform=ax.transAxes,horizontalalignment='center')
ax.text(-1.3,.5,'$\Delta v/\sigma_v $',fontsize=22,transform=ax.transAxes,rotation=90,verticalalignment='center')
if lowmass:
figname=homedir+'research/LocalClusters/SamplePlots/sizedvdr-lowLx'
elif himass:
figname=homedir+'research/LocalClusters/SamplePlots/sizedvdr-hiLx'
else:
figname=homedir+'research/LocalClusters/SamplePlots/sizedvdr'
if plotsingle:
savefig(figname+'.png')
savefig(figname+'.eps')
def plotsizedvdrcombined(self,plotsingle=1,reonly=1,onlycoma=0,plotHI=0,plotbadfits=1,lowmass=0,himass=0,cluster=None,plothexbin=False,hexbinmax=10,scalepoint=0):
# log10(chabrier) = log10(Salpeter) - .25 (SFR estimate)
# log10(chabrier) = log10(diet Salpeter) - 0.1 (Stellar mass estimates)
if plotsingle:
figure(figsize=(10,6))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#axis([1.e9,1.e12,5.e-14,5.e-10])
#axis([9,12,-14.5,-10.5])
ylabel('$ \Delta v/\sigma $',fontsize=26)
xlabel('$ \Delta R/R_{200} $',fontsize=26)
legend(loc='upper left',numpoints=1)
colors=self.s.SIZE_RATIO
cbticks=[arange(.2,1.3,.4),arange(0,2.2,.5)]
clabel=['$R_e(24)/R_e(r)$','$R_{iso}(24)/R_{iso}(r)$']
cmaps=['jet_r','jet_r']
v1=[0.2,0.]
v2=[1.2,2]
nplot=1
x=(self.s.DR_R200)
y=self.dv
flag=self.sampleflag & self.dvflag
if cluster != None:
flag = flag & (self.s.CLUSTER == cluster)
hexflag=self.dvflag
if cluster != None:
hexflag = hexflag & (self.s.CLUSTER == cluster)
nofitflag = self.sfsampleflag & ~self.sampleflag & self.dvflag
if cluster != None:
nofitflag = nofitflag & (self.s.CLUSTER == cluster)
if lowmass:
flag = flag & (self.s.CLUSTER_LX < 1.)
hexflag = hexflag & (self.s.CLUSTER_LX < 1.)
nofitflag = nofitflag & (self.s.CLUSTER_LX < 1.)
if himass:
flag = flag & (self.s.CLUSTER_LX > 1.)
hexflag = hexflag & (self.s.CLUSTER_LX > 1.)
nofitflag = nofitflag & (self.s.CLUSTER_LX > 1.)
if onlycoma:
flag = flag & (self.s.CLUSTER == 'Coma')
if plothexbin:
sp=hexbin(x[hexflag],y[hexflag],gridsize=(24,8),alpha=.5,extent=(0,4,0,3),cmap='gray_r',vmin=0,vmax=hexbinmax)#,C=colors[flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i],gridsize=5,alpha=0.5,extent=(0,3.,0,2))
#flags=[self.sampleflag & self.dvflag ,self.sampleflag & self.agnflag]
subplots_adjust(bottom=.15,left=.15,right=.95,top=.95,hspace=.02,wspace=.02)
xl=np.array([1.4,.35])
yl=np.array([3.0,1.2])
pl.plot(xl,yl,'k--',lw=2)
xl=np.array([0.01,1.2])
yl=np.array([1.5,0])
pl.plot(xl,yl,'k-',lw=2)
if reonly:
nplot=1
else:
nplot=2
if scalepoint:
size=(self.ssfrms[flag]+2)*40
else:
size=60
for i in range(nplot):
if not(reonly):
subplot(1,2,nplot)
nplot +=1
ax=gca()
#flag=flags[i]
#sp=hexbin(x[flag],y[flag],C=colors[flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i],gridsize=5,alpha=0.5,extent=(0,3.,0,2))
sp=scatter(x[flag],y[flag],c=colors[flag],s=size,cmap=cm.jet_r,vmin=0.1,vmax=1)
#flag2=self.spiralflag & ~self.sampleflag & self.dvflag & ~self.agnflag
#plot(x[flag2],y[flag2],'ko',color='0.5')
#flag2=flag & self.truncflag
#scatter(x[flag2],y[flag2]-x[flag2],c=colors[i][flag2],marker='*',s=120)
#scatter(x[self.sampleflag],y[self.outertruncflag]-x[self.outertruncflag],c=colors[i][self.outertruncflag],marker='*',s=120)
#axhline(y=0,ls='-',color='k')
axis([-.1,4.2,-.1,3])
if i > 0:
ax.set_yticklabels(([]))
ax.tick_params(axis='both', which='major', labelsize=16)
#ax.set_xscale('log')
#axins1 = inset_axes(ax,
# width="5%", # width = 10% of parent_bbox width
# height="50%", # height : 50%
# bbox_to_anchor=(.9,0.05,1,1),
# bbox_transform=ax.transAxes,
# borderpad=0,
# loc=3)
if plotsingle:
cb=colorbar(sp,fraction=0.08)#cax=axins1,ticks=cbticks[i])
text(.95,.9,clabel[i],transform=ax.transAxes,horizontalalignment='right',fontsize=20)
if plotHI:
f=flag & self.HIflag
pl.plot(x[f],y[f],'bs',mfc='None',mec='b',lw=2,markersize=20)
if plotbadfits:
plot(x[nofitflag],y[nofitflag],'rx',markersize=8,mec='r',mfc='None',label='No Fit')
if not(reonly):
ax.text(0,-.1,'$ \Delta R/R_{200} $',fontsize=22,transform=ax.transAxes,horizontalalignment='center')
ax.text(-1.3,.5,'$\Delta v/\sigma_v $',fontsize=22,transform=ax.transAxes,rotation=90,verticalalignment='center')
if lowmass:
figname=homedir+'research/LocalClusters/SamplePlots/sizedvdr-lowLx'
elif himass:
figname=homedir+'research/LocalClusters/SamplePlots/sizedvdr-hiLx'
else:
figname=homedir+'research/LocalClusters/SamplePlots/sizedvdr'
if plotsingle:
savefig(figname+'.png')
savefig(figname+'.eps')
def plotSFRvsStellarmassPaper(self,plotsingle=1,zoom=0,onepanel=0,farfield=0):
figure(figsize=plotsize_single)
pl.subplots_adjust(left=.17,bottom=.2)
flag=self.mipsflag & self.agnflag
pl.plot(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],'ko',markersize=3,label='AGN',mfc='None')
flag=self.mipsflag & ~self.agnflag
pl.plot(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],'k*',c='0.6',markersize=7,label='SF',mfc='None')
#pl.hexbin(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],cmap='gray_r')
#flag=self.sfsampleflag & self.agnflag
#plot(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],'kx', c='k',markersize=8,label='AGN(Sample)',mfc='None',mec='k')
#flag=self.sfsampleflag & ~self.agnflag
#plot(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],'k^',color='k',markersize=8,label='SF(Sample)')
pl.axis([7.8,12,.008,20])
xe=np.arange(8.5,11.5,.1)
xe=10.**xe
ye=(.08e-9)*xe
pl.plot(log10(xe),(ye),'k-',lw=2,label='Elbaz+2011')
pl.gca().set_yscale('log')
pl.axvline(x=9.3,c='k',ls='--')
pl.axhline(y=.086,c='k',ls='--')
#colorbar(sp,fraction=.08)
pl.axis([7.9,12,1.e-3,25])
pl.xlabel(r'$ M_* \ (M_\odot/yr) $')
pl.ylabel('$ SFR \ (M_\odot/yr) $')
pl.legend(loc='upper left',numpoints=1,scatterpoints=1)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/SFRvsStellarmassPaper.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/SFRvsStellarmassPaper.eps')
def plotSFRvsStellarmassPaper2(self,plotsingle=1,zoom=0,onepanel=0,farfield=0):
figure(figsize=plotsize_2panel)
pl.subplots_adjust(bottom=.2, hspace=.05)
axes=[]
pl.subplot(1,2,1)
flag=self.mipsflag & ~self.agnflag
pl.plot(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],'ko',markersize=3,label='SF',mfc='None')
flag=self.mipsflag & self.unknownagn
pl.plot(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],'ks',markersize=5,label='AGN?')
pl.ylabel('$ SFR \ (M_\odot/yr) $')
pl.title('$ SF \ Galaxies $',fontsize=20)
axes.append(pl.gca())
pl.subplot(1,2,2)
flag=self.mipsflag & self.agnflag
pl.plot(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],'ko',markersize=3,label='AGN',mfc='None')
pl.yticks([])
pl.title('$ AGN $',fontsize=20)
axes.append(pl.gca())
for a in axes:
pl.sca(a)
pl.axis([7.8,11.75,.008,20])
xe=np.arange(8.5,11.5,.1)
xe=10.**xe
ye=(.08e-9)*xe
pl.plot(log10(xe),(ye),'k-',lw=2,label='Elbaz+2011')
pl.plot(log10(xe),(ye/50.),'k:',lw=1,label='MS/50')
pl.gca().set_yscale('log')
pl.axvline(x=9.3,c='k',ls='--')
pl.axhline(y=.086,c='k',ls='--')
pl.axis([7.9,12,1.e-3,25])
pl.xlabel(r'$ log_{10}(M_* \ (M_\odot/yr)) $')
pl.legend(loc='upper left',numpoints=1,scatterpoints=1)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/SFRvsStellarmassPaper.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/SFRvsStellarmassPaper.eps')
def plotsizeBT(self,scalepoint=0,blueflag=False):
figure(figsize=(10,8))
subplots_adjust(left=.12,bottom=.15,wspace=.02,hspace=.02)
if blueflag:
flag1=self.blueflag2
flag2=self.bluesampleflag
else:
flag1=self.sfsampleflag
flag2=self.sampleflag
x_flags=[flag1 & ~self.sampleflag & ~self.agnflag & self.membflag & self.gim2dflag,
flag1 & ~self.sampleflag & self.agnflag & self.membflag & self.gim2dflag,
flag1 & ~self.sampleflag & ~self.agnflag & ~self.membflag & self.dvflag & self.gim2dflag,
flag1 & ~self.sampleflag & self.agnflag & ~self.membflag & self.dvflag & self.gim2dflag]
point_flags=[flag2 & ~self.agnflag & self.membflag & self.gim2dflag,
flag2 & self.agnflag & self.membflag & self.gim2dflag,
flag2 & ~self.agnflag & ~self.membflag & self.dvflag & self.gim2dflag,
flag2 & self.agnflag & ~self.membflag & self.dvflag & self.gim2dflag]
bothax=[]
x=self.s.B_T_r
y=self.s.SIZE_RATIO
limits=[-.1,1.,.01,1.5]
if scalepoint:
size=(self.ssfrms[point_flags[i]]+2)*40
else:
size=60
for i in range(4):
pl.subplot(2,2,i+1)
#pl.plot(x[x_flags[i]],y[x_flags[i]],'kx',markersize=8,label='No Fit')
sp=pl.scatter(x[point_flags[i]],y[point_flags[i]],c=self.logstellarmass[point_flags[i]],vmin=mstarmin,vmax=mstarmax,cmap='jet',s=size,label='GALFIT')
pl.axis(limits)
a=pl.gca()
rho,p=spearman(x[point_flags[i]],y[point_flags[i]])
ax=pl.gca()
pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=a.transAxes,fontsize=18)
pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=a.transAxes,fontsize=18)
bothax.append(a)
if i == 0:
a.set_xticklabels(([]))
pl.text(0.1,0.9,'$Cluster$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
pl.title('$ SF \ Galaxies $',fontsize=22)
if i == 1:
a.set_xticklabels(([]))
a.set_yticklabels(([]))
#pl.legend(loc='lower left',numpoints=1,scatterpoints=1)
pl.title('$AGN $',fontsize=22)
if i == 2:
text(0.1,0.9,'$Field$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
text(-0.2,1.,'$R_e(24)/Re(r)$',transform=a.transAxes,rotation=90,horizontalalignment='center',verticalalignment='center',fontsize=24)
if i == 3:
a.set_yticklabels(([]))
text(-0.02,-.2,'$B/T$',transform=a.transAxes,horizontalalignment='center',fontsize=24)
i += 1
c=colorbar(ax=bothax,fraction=.05)
c.ax.text(2.4,.5,'$log_{10}(M_*/M_\odot)$',rotation=-90,verticalalignment='center',fontsize=20)
savefig(homedir+'research/LocalClusters/SamplePlots/sizeBT.png')
savefig(homedir+'research/LocalClusters/SamplePlots/sizeBT.eps')
def plotsizesb(self,scalepoint=0):
figure(figsize=(10,8))
subplots_adjust(left=.12,bottom=.15,wspace=.02,hspace=.02)
x_flags=[self.sfsampleflag & ~self.sampleflag & ~self.agnflag & self.membflag,
self.sfsampleflag & ~self.sampleflag & self.agnflag & self.membflag,
self.sfsampleflag & ~self.sampleflag & ~self.agnflag & ~self.membflag,
self.sfsampleflag & ~self.sampleflag & self.agnflag & ~self.membflag]
point_flags=[self.sampleflag & ~self.agnflag & self.membflag & self.gim2dflag,
self.sampleflag & self.agnflag & self.membflag & self.gim2dflag,
self.sampleflag & ~self.agnflag & ~self.membflag,
self.sampleflag & self.agnflag & ~self.membflag]
bothax=[]
x=self.sb_obs
y=self.s.SIZE_RATIO
limits=[12,21.,.01,1.5]
if scalepoint:
size=(self.ssfrms[point_flags[i]]+2)*40
else:
size=60
for i in range(4):
pl.subplot(2,2,i+1)
#pl.plot(x[x_flags[i]],y[x_flags[i]],'kx',markersize=8,label='No Fit')
sp=pl.scatter(x[point_flags[i]],y[point_flags[i]],c=self.logstellarmass[point_flags[i]],vmin=mstarmin,vmax=mstarmax,cmap='jet',s=size,label='GALFIT')
pl.axis(limits)
a=pl.gca()
#rho,p=spearman(x[point_flags[i]],y[point_flags[i]])
#ax=pl.gca()
#pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=a.transAxes,fontsize=18)
#pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=a.transAxes,fontsize=18)
bothax.append(a)
if i == 0:
a.set_xticklabels(([]))
pl.text(0.1,0.9,'$Cluster$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
pl.title('$ SF \ Galaxies $',fontsize=22)
if i == 1:
a.set_xticklabels(([]))
a.set_yticklabels(([]))
#pl.legend(loc='lower left',numpoints=1,scatterpoints=1)
pl.title('$AGN $',fontsize=22)
if i == 2:
text(0.1,0.9,'$Field$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
text(-0.2,1.,'$R_e(24)/Re(r)$',transform=a.transAxes,rotation=90,horizontalalignment='center',verticalalignment='center',fontsize=24)
if i == 3:
a.set_yticklabels(([]))
text(-0.02,-.2,'$B/T$',transform=a.transAxes,horizontalalignment='center',fontsize=24)
i += 1
c=colorbar(ax=bothax,fraction=.05)
c.ax.text(2.4,.5,'$log_{10}(M_*/M_\odot)$',rotation=-90,verticalalignment='center',fontsize=20)
savefig(homedir+'research/LocalClusters/SamplePlots/sizesb.png')
savefig(homedir+'research/LocalClusters/SamplePlots/sizesb.eps')
def plotssfrsigmair(self,scalepoint=0,usesize=0):
figure(figsize=(10,8))
subplots_adjust(left=.12,bottom=.15,wspace=.02,hspace=.02)
x_flags=[self.sfsampleflag & ~self.sampleflag & ~self.agnflag,
self.sfsampleflag & ~self.sampleflag & self.agnflag,
self.sfsampleflag & ~self.sampleflag & ~self.agnflag,
self.sfsampleflag & ~self.sampleflag & self.agnflag]
point_flags=[self.sampleflag & ~self.agnflag & self.membflag,
self.sampleflag & self.agnflag & self.membflag,
self.sampleflag & ~self.agnflag & ~self.membflag,
self.sampleflag & self.agnflag & ~self.membflag]
bothax=[]
x=self.sigma_ir
y=self.ssfr*1.e9/.08
yerror=self.ssfrerr*1.e9/.08
xerror=self.sigma_irerr
limits=[2.e7,9.e10,1.e-2,15.]
if scalepoint:
size=(self.ssfrms[point_flags[i]]+2)*40
else:
size=60
for i in range(4):
pl.subplot(2,2,i+1)
#pl.plot(x[x_flags[i]],y[x_flags[i]],'kx',markersize=8,label='No Fit')
if usesize:
sp=pl.scatter(x[point_flags[i]],y[point_flags[i]],c=self.s.SIZE_RATIO[point_flags[i]],vmin=.1,vmax=1,cmap='jet_r',s=size,label='GALFIT')
else:
sp=pl.scatter(x[point_flags[i]],y[point_flags[i]],c=self.logstellarmass[point_flags[i]],vmin=mstarmin,vmax=mstarmax,cmap='jet',s=size,label='GALFIT')
pl.errorbar(x[point_flags[i]],y[point_flags[i]],yerr=yerror[point_flags[i]],xerr=xerror[point_flags[i]],fmt=None)
pl.axis(limits)
a=pl.gca()
a.set_xscale('log')
a.set_yscale('log')
pl.axhline(y=2,ls='--',color='b')
pl.axhline(y=1,ls='-',color='k')
pl.axvline(x=5.e9,ls='--',color='b')
#rho,p=spearman(x[point_flags[i]],y[point_flags[i]])
#ax=pl.gca()
#pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=a.transAxes,fontsize=18)
#pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=a.transAxes,fontsize=18)
bothax.append(a)
if i == 0:
a.set_xticklabels(([]))
pl.text(0.1,0.9,'$Cluster$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
pl.title('$ SF \ Galaxies $',fontsize=22)
if i == 1:
a.set_xticklabels(([]))
a.set_yticklabels(([]))
#pl.legend(loc='lower left',numpoints=1,scatterpoints=1)
pl.title('$AGN $',fontsize=22)
if i == 2:
text(0.1,0.9,'$Field$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
text(-0.2,1.,'$sSFR/sSFR_{MS}$',transform=a.transAxes,rotation=90,horizontalalignment='center',verticalalignment='center',fontsize=24)
if i == 3:
a.set_yticklabels(([]))
text(-0.02,-.2,'$\Sigma_{IR} = L_{IR}/(\pi R_e(24)^2) $',transform=a.transAxes,horizontalalignment='center',fontsize=24)
i += 1
c=colorbar(ax=bothax,fraction=.05)
if usesize:
c.ax.text(2.4,.5,'$R_e(24)/R_e(r)$',rotation=-90,verticalalignment='center',fontsize=20)
else:
c.ax.text(2.4,.5,'$log_{10}(M_*/M_\odot)$',rotation=-90,verticalalignment='center',fontsize=20)
savefig(homedir+'research/LocalClusters/SamplePlots/ssfrsigmair.png')
savefig(homedir+'research/LocalClusters/SamplePlots/ssfrsigmair.eps')
def plotsizepcs(self,scalepoint=0):
figure(figsize=(10,8))
subplots_adjust(left=.12,bottom=.15,wspace=.02,hspace=.02)
x_flags=[self.sfsampleflag & ~self.sampleflag & ~self.agnflag & self.membflag & self.zooflag,
self.sfsampleflag & ~self.sampleflag & self.agnflag & self.membflag & self.zooflag,
self.sfsampleflag & ~self.sampleflag & ~self.agnflag & ~self.membflag & self.dvflag & self.zooflag,
self.sfsampleflag & ~self.sampleflag & self.agnflag & ~self.membflag & self.dvflag & self.zooflag]
point_flags=[self.sampleflag & ~self.agnflag & self.membflag & self.zooflag,
self.sampleflag & self.agnflag & self.membflag & self.zooflag,
self.sampleflag & ~self.agnflag & ~self.membflag & self.dvflag & self.zooflag,
self.sampleflag & self.agnflag & ~self.membflag & self.dvflag & self.zooflag]
bothax=[]
x=self.s.p_cs
y=self.s.SIZE_RATIO
limits=[-.1,1.,.01,1.5]
if scalepoint:
size=(self.ssfrms[point_flags[i]]+2)*40
else:
size=60
for i in range(4):
pl.subplot(2,2,i+1)
#pl.plot(x[x_flags[i]],y[x_flags[i]],'kx',markersize=8,label='No Fit')
sp=pl.scatter(x[point_flags[i]],y[point_flags[i]],c=self.logstellarmass[point_flags[i]],vmin=mstarmin,vmax=mstarmax,cmap='jet',s=size,label='GALFIT')
pl.axis(limits)
a=pl.gca()
rho,p=spearman(x[point_flags[i]],y[point_flags[i]])
ax=pl.gca()
pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=a.transAxes,fontsize=18)
pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=a.transAxes,fontsize=18)
bothax.append(a)
if i == 0:
a.set_xticklabels(([]))
pl.text(0.1,0.9,'$Cluster$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
pl.title('$ SF \ Galaxies $',fontsize=22)
if i == 1:
a.set_xticklabels(([]))
a.set_yticklabels(([]))
#pl.legend(loc='lower left',numpoints=1,scatterpoints=1)
pl.title('$AGN $',fontsize=22)
if i == 2:
text(0.1,0.9,'$Field$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
text(-0.2,1.,'$R_e(24)/Re(r)$',transform=a.transAxes,rotation=90,horizontalalignment='center',verticalalignment='center',fontsize=24)
if i == 3:
a.set_yticklabels(([]))
text(-0.02,-.2,'$Spiral \ Probability$',transform=a.transAxes,horizontalalignment='center',fontsize=24)
i += 1
c=colorbar(ax=bothax,fraction=.05)
c.ax.text(2.4,.5,'$log_{10}(M_*/M_\odot)$',rotation=-90,verticalalignment='center',fontsize=20)
savefig(homedir+'research/LocalClusters/SamplePlots/sizeBT.png')
savefig(homedir+'research/LocalClusters/SamplePlots/sizeBT.eps')
def plotsizedvdr4(self,scalepoint=0):
figure(figsize=(10,8))
subplots_adjust(left=.12,bottom=.15,wspace=.02,hspace=.02)
x_flags=[self.sfsampleflag & ~self.sampleflag & ~self.agnflag & self.dvflag & (self.s.CLUSTER_LX < 1),
self.sfsampleflag & ~self.sampleflag & self.agnflag & self.dvflag& (self.s.CLUSTER_LX < 1),
self.sfsampleflag & ~self.sampleflag & ~self.agnflag & self.dvflag & (self.s.CLUSTER_LX > 1),
self.sfsampleflag & ~self.sampleflag & self.agnflag & self.dvflag & (self.s.CLUSTER_LX > 1)]
point_flags=[self.sampleflag & ~self.agnflag & self.dvflag & (self.s.CLUSTER_LX < 1),
self.sampleflag & self.agnflag & self.dvflag & (self.s.CLUSTER_LX < 1),
self.sampleflag & ~self.agnflag & self.dvflag & (self.s.CLUSTER_LX > 1),
self.sampleflag & self.agnflag & self.dvflag & (self.s.CLUSTER_LX > 1)]
bothax=[]
x=self.s.DR_R200
y=abs(self.dv)
limits=[-.1,3.4,-.1,2.6]
if scalepoint:
size=(self.ssfrms+2)*40
else:
size=60*np.ones(len(x))
for i in range(4):
pl.subplot(2,2,i+1)
pl.scatter(x[x_flags[i]],y[x_flags[i]],marker='x',c='k',s=40,label='No Fit')
sp=pl.scatter(x[point_flags[i]],y[point_flags[i]],s=size[point_flags[i]],vmin=.1,vmax=1,cmap='jet_r',c=self.s.SIZE_RATIO[point_flags[i]],label='GALFIT')
pl.axis(limits)
a=pl.gca()
bothax.append(a)
if i == 0:
a.set_xticklabels(([]))
pl.title('$ SF \ Galaxies $',fontsize=22)
if i == 1:
a.set_xticklabels(([]))
a.set_yticklabels(([]))
#pl.legend(loc='lower left',numpoints=1,scatterpoints=1)
pl.title('$AGN $',fontsize=22)
pl.text(0.95,0.9,'$log_{10}(L_X) < 43$',transform=a.transAxes,horizontalalignment='right',fontsize=20)
if i == 2:
pl.text(-0.2,1.,'$\Delta v/\sigma_v$',transform=a.transAxes,rotation=90,horizontalalignment='center',verticalalignment='center',fontsize=24)
if i == 3:
a.set_yticklabels(([]))
pl.text(0.95,0.9,'$log_{10}(L_X) > 43$',transform=a.transAxes,horizontalalignment='right',fontsize=20)
pl.text(-0.02,-.2,'$\Delta r/R_{200}$',transform=a.transAxes,horizontalalignment='center',fontsize=24)
xl=np.array([1.4,.35])
yl=np.array([3.0,1.2])
pl.plot(xl,yl,'k--',lw=2)
xl=np.array([0.01,1.2])
yl=np.array([1.5,0])
pl.plot(xl,yl,'k-',lw=2)
c=colorbar(ax=bothax,fraction=.05)
c.ax.text(2.4,.5,'$R_e(24)/R_e(r)$',rotation=-90,verticalalignment='center',fontsize=20)
savefig(homedir+'research/LocalClusters/SamplePlots/sizedvdr4.png')
savefig(homedir+'research/LocalClusters/SamplePlots/sizedvdr4.eps')
def plotsalimcolormag(self):
figure(figsize=(10,8))
subplots_adjust(left=.12,bottom=.15,wspace=.02,hspace=.02)
x_flags=[self.sfsampleflag & ~self.sampleflag & ~self.agnflag & self.membflag,
self.sfsampleflag & ~self.sampleflag & self.agnflag & self.membflag,
self.sfsampleflag & ~self.sampleflag & ~self.agnflag & ~self.membflag & self.dvflag,
self.sfsampleflag & ~self.sampleflag & self.agnflag & ~self.membflag & self.dvflag]
point_flags=[self.sampleflag & ~self.agnflag & self.membflag,
self.sampleflag & self.agnflag & self.membflag,
self.sampleflag & ~self.agnflag & ~self.membflag & self.dvflag,
self.sampleflag & self.agnflag & ~self.membflag & self.dvflag]
bothax=[]
y=self.nsamag[:,1] - self.nsamag[:,4]
x=self.s.ABSMAG[:,4]
limits=[-22.8,-16.8,.5,6.9]
for i in range(4):
pl.subplot(2,2,i+1)
pl.axhline(y=4,ls='--',color='k')
pl.plot(x[x_flags[i]],y[x_flags[i]],'kx',markersize=8,label='No Fit')
sp=pl.scatter(x[point_flags[i]],y[point_flags[i]],c=self.s.SIZE_RATIO[point_flags[i]],vmin=0.1,vmax=1,cmap='jet_r',s=100,label='GALFIT')
pl.axis(limits)
#xe=arange(8.5,11.5,.1)
#xe=10.**xe
#ye=(.08e-9)*xe
#plot(log10(xe),(ye),'k-',lw=1,label='$Elbaz+2011$')
#plot(log10(xe),(2*ye),'k:',lw=1,label='$2 \ SFR_{MS}$')
#gca().set_yscale('log')
a=pl.gca()
bothax.append(a)
#axvline(x=9.3,c='k',ls='--')
#axhline(y=.086,c='k',ls='--')
#if i > 2:
# xlabel('$log_{10}(M_* (M_\odot)) $',fontsize=22)
if i == 0:
a.set_xticklabels(([]))
pl.text(0.1,0.9,'$Cluster$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
pl.title('$ SF \ Galaxies $',fontsize=22)
if i == 1:
a.set_xticklabels(([]))
a.set_yticklabels(([]))
pl.legend(loc='lower left',numpoints=1,scatterpoints=1)
pl.title('$AGN $',fontsize=22)
if i == 2:
text(0.1,0.9,'$Field$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
text(-0.2,1.,'$NUV - r$',transform=a.transAxes,rotation=90,horizontalalignment='center',verticalalignment='center',fontsize=24)
if i == 3:
a.set_yticklabels(([]))
text(-0.02,-.2,'$M_r$',transform=a.transAxes,horizontalalignment='center',fontsize=24)
i += 1
c=colorbar(ax=bothax,fraction=.05)
c.ax.text(2.2,.5,'$R_e(24)/R_e(r)$',rotation=-90,verticalalignment='center',fontsize=20)
savefig(homedir+'research/LocalClusters/SamplePlots/salimcolormag.png')
savefig(homedir+'research/LocalClusters/SamplePlots/salimcolormag.eps')
def plotSFRStellarmassSize(self,clustername=None):
figure(figsize=(10,8))
subplots_adjust(left=.12,bottom=.15,wspace=.02,hspace=.02)
x_flags=[self.blueflag2 & ~self.sampleflag & ~self.agnflag & self.membflag,
self.blueflag2 & ~self.sampleflag & self.agnflag & self.membflag,
self.blueflag2 & ~self.sampleflag & ~self.agnflag & ~self.membflag & self.dvflag,
self.blueflag2 & ~self.sampleflag & self.agnflag & ~self.membflag & self.dvflag]
point_flags=[self.bluesampleflag & ~self.agnflag & self.membflag,
self.bluesampleflag & self.agnflag & self.membflag,
self.bluesampleflag & ~self.agnflag & ~self.membflag & self.dvflag,
self.bluesampleflag & self.agnflag & ~self.membflag & self.dvflag]
bothax=[]
y=self.SFR_BEST*1.58 # convert from salpeter to chabrier IMF according to Salim+07
for i in range(4):
pl.subplot(2,2,i+1)
if clustername != None:
x_flags[i] = x_flags[i] & (self.s.CLUSTER == clustername)
point_flags[i] = point_flags[i] & (self.s.CLUSTER == clustername)
pl.plot(self.logstellarmass[x_flags[i]],y[x_flags[i]],'kx',markersize=8,label='No Fit')
sp=pl.scatter(self.logstellarmass[point_flags[i]],y[point_flags[i]],c=self.s.SIZE_RATIO[point_flags[i]],vmin=0.1,vmax=1,cmap='jet_r',s=60,label='GALFIT')
if (i == 0) | (i == 2):
xbin,ybin,ybinerr=my.binitbins(9.4,11.,(11.-9.4)/.2,self.logstellarmass[point_flags[i]],y[point_flags[i] ])
xbin,sbin,sbinerr=my.binitbins(9.4,11.,(11-9.4)/.2,self.logstellarmass[point_flags[i]],self.s.SIZE_RATIO[point_flags[i]])
#xbin,ybin,ybinerr=my.binit(self.logstellarmass[point_flags[i]],self.SFR_BEST[point_flags[i] ],5)
#xbin,sbin,sbinerr=my.binit(self.logstellarmass[point_flags[i]],self.s.SIZE_RATIO[point_flags[i]],5)
errorbar(xbin,ybin,yerr=ybinerr,fmt=None,color='k',markersize=16)
pl.scatter(xbin,ybin,c=sbin,s=300,cmap='jet_r',vmin=.1,vmax=1,marker='s')
pl.axis([9.1,11.75,7.e-2,32])
self.plotelbaz()
gca().set_yscale('log')
a=pl.gca()
bothax.append(a)
axvline(x=minmass,c='k',ls='--')
axhline(y=.086,c='k',ls='--')
#if i > 2:
# xlabel('$log_{10}(M_* (M_\odot)) $',fontsize=22)
if i == 0:
a.set_xticklabels(([]))
pl.text(0.1,0.9,'$Cluster$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
pl.title('$ SF \ Galaxies $',fontsize=22)
if i == 1:
a.set_xticklabels(([]))
a.set_yticklabels(([]))
pl.legend(loc='upper left',numpoints=1,scatterpoints=1)
pl.title('$AGN $',fontsize=22)
if i == 2:
text(0.1,0.9,'$Field$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
text(-0.2,1.,'$SFR \ (M_\odot/yr)$',transform=a.transAxes,rotation=90,horizontalalignment='center',verticalalignment='center',fontsize=24)
if i == 3:
a.set_yticklabels(([]))
text(-0.02,-.2,'$log_{10}(M_*/M_\odot)$',transform=a.transAxes,horizontalalignment='center',fontsize=24)
i += 1
c=colorbar(ax=bothax,fraction=.05)
c.ax.text(2.2,.5,'$R_e(24)/R_e(r)$',rotation=-90,verticalalignment='center',fontsize=20)
savefig(homedir+'research/LocalClusters/SamplePlots/SFRStellarmassSize.png')
savefig(homedir+'research/LocalClusters/SamplePlots/SFRStellarmassSize.eps')
def plotSFRStellarmassSizeBlue(self,clustername=None,blueflag=True,spiralflag=False,plotbadfits=True):
figure(figsize=(10,8))
baseflag = np.ones(len(self.sampleflag),'bool')
if blueflag:
baseflag = baseflag & self.blueflag2
if spiralflag:
baseflag = baseflag & self.spiralflag
subplots_adjust(left=.12,bottom=.15,wspace=.02,hspace=.02)
x_flags=[baseflag & ~self.sampleflag & ~self.agnflag & self.membflag,
baseflag & ~self.sampleflag & self.agnflag & self.membflag,
baseflag & ~self.sampleflag & ~self.agnflag & ~self.membflag & self.dvflag,
baseflag & ~self.sampleflag & self.agnflag & ~self.membflag & self.dvflag]
point_flags=[baseflag & self.sampleflag & ~self.agnflag & self.membflag,
baseflag & self.sampleflag & self.agnflag & self.membflag,
baseflag & self.sampleflag & ~self.agnflag & ~self.membflag & self.dvflag,
baseflag & self.sampleflag & self.agnflag & ~self.membflag & self.dvflag]
bothax=[]
y=self.SFR_BEST*1.58 # convert from salpeter to chabrier IMF according to Salim+07
for i in range(4):
pl.subplot(2,2,i+1)
if clustername != None:
x_flags[i] = x_flags[i] & (self.s.CLUSTER == clustername)
point_flags[i] = point_flags[i] & (self.s.CLUSTER == clustername)
if (i == 0) | (i==2):
if plotbadfits:
pl.plot(self.logstellarmass[x_flags[i]],y[x_flags[i]],'kx',markersize=8,label='No Fit')
sp=pl.scatter(self.logstellarmass[point_flags[i]],y[point_flags[i]],c=self.s.SIZE_RATIO[point_flags[i]],vmin=0.1,vmax=1,cmap='jet_r',s=60,label='GALFIT')
if (i == 1) | (i == 3):
xbin,ybin,ybinerr=my.binitbins(9.4,11.,(11.-9.4)/.2,self.logstellarmass[point_flags[i-1]],y[point_flags[i-1] ])
xbin,sbin,sbinerr=my.binitbins(9.4,11.,(11-9.4)/.2,self.logstellarmass[point_flags[i-1]],self.s.SIZE_RATIO[point_flags[i-1]])
#xbin,ybin,ybinerr=my.binit(self.logstellarmass[point_flags[i]],self.SFR_BEST[point_flags[i] ],5)
#xbin,sbin,sbinerr=my.binit(self.logstellarmass[point_flags[i]],self.s.SIZE_RATIO[point_flags[i]],5)
errorbar(xbin,ybin,yerr=ybinerr,fmt=None,color='k',markersize=16)
pl.scatter(xbin,ybin,c=sbin,s=300,cmap='jet_r',vmin=.2,vmax=.9,marker='s')
pl.axis([9.1,11.75,7.e-2,32])
self.plotelbaz()
gca().set_yscale('log')
a=pl.gca()
bothax.append(a)
axvline(x=minmass,c='k',ls='--')
axhline(y=.086,c='k',ls='--')
#if i > 2:
# xlabel('$log_{10}(M_* (M_\odot)) $',fontsize=22)
if i == 0:
a.set_xticklabels(([]))
pl.text(0.1,0.9,'$Cluster$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
pl.title('$ SF \ Galaxies $',fontsize=22)
if i == 1:
a.set_xticklabels(([]))
a.set_yticklabels(([]))
pl.legend(loc='upper left',numpoints=1,scatterpoints=1)
pl.title('$Median $',fontsize=22)
if i == 2:
text(0.1,0.9,'$Field$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
text(-0.2,1.,'$SFR \ (M_\odot/yr)$',transform=a.transAxes,rotation=90,horizontalalignment='center',verticalalignment='center',fontsize=24)
if i == 3:
a.set_yticklabels(([]))
text(-0.02,-.2,'$log_{10}(M_*/M_\odot)$',transform=a.transAxes,horizontalalignment='center',fontsize=24)
i += 1
c=colorbar(ax=bothax,fraction=.05,ticks=arange(.2,1,.1),format='%.1f')
c.ax.text(2.2,.5,'$R_e(24)/R_e(r)$',rotation=-90,verticalalignment='center',fontsize=20)
savefig(homedir+'research/LocalClusters/SamplePlots/SFRStellarmassSizeBlue.png')
savefig(homedir+'research/LocalClusters/SamplePlots/SFRStellarmassSizeBlue.eps')
def plotelbaz(self):
xe=arange(8.5,11.5,.1)
xe=10.**xe
ye=(.08e-9)*xe
plot(log10(xe),(ye),'k-',lw=1,label='$Elbaz+2011$')
plot(log10(xe),(2*ye),'k:',lw=1,label='$2 \ SFR_{MS}$')
def plotSFRStellarmassNUV24(self,clustername=None):
figure(figsize=(10,8))
subplots_adjust(left=.12,bottom=.15,wspace=.02,hspace=.02)
x_flags=[self.sfsampleflag & ~self.sampleflag & ~self.agnflag & self.membflag,
self.sfsampleflag & ~self.sampleflag & self.agnflag & self.membflag,
self.sfsampleflag & ~self.sampleflag & ~self.agnflag & ~self.membflag & self.dvflag,
self.sfsampleflag & ~self.sampleflag & self.agnflag & ~self.membflag & self.dvflag]
point_flags=[self.sampleflag & ~self.agnflag & self.membflag,
self.sampleflag & self.agnflag & self.membflag,
self.sampleflag & ~self.agnflag & ~self.membflag & self.dvflag,
self.sampleflag & self.agnflag & ~self.membflag & self.dvflag]
bothax=[]
for i in range(4):
pl.subplot(2,2,i+1)
if clustername != None:
x_flags[i] = x_flags[i] & (self.s.CLUSTER == clustername)
point_flags[i] = point_flags[i] & (self.s.CLUSTER == clustername)
pl.plot(self.logstellarmass[x_flags[i]],self.s.SFR_ZDIST[x_flags[i]],'kx',markersize=8,label='No Fit')
sp=pl.scatter(self.logstellarmass[point_flags[i]],self.s.SFR_ZDIST[point_flags[i]],c=self.s.SIZE_RATIO[point_flags[i]],vmin=0.1,vmax=1,cmap='jet_r',s=60,label='GALFIT')
if (i == 0) | (i == 2):
xbin,ybin,ybinerr=my.binit(self.logstellarmass[point_flags[i]],self.s.SFR_ZDIST[point_flags[i]],7)
xbin,sbin,sbinerr=my.binit(self.logstellarmass[point_flags[i]],self.s.SIZE_RATIO[point_flags[i]],7)
errorbar(xbin,ybin,yerr=ybinerr,fmt=None,color='k',markersize=16)
pl.scatter(xbin,ybin,c=sbin,s=300,cmap='jet_r',vmin=.1,vmax=1,marker='s')
pl.axis([9.1,11.75,7.e-2,32])
xe=arange(8.5,11.5,.1)
xe=10.**xe
ye=(.08e-9)*xe
plot(log10(xe),(ye),'k-',lw=1,label='$Elbaz+2011$')
plot(log10(xe),(2*ye),'k:',lw=1,label='$2 \ SFR_{MS}$')
gca().set_yscale('log')
a=pl.gca()
bothax.append(a)
axvline(x=9.3,c='k',ls='--')
axhline(y=.086,c='k',ls='--')
#if i > 2:
# xlabel('$log_{10}(M_* (M_\odot)) $',fontsize=22)
if i == 0:
a.set_xticklabels(([]))
pl.text(0.1,0.9,'$Cluster$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
pl.title('$ SF \ Galaxies $',fontsize=22)
if i == 1:
a.set_xticklabels(([]))
a.set_yticklabels(([]))
pl.legend(loc='upper left',numpoints=1,scatterpoints=1)
pl.title('$AGN $',fontsize=22)
if i == 2:
text(0.1,0.9,'$Field$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
text(-0.2,1.,'$SFR \ (M_\odot/yr)$',transform=a.transAxes,rotation=90,horizontalalignment='center',verticalalignment='center',fontsize=24)
if i == 3:
a.set_yticklabels(([]))
text(-0.02,-.2,'$log_{10}(M_*/M_\odot)$',transform=a.transAxes,horizontalalignment='center',fontsize=24)
i += 1
c=colorbar(ax=bothax,fraction=.05)
c.ax.text(2.2,.5,'$R_e(24)/R_e(r)$',rotation=-90,verticalalignment='center',fontsize=20)
savefig(homedir+'research/LocalClusters/SamplePlots/SFRStellarmassSize.png')
savefig(homedir+'research/LocalClusters/SamplePlots/SFRStellarmassSize.eps')
def plotSFRStellarmassSizeold(self):
figure(figsize=(10,5))
subplots_adjust(left=.12,bottom=.15,wspace=.05)
subplot(1,2,1)
flag=self.sfsampleflag & ~self.sampleflag & ~self.agnflag
plot(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],'kx',markersize=8,label='No Fit')
flag=self.sampleflag & ~self.agnflag & ~self.membflag
sp=scatter(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],c=self.s.SIZE_RATIO[flag],vmin=0,vmax=1,cmap='jet_r',s=50,label='GALFIT')
ax1=pl.gca()
pl.title('$ SF \ Galaxies $',fontsize=22)
pl.ylabel('$ SFR \ (M_\odot/yr) $')
subplot(1,2,2)
flag=self.sfsampleflag & ~self.sampleflag & self.agnflag
plot(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],'kx',markersize=8,label='No Fit')
flag=self.sampleflag & self.agnflag & ~self.membflag
sp=scatter(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],c=self.s.SIZE_RATIO[flag],vmin=0.1,vmax=1,cmap='jet_r',s=50,label='GALFIT')
ax2=pl.gca()
bothax=[ax1,ax2]
for a in bothax:
pl.sca(a)
axis([9.1,12,7.e-2,32])
xe=arange(8.5,11.5,.1)
xe=10.**xe
ye=(.08e-9)*xe
plot(log10(xe),(ye),'k-',lw=1,label='$Elbaz+2011$')
plot(log10(xe),(2*ye),'k:',lw=1,label='$2 \ SFR_{MS}$')
gca().set_yscale('log')
axvline(x=9.3,c='k',ls='--')
axhline(y=.086,c='k',ls='--')
xlabel('$log_{10}(M_* (M_\odot)) $',fontsize=22)
ax2.set_yticklabels(([]))
colorbar(ax=[ax1,ax2],fraction=.03)
legend(loc='upper left',numpoints=1,scatterpoints=1)
title('$AGN $',fontsize=22)
savefig(homedir+'research/LocalClusters/SamplePlots/SFRStellarmassSize.png')
savefig(homedir+'research/LocalClusters/SamplePlots/SFRStellarmassSize.eps')
def compare_elbaz(self):
pl.figure()
flag=self.sampleflag & self.agnflag & self.dvflag #& (self.s.SERSIC_N < 2.)
#pl.plot(self.sigma_ir[self.sampleflag & ~self.agnflag],s.ssfr[s.sampleflag & ~self.agnflag]*1.e9/.08,'bo')
pl.scatter(self.sigma_ir[flag],s.ssfr[flag]*1.e9/.08,c=self.s.DR_R200[flag],s=60,cmap='jet_r',vmin=0,vmax=1.5)
pl.colorbar(fraction=.08)
pl.gca().set_yscale('log')
pl.gca().set_xscale('log')
pl.subplots_adjust(bottom=.2,left=.15)
pl.axhline(y=2,ls='--')
pl.axvline(x=5.e9,ls='--')
pl.ylabel('$ sSFR/sSFR_{MS} $')
pl.xlabel('$\Sigma_{IR} = L_{IR}/(\pi R_e(24)^2) $')
def plotsSFRvsStellarmass(self,plotsingle=1,zoom=0,onepanel=0,farfield=0):
# log10(chabrier) = log10(Salpeter) - .25 (SFR estimate)
# log10(chabrier) = log10(diet Salpeter) - 0.1 (Stellar mass estimates)
if plotsingle:
if onepanel:
figure(figsize=(6,6))
subplots_adjust(bottom=.15,left=.15,right=.95,top=.95,hspace=.02,wspace=.02)
else:
figure(figsize=(12,4))
subplots_adjust(bottom=.2,left=.1,right=.95,top=.95,hspace=.02,wspace=.02)
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#axis([1.e9,1.e12,5.e-14,5.e-10])
#axis([9,12,-14.5,-10.5])
#xlabel('$ log_{10}(Stellar \ Mass \ (M_\odot)) $',fontsize=20)
#ylabel('$ log_{10}(SFR_{IR}/Stellar \ Mass \ (M_\odot)) $',fontsize=20)
legend(loc='upper left',numpoints=1)
colors=[log10(self.s.SIGMA_5),self.isosize]
colors=[(self.s.DR_R200),self.isosize]
colors=[self.isosize,self.s.SIZE_RATIO,(self.s.DR_R200)]
cbticks=[arange(-.5,2.2,.5),arange(0,2.5,.5),arange(0,2.5,.5)]
clabel=['$\Sigma_5$','$R_{iso}(24)/R_{iso}(r)$']
clabel=['$R_{iso}(24)/R_{iso}(r)$','$R_{e}(24)/R_{e}(r)$','$\Delta r/R_{200}$',]
cmaps=['jet_r','jet_r','jet_r']
v1=[0.2,0.2,0]
v2=[1.2,1.2,2]
nplot=1
x=(self.logstellarmass)#-.1
y=log10(self.s.SFR_ZDIST)# convert from salpeter to chabrier IMF
#y=log10(self.s.SFR_ZCLUST)-.2 # convert from salpeter to chabrier IMF
if onepanel:
nplots=1
else:
nplots=3
for i in range(nplots):
if not(onepanel):
subplot(1,3,nplot)
nplot +=1
ax=gca()
if i == 1:
flag=self.sampleflag & ~self.agnflag & self.dvflag
flag2=self.sampleflag & ~self.agnflag & ~self.dvflag
else:
flag=self.isosampleflag & ~self.agnflag & self.dvflag
flag2=self.isosampleflag & ~self.agnflag & ~self.dvflag
#sp=hexbin(x[flag],y[flag]-x[flag],C=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i],gridsize=10,alpha=0.5)#,extent=(0,2.,0,1.5))
sp=scatter(x[flag],y[flag]-x[flag],c=colors[i][flag],s=30,cmap=cmaps[i],vmin=v1[i],vmax=v2[i])
if farfield:
sp=scatter(x[flag2],y[flag2]-x[flag2],marker='*',c=colors[i][flag2],s=300,cmap=cmaps[i],vmin=v1[i],vmax=v2[i])
#scatter(x[self.outertruncflag & flag],y[self.outertruncflag & flag]-x[self.outertruncflag &flag],c=colors[i][self.outertruncflag & flag],marker='*',s=120)
#flag2=flag & self.truncflag
#scatter(x[flag2],y[flag2]-x[flag2],c=colors[i][flag2],marker='*',s=120)
#scatter(x[self.sampleflag],y[self.outertruncflag]-x[self.outertruncflag],c=colors[i][self.outertruncflag],marker='*',s=120)
xl=arange(9,11.5,.1)
yl=(-0.53*((xl)-10)-9.87)
#plot(xl,yl,'k-',label='Blue Galaxies (Salim+07)')
yl=(-0.35*((xl)-10)-9.83)
#plot(xl,yl,'k-',label='Pure SF (Salim+07)')
yl=log10(5.96e-11*10.**((-1.35+1)*(xl-11.03))*exp(-10.**(xl-11.03)))
plot(xl,yl,'r-',label='Salim+2007')
plot(xl,yl-.5,'r--',label='Salim-0.5dex')
#yl=(-0.35*((xl)-10)-10.)
#plot(xl,yl,'k-',label='Enhanced')
#plot(xl,yl-.92,'k--',label='Low sSFR')
#plot(xl,yl-1.4,'k:',label='Depleted')
'''
xl=arange(2.5e9,3.e11,5.e9)
xl=arange(9.5,11.5,.1)
#yl=10.**(-0.53*(log10(xl)-10)-9.87)
#yl=10.**(-0.35*(log10(xl)-10)-9.83)
yl=(-0.35*((xl)-10)-9.83)
plot(xl,yl,'k-',label='Salim+07')
plot(xl,yl-log10(8),'k--',label='Salim/8')
legend(prop={'size':12},numpoints=1)
# plot SF Main Sequence from Elbaz et al 2011
xl=arange(9,12,.1)
xl=10.**xl
yl=.25e-9*xl
plot(log10(xl),log10(yl)-log10(xl),'c-',lw=3,label='Elbaz+ 2011')
'''
# plot SF Main Sequence from Elbaz et al 2011
xl=arange(9.,11.5,.1)
xl=10.**xl
yl=.25e-9*xl
# plot SF Main Sequence from Elbaz et al 2011
xe=arange(9.,11.5,.1)
xe=10.**xe
ye=(.08e-9)*xe
plot(log10(xe),(ye),'k-',lw=1,label='Elbaz+2011')
text(8.3,ye[0]*2,'$\mathrm{Elbaz \ z=0}$',color='k',fontsize=14,horizontalalignment='left')
# subtract 0.25 dex from log10(yl) to convert from salpeter to chabrier IMF
# actually, don't need to correct b/c factor applies to both SFR and M*
#plot(log10(xl),log10(yl)-log10(xl),'c-',lw=3,label='Elbaz+2011')
if i == 0:
legend(loc='upper right',prop={'size':10},numpoints=1)
if zoom:
print 'zooming'
axis([8.5,12,-11.5,-9.7])
else:
if onepanel:
axis([8.9,11.9,-13.8,-8.9])
else:
axis([8.9,12.2,-13.8,-8.9])
if i > 0:
ax.set_yticklabels(([]))
axins1 = inset_axes(ax,
width="5%", # width = 10% of parent_bbox width
height="40%", # height : 50%
bbox_to_anchor=(.85,0.05,1,1),
bbox_transform=ax.transAxes,
borderpad=0,
loc=3)
cb=colorbar(sp,cax=axins1,ticks=cbticks[i])
text(.82,.05,clabel[i],transform=ax.transAxes,horizontalalignment='right',fontsize=18)
if onepanel:
ax.text(.5,-.1,'$ log_{10}(M_*/M_\odot) $',fontsize=22,transform=ax.transAxes,horizontalalignment='center')
ax.text(-.15,.5,'$ log_{10}(SFR/M_*) $',fontsize=22,transform=ax.transAxes,rotation=90,verticalalignment='center')
else:
ax.text(-.5,-.15,'$ log_{10}(M_*/M_\odot) $',fontsize=22,transform=ax.transAxes,horizontalalignment='center')
ax.text(-2.32,.5,'$ log_{10}(SFR/M_*) $',fontsize=22,transform=ax.transAxes,rotation=90,verticalalignment='center')
if zoom:
savefig(homedir+'research/LocalClusters/SamplePlots/sSFRvsStellarmass_zoom.png')
savefig(homedir+'research/LocalClusters/SamplePlots/sSFRvsStellarmass_zoom.eps')
else:
if onepanel:
savefig(homedir+'research/LocalClusters/SamplePlots/sSFRvsStellarmass_onepanel.png')
savefig(homedir+'research/LocalClusters/SamplePlots/sSFRvsStellarmass_onepanel.eps')
else:
savefig(homedir+'research/LocalClusters/SamplePlots/sSFRvsStellarmass.png')
savefig(homedir+'research/LocalClusters/SamplePlots/sSFRvsStellarmass.eps')
def plotSFRvsStellarmass2panel(self,plotsingle=1,showtrunc=0):
if plotsingle:
figure(figsize=(10,5))
ax=gca()
#ax.set_xscale('log')
ax.set_yscale('log')
axis([8.8,12,1.e-3,40.])
legend(loc='upper left',numpoints=1,prop={'size':10})
subplots_adjust(bottom=0.15,wspace=.02,right=.95)
subplot(1,2,1)
flag=self.membflag & ~self.agnflag & self.sampleflag #(self.s.p_cs > spiralcut)
for i in range(len(clusternames)):
cl=clusternames[i]
fflag=flag & (self.s.CLUSTER == cl)
plot(self.logstellarmass[fflag],self.s.SFR_ZDIST[fflag],'ko',color=colors[i],marker=shapes[i],label=cl,markersize=8)
xbin,ybin,ybinerr=my.binit(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],7)
xbin,ybin,ybinerr=my.binitbins(9.5,11,6,self.logstellarmass[flag],self.s.SFR_ZDIST[flag])
if showtrunc:
plot(self.logstellarmass[flag&self.truncflag],self.s.SFR_ZDIST[flag & self.truncflag],'k*',markersize=20)
#plot(xbin,ybin,'ro',markersize=10,label='_nolegend_')
#errorbar(xbin,ybin,ybinerr,fmt=None,ecolor='r')
legend(numpoints=1,loc='upper left',prop={'size':10})
gca().set_yscale('log')
limits=[8.6,11.8,.08,15]
axis(limits)
ylabel('$ SFR_{IR} \ (M_\odot/yr) $',fontsize=26)
text(.9,.9,'$Cluster $',fontsize=22,transform=gca().transAxes,horizontalalignment='right')
subplot(1,2,2)
flag= ~self.membflag & ~self.agnflag & self.sampleflag
plot(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],'b.',label='_nolegend_')
plot(xbin,ybin,'ro',markersize=10,label='Cluster')
errorbar(xbin,ybin,ybinerr,fmt=None,ecolor='r')
xbin,ybin,ybinerr=my.binit(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],7)
xbin,ybin,ybinerr=my.binitbins(9.5,11,6,self.logstellarmass[flag],self.s.SFR_ZDIST[flag])
plot(xbin,ybin,'bo',markersize=10,label='Field')
errorbar(xbin,ybin,ybinerr,fmt=None,ecolor='b')
gca().set_yscale('log')
legend(numpoints=1,loc='upper left',prop={'size':10})
axis(limits)
gca().set_yticklabels(([]))
text(.9,.9,'$Cluster \ vs. \ Field $',fontsize=22,transform=gca().transAxes,horizontalalignment='right')
text(-.05,-.15,'$ Stellar \ Mass \ (M_\odot) $',transform=gca().transAxes,horizontalalignment='center',fontsize=26)
savefig(homedir+'research/LocalClusters/SamplePlots/SFRvsStellarmass2panel.png')
savefig(homedir+'research/LocalClusters/SamplePlots/SFRvsStellarmass2panel.eps')
def plotSFRvsStellarmass(self,plotsingle=1,plotsize=False,plotagn=False):
if plotsingle:
pl.figure()
pl.subplots_adjust(bottom=.15,left=.15)
x=self.logstellarmass
msize=self.s.SIZE_RATIO
flag=self.sfsampleflag & self.membflag & ~self.agnflag
plot(self.logstellarmass[flag],self.SFR_BEST[flag],'k.')
#scatter(self.logstellarmass[flag],self.SFR_BEST[flag])
if plotsize:
#print self.s.SIZE_RATIO[flag]
#pl.scatter(self.logstellarmass[flag],self.SFR_BEST[flag],s=self.logstellarmass[flag],c='r')#,vmin=0.1,vmax=1.,cmap=cm.jet_r)
#colorbar(sp)
print 'skipping'
else:
plot(x[flag],self.SFR_BEST[flag],'r.',label='_nolegend_')
xbin,ybin,ybinerr=my.binitbins(9.3,11.3,9,x[flag],self.SFR_BEST[flag])
plot(xbin,ybin,'r^',markersize=12,label='Cluster')
errorbar(xbin,ybin,ybinerr,fmt=None,ecolor='r',label='_nolegend_')
# plot field
flag= ~self.membflag & self.sfsampleflag & ~self.agnflag#& ~self.AGNKAUFF #& ~self.agnflag
if plotsize:
print 'skipping'
#sp=scatter(x[flag],self.SFR_BEST[flag],c=self.s.SIZE_RATIO[flag],s='100',vmin=0.1,vmax=1.,cmap='jet_r')
else:
plot(x[flag],self.SFR_BEST[flag],'b.',label='_nolegend_')
xbin,ybin,ybinerr=my.binitbins(9.3,11.3,9,x[flag],self.SFR_BEST[flag])
plot(xbin,ybin,'b^',markersize=12,label='Field')
errorbar(xbin,ybin,ybinerr,fmt=None,ecolor='b',label='_nolegend_')
# plot SF Main Sequence from Elbaz et al 2011
xl=arange(9.,11.5,.1)
xl=10.**xl
yl=.08e-9*xl
#plot(log10(xl),(yl),'c-',lw=3,label='z=0 (Elbaz+2011)')
# plot SF Main Sequence from Elbaz et al 2011
xe=arange(9.,11.5,.1)
xe=10.**xe
ye=(.08e-9)*xe
plot(log10(xe),(ye),'k-',lw=1,label='Elbaz+2011')
legend(numpoints=1,loc='upper left')
if plotsingle:
ax=gca()
#ax.set_xscale('log')
ax.set_yscale('log')
axis([9.1,12,5.e-2,15.])
xlabel('$ Stellar \ Mass \ (M_\odot) $',fontsize=20)
ylabel('$ SFR_{IR} \ (M_\odot/yr) $',fontsize=20)
legend(loc='upper left',numpoints=1)
#text(9.3,ye[0]*2,'$\mathrm{Elbaz \ z=0}$',color='k',fontsize=14,horizontalalignment='left')
#savefig(homedir+'research/LocalClusters/SamplePlots/SFRvsStellarmass.png')
#savefig(homedir+'research/LocalClusters/SamplePlots/SFRvsStellarmass.eps')
def newfigure(self):
pl.figure(figsize=plotsize_2panel)
#pl.subplot(1,2,1)
extraflag=[self.membflag,~self.membflag]
markers=['o','s']
allax=[]
for i in range(2):
pl.subplot(1,2,i+1)
flag=self.sfsampleflag & ~self.agnflag & extraflag[i]
pl.scatter(self.logstellarmass[flag],self.SFR_BEST[flag],s=50.*self.s.SIZE_RATIO[flag],c='None',vmin=.1,vmax=1,marker=markers[i])
flag=self.sampleflag & ~self.agnflag & extraflag[i]
pl.scatter(self.logstellarmass[flag],self.SFR_BEST[flag],s=50.*self.s.SIZE_RATIO[flag],c=self.NUV24color[flag],vmin=1,vmax=4,cmap='jet',marker=markers[i])
pl.axis([9.2,11,.04,12])
pl.gca().set_yscale('log')
self.plotelbaz()
allax.append(pl.gca())
c=colorbar(ax=allax,fraction=.05)
c.ax.text(3.2,.5,'$NUV-24$',rotation=-90,verticalalignment='center',fontsize=20)
flag = self.sampleflag & ~self.agnflag & self.membflag
xbin,ybin,ybinerr=my.binitbinsmedian(9.3,11,7,self.logstellarmass[flag],self.SFR_BEST[flag])
xbin,sizebin,sizebinerr=my.binitbinsmedian(9.3,11,7,self.logstellarmass[flag],self.s.SIZE_RATIO[flag])
flag = self.sampleflag & ~self.agnflag & ~self.membflag
fxbin,fybin,fybinerr=my.binitbinsmedian(9.3,11,7,self.logstellarmass[flag],self.SFR_BEST[flag])
fxbin,fsizebin,fsizebinerr=my.binitbinsmedian(9.3,11,7,self.logstellarmass[flag],self.s.SIZE_RATIO[flag])
#print xbin,ybin,sizebin
#pl.subplot(1,2,2)
pl.figure(figsize=plotsize_2panel)
#for i in range(len(xbin)):print xbin[i],ybin[i],sizebin[i]
pl.subplot(1,2,1)
pl.scatter(xbin,ybin,s=250,c=sizebin,vmin=.1,vmax=1,marker='o',cmap='jet_r')
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None,color='k',markersize=20)
self.plotelbaz()
pl.axis([9.2,11,.04,12])
pl.gca().set_yscale('log')
pl.subplot(1,2,2)
#for i in range(len(xbin)):print xbin[i],ybin[i],sizebin[i]
pl.scatter(fxbin,fybin,s=100,c=fsizebin,vmin=.1,vmax=1,marker='s',cmap='jet_r')
pl.errorbar(fxbin,fybin,yerr=fybinerr,fmt=None,color='.5',markersize=20)
self.plotelbaz()
pl.axis([9.2,11,.04,12])
pl.gca().set_yscale('log')
c=colorbar(fraction=.08)
c.ax.text(3.2,.5,'$R_e(24)/R_e(r)$',rotation=-90,verticalalignment='center',fontsize=20)
def plotSFR24vsSFRJM(self):
figure(figsize=(10,5))
subplots_adjust(bottom=.15,wspace=.3,right=.95,left=.1)
subplot(1,2,1)
sfrjm=self.jmass.SFR100_AVG
flag=~self.agnflag
plot(log10(self.s.SFR_ZDIST[flag])-.2,sfrjm[flag],'k.')
xl=arange(-2.5,1.5,.1)
plot(xl,xl,'b-')
axis([-3,1,-6,1])
xlabel(r'$ SFR(Chary \ & \ Elbaz) \ (M_\odot/yr) $',fontsize=20)
ylabel('$ SFR(Moustakas) \ (M_\odot/yr) $',fontsize=20)
subplot(1,2,2)
plot(self.logstellarmass[flag],sfrjm[flag],'k.',label='Moustakas')
plot(self.logstellarmass[flag],log10(self.s.SFR_ZDIST[flag])-.2,'b.',label='Chary-Elbaz')
xlabel(r'$ M_*(Moustakas) \ (M_\odot/yr) $',fontsize=20)
ylabel('$ SFR \ (M_\odot/yr) $',fontsize=20)
legend(loc='upper left',numpoints=1,prop={'size':10})
axis([8,12,-6,1])
savefig(homedir+'research/LocalClusters/SamplePlots/CharyElbazvsMoustakas.png')
def plotRe24vsmag(self,plotsingle=1,sbcutobs=20.,absmagflag=0):
#print 'hi'
if plotsingle:
figure(figsize=(10,8))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
xlabel('$ m_{24}$',fontsize=20)
ylabel('$ R_e(24) \ (arcsec) $',fontsize=20)
#legend(loc='upper left',numpoints=1)
xmin=10.5
xmax=16.5
flag=(self.sampleflag)# & (self.sb_obs < sbcutobs)
#flag=ones(len(self.s.fcmag1),'bool')
x=(self.s.fcmag1[flag])
y=self.s.fcre1[flag]*mipspixelscale
if absmagflag:
x=x-self.distmod[flag]
xmin=-24.
xmax=-16.
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
if plotsingle:
colorbar(sp)
axis([xmin,xmax,.9,40.])
xl=arange(xmin+1,xmax-.3,.1)
yl=sqrt(1./pi*10**((sbcutobs-xl)/2.5))#/mipspixelscale
plot(xl,yl,'k--')
axhline(y=mipspixelscale,color='k',ls=':')
ax=pl.gca()
ax.set_yscale('log')
if plotsingle:
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRe24vsmag.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRe24vsmag.png')
def plotdsrsigma(self,flag,plotsingle=True):
if plotsingle:
pl.figure(figsize=plotsize_2panel)
pl.plot(self.s.SIGMA_5[flag],self.s.DR_R200[flag],'k.')
if plotsingle:
pl.xlabel('$\Sigma_5$')
pl.ylabel('$\Delta R/R_{200} $')
pl.axhline(y=1,c='k',ls='--')
pl.gca().set_yscale('log')
pl.gca().set_xscale('log')
pl.axis([0.1,100,0.008,8])
def plotsmoothnessBT(self):
pl.figure(figsize=plotsize_2panel)
pl.subplots_adjust(left=.12,bottom=.2,hspace=.0,wspace=.05)
limits=[-.05,.9,.0,.4]
allax=[]
flags=[self.sampleflag & ~self.agnflag & self.gim2dflag,
self.sampleflag & self.agnflag & self.gim2dflag]
titles=['$SF \ Galaxies $','$AGN $']
for i in range(len(flags)):
pl.subplot(1,2,i+1)
sp=pl.scatter(self.s.B_T_r[flags[i]],self.s.S2g_1[flags[i]],c=self.s.SIZE_RATIO[flags[i]],s=60,vmin=.1,vmax=1,cmap='jet_r')
pl.title(titles[i],fontsize=20)
#pl.gca().set_yscale('log')
pl.xlabel('$B/T$')
pl.axis(limits)
allax.append(pl.gca())
if i == 0:
pl.ylabel('$Smoothness $')
if i == 1:
pl.gca().set_yticklabels(([]))
pl.colorbar(ax=allax,fraction=.05)
savefig(homedir+'/research/LocalClusters/SamplePlots/plotsmoothBT.png')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotsmoothBT.eps')
def plotdrBT(self,usesersic=False,useagn=False):
pl.figure(figsize=plotsize_2panel)
pl.subplots_adjust(left=.1,bottom=.2)
limits=[-.05,.9,.04,6]
pl.subplot(1,2,1)
if usesersic:
x=self.s.SERSIC_N
limits=[-.1,6.1,.04,6.4]
if useagn:
flag= self.sampleflag
else:
flag= self.sampleflag & ~self.agnflag #& self.membflag
xl='$N\_SERSIC$'
else:
x=self.s.B_T_r
limits=[-.1,.9,.04,6.4]
if useagn:
flag= self.sampleflag & self.gim2dflag
else:
flag= self.sampleflag & self.gim2dflag & ~self.agnflag #& self.membflag
xl='$GIM2D \ B/T$'
flag = flag & self.dvflag
sp=pl.scatter(x[flag],self.s.DR_R200[flag],c=self.s.SIZE_RATIO[flag],s=60,vmin=0.1,vmax=1,cmap='jet_r')
pl.xlabel(xl)
pl.ylabel('$\Delta R/R_{200} $')
pl.gca().set_yscale('log')
pl.colorbar(sp,fraction=.08)
pl.text(.95,.9,'$R_e(24)/R_e(r) $',transform=gca().transAxes,horizontalalignment='right',fontsize=16)
pl.axis(limits)
if usesersic:
pl.gca().set_xscale('log')
pl.xlim(.2,7)
pl.subplot(1,2,2)
sp=pl.scatter(x[flag],self.s.DR_R200[flag],c=self.logstellarmass[flag],s=60,vmin=9.3,vmax=10.8,cmap='jet')
pl.xlabel(xl)
pl.gca().set_yscale('log')
if usesersic:
pl.gca().set_xscale('log')
pl.xlim(.2,7)
#ylabel('$\Delta R/R_{200} $',fontsize=24)
pl.text(.95,.9,'$log_{10}(M_*) $',transform=gca().transAxes,horizontalalignment='right',fontsize=16)
pl.colorbar(sp,fraction=.08)
pl.axis(limits)
savefig(homedir+'/research/LocalClusters/SamplePlots/plotdrBT.png')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotdrBT.eps')
def plotsigmaBT(self,usesersic=False):
pl.figure(figsize=(10,8))
pl.subplots_adjust(left=.12,bottom=.12,wspace=.01,hspace=.02)
if usesersic:
x=self.s.SERSIC_N
limits=[-.1,6.1,.1,40]
xl='$N\_SERSIC$'
else:
x=self.s.B_T_r
limits=[-.1,.9,.2,40]
xl='$GIM2D \ B/T$'
baseflag = self.sampleflag & self.gim2dflag & self.dvflag
colors=[self.s.SIZE_RATIO,self.logstellarmass]
sizeax=[]
mstarax=[]
allax=[]
for i in range(4):
pl.subplot(2,2,i+1)
if (i == 0) | (i == 2):
flag = baseflag & ~self.agnflag
if (i == 1) | (i == 3):
flag = baseflag & self.agnflag
if (i < 2):
col=colors[0]
v1=.1
v2=1
cm='jet_r'
else:
col=colors[1]
v1=mstarmin
v2=mstarmax
cm='jet'
sp=pl.scatter(x[flag],self.s.SIGMA_5[flag],c=col[flag],s=60,vmin=v1,vmax=v2,cmap=cm)
pl.gca().set_yscale('log')
#pl.colorbar(sp,fraction=.08)
pl.axis(limits)
allax.append(pl.gca())
a=pl.gca()
if i == 0:
a.set_xticklabels(([]))
#pl.text(0.1,0.9,'$Cluster$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
pl.title('$ SF \ Galaxies $',fontsize=22)
sizeax.append(a)
if i == 1:
a.set_xticklabels(([]))
a.set_yticklabels(([]))
#pl.legend(loc='lower left',numpoints=1,scatterpoints=1)
pl.title('$AGN $',fontsize=22)
sizeax.append(a)
c=colorbar(ax=sizeax,fraction=.02,shrink=.9,pad=.03)
c.ax.text(3.8,.5,'$R_e(24)/R_e(r)$',rotation=-90,verticalalignment='center',fontsize=20)
if i == 2:
#text(0.1,0.9,'$Field$',transform=a.transAxes,horizontalalignment='left',fontsize=20)
text(-0.2,1.,'$\Sigma_5 \ (gal/Mpc^2)$',transform=a.transAxes,rotation=90,horizontalalignment='center',verticalalignment='center',fontsize=24)
mstarax.append(a)
if i == 3:
a.set_yticklabels(([]))
text(-0.02,-.2,'$GIM2D \ B/T$',transform=a.transAxes,horizontalalignment='center',fontsize=24)
mstarax.append(a)
c=colorbar(ax=mstarax,fraction=.02,shrink=.9,pad=.03)
c.ax.text(3.8,.5,'$log_{10}(M_*/M_\odot)$',rotation=-90,verticalalignment='center',fontsize=20)
pl.axhline(y=10,color='k',ls='--')
#pl.colorbar(ax=allax,fraction=.05)
savefig(homedir+'/research/LocalClusters/SamplePlots/plotsigmaBT.png')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotsigmaBT.eps')
def plotLxBT(self,useagn=False,usesersic=False):
pl.figure(figsize=plotsize_2panel)
pl.subplots_adjust(left=.12,bottom=.2,wspace=.25)
if usesersic:
x=self.s.SERSIC_N
limits=[-.1,6.1,41.5,44.5]
if useagn:
flag= self.sampleflag
else:
flag= self.sampleflag & ~self.agnflag #& self.membflag
xl='$N\_SERSIC$'
else:
x=self.s.B_T_r
limits=[-.1,.3,41.5,44.5]
if useagn:
flag= self.sampleflag & self.gim2dflag
else:
flag= self.sampleflag & self.gim2dflag & ~self.agnflag #& self.membflag
xl='$GIM2D \ B/T$'
y=np.log10(self.s.CLUSTER_LX)+43.
pl.subplot(1,2,1)
flag = flag & self.dvflag
sp=pl.scatter(x[flag],y[flag],c=self.s.SIZE_RATIO[flag],s=60,vmin=0.1,vmax=1,cmap='jet_r')
pl.xlabel(xl)
pl.ylabel('$log_{10}(L_X) $')
#pl.gca().set_yscale('log')
pl.colorbar(sp,fraction=.08)
pl.text(.95,.9,'$R_e(24)/R_e(r) $',transform=gca().transAxes,horizontalalignment='right',fontsize=16)
pl.axis(limits)
pl.subplot(1,2,2)
sp=pl.scatter(x[flag],y[flag],c=self.logstellarmass[flag],s=60,vmin=9.3,vmax=10.8,cmap='jet')
pl.xlabel(xl)
#pl.gca().set_yscale('log')
#ylabel('$\Delta R/R_{200} $',fontsize=24)
pl.text(.95,.9,'$log_{10}(M_*) $',transform=gca().transAxes,horizontalalignment='right',fontsize=16)
pl.colorbar(sp,fraction=.08)
pl.axis(limits)
savefig(homedir+'/research/LocalClusters/SamplePlots/plotsigmaBT.png')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotsigmaBT.eps')
def plotphiBT(self,useagn=False,usesersic=False):
pl.figure(figsize=plotsize_2panel)
pl.subplots_adjust(left=.12,bottom=.2,wspace=.2)
allax=[]
if usesersic:
x=self.s.SERSIC_N
limits=[-.1,6.1,-2,92]
if useagn:
flag= self.sampleflag & self.membflag
else:
flag= self.sampleflag & ~self.agnflag & self.membflag#& self.membflag
xl='$N\_SERSIC$'
else:
x=self.s.B_T_r
limits=[-.1,.9,-2,92]
if useagn:
flag= self.sampleflag & self.gim2dflag & self.membflag
else:
flag= self.sampleflag & self.gim2dflag & ~self.agnflag & self.membflag #& self.membflag
xl='$GIM2D \ B/T$'
pl.subplot(1,2,1)
flag = flag & self.dvflag
sp=pl.scatter(x[flag],self.s.CLUSTER_PHI[flag],c=self.s.SIZE_RATIO[flag],s=60,vmin=0.1,vmax=1,cmap='jet_r')
pl.xlabel(xl)
pl.ylabel('$\Phi \ (degree) $')
#pl.gca().set_yscale('log')
#pl.colorbar(sp,fraction=.08)
pl.text(.95,.9,'$R_e(24)/R_e(r) $',transform=gca().transAxes,horizontalalignment='right',fontsize=16)
pl.axis(limits)
allax.append(pl.gca())
pl.subplot(1,2,2)
if useagn:
flag= self.sampleflag & self.membflag
else:
flag= self.sampleflag & self.membflag & ~self.agnflag
x=(self.s.SIGMA_5)
sp=pl.scatter(x[flag],self.s.CLUSTER_PHI[flag],c=(self.s.SIZE_RATIO[flag]),s=60,vmin=.1,vmax=1.,cmap='jet_r')
pl.xlabel('$\Sigma_5$')
#pl.gca().set_yscale('log')
#ylabel('$\Delta R/R_{200} $',fontsize=24)
pl.text(.95,.9,'$R_e(24)/R_e(r) $',transform=gca().transAxes,horizontalalignment='right',fontsize=16)
pl.gca().set_xscale('log')
allax.append(pl.gca())
pl.ylim(-2,92)
pl.xlim(.5,60)
pl.colorbar(ax=allax,fraction=.08)
#pl.xlim()
savefig(homedir+'/research/LocalClusters/SamplePlots/plotphiBT.png')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotphiBT.eps')
def plotRevsmag(self,plotsingle=1,sbcutobs=20.,absmagflag=0):
if plotsingle:
figure(figsize=(10,8))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
xlabel('$ m_{24}$',fontsize=20)
ylabel('$ R_e \ (arcsec) $',fontsize=20)
#legend(loc='upper left',numpoints=1)
xmin=10.5
xmax=16.5
flag=(self.sampleflag) #& (self.sb_obs < sbcutobs)
#flag=ones(len(self.s.fcmag1),'bool')
x=(self.s.fcmag1[flag])
if absmagflag:
x=x-self.distmod[flag]
xmin=-24.
xmax=-16.
y=self.s.SERSIC_TH50[flag]
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
if plotsingle:
colorbar(sp)
xl=arange(xmin+1,xmax-.3,.1)
yl=sqrt(1./pi*10**((sbcutobs-xl)/2.5))#/mipspixelscale
plot(xl,yl,'k--')
axis([xmin,xmax,.9,40.])
axhline(y=mipspixelscale,color='k',ls=':')
ax=pl.gca()
ax.set_yscale('log')
def plotRe24vsrmag(self,plotsingle=1,sbcutobs=20.):
#print 'hi'
if plotsingle:
figure(figsize=(10,8))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
xlabel('$ m_{24}$',fontsize=20)
ylabel('$ R_e(24) \ (arcsec) $',fontsize=20)
#legend(loc='upper left',numpoints=1)
axis([-22.5,-16.5,.9,40.])
flag=(self.sampleflag)# & (self.sb_obs < sbcutobs)
#flag=ones(len(self.s.fcmag1),'bool')
x=(self.s.ABSMAG[:,4][flag])
y=self.s.fcre1[flag]*mipspixelscale
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
if plotsingle:
colorbar(sp)
xl=arange(11.5,16.2,.1)
yl=sqrt(1./pi*10**((sbcutobs-xl)/2.5))#/mipspixelscale
plot(xl,yl,'k--')
axhline(y=mipspixelscale,color='k',ls=':')
ax=pl.gca()
ax.set_yscale('log')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRe24vsrmag.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRe24vsrmag.png')
def plotRevsrmag(self,plotsingle=1,sbcutobs=20.):
if plotsingle:
figure(figsize=(10,8))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
xlabel('$ ABS \ r$',fontsize=20)
ylabel('$ R_e \ (arcsec) $',fontsize=20)
#legend(loc='upper left',numpoints=1)
axis([-22.5,-16.5,.9,40.])
flag=(self.sampleflag) & (self.sb_obs < sbcutobs)
#flag=ones(len(self.s.fcmag1),'bool')
x=(self.s.ABSMAG[:,4][flag])
y=self.s.SERSIC_TH50[flag]
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
if plotsingle:
colorbar(sp)
xl=arange(11.5,16.2,.1)
yl=sqrt(1./pi*10**((sbcutobs-xl)/2.5))#/mipspixelscale
#plot(xl,yl,'k--')
axhline(y=mipspixelscale,color='k',ls=':')
ax=pl.gca()
ax.set_yscale('log')
def plotRevsmass(self,plotsingle=1,sbcutobs=20.,flag24=1,sbflag=0):
if plotsingle:
figure(figsize=(10,8))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
xlabel('$ log_{10}(M_*/M_\odot) $',fontsize=20)
if flag24:
ylabel('$ R_e(24) \ (arcsec) $',fontsize=20)
else:
ylabel('$ R_e(r) \ (arcsec) $',fontsize=20)
#legend(loc='upper left',numpoints=1)
axis([8.8,12.4,.9,40.])
flag=(self.sampleflag) & (self.sb_obs < sbcutobs)
#flag=ones(len(self.s.fcmag1),'bool')
if flag24:
y=self.s.fcre1[flag]*mipspixelscale
erry=self.s.fcre1[flag]*mipspixelscale
else:
flag=ones(len(self.s.SERSIC_TH50),'bool')
y=self.s.SERSIC_TH50[flag]
#erry=self.s.fcre1[flag]*mipspixelscale
x=(self.logstellarmass[flag])
if sbflag:
color=self.sb_obs[flag]
v1=sbmin
v2=sbmax
else:
color=log10(self.ssfr[flag])
v1=ssfrmin
v2=ssfrmax
sp=scatter(x,y,s=30,c=color,vmin=v1,vmax=v2)
if plotsingle:
colorbar(sp)
#xl=arange(8,12.2,.1)
#yl=sqrt(1./pi*10**((sbcutobs-xl)/2.5))#/mipspixelscale
#plot(xl,yl,'k--')
axhline(y=mipspixelscale,color='k',ls=':')
ax=pl.gca()
ax.set_yscale('log')
if plotsingle:
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRe24vsmass.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRe24vsmass.png')
def plotRisovsmass(self,plotsingle=1,sbcutobs=20.,flag24=1,sbflag=0):
if plotsingle:
figure(figsize=(10,8))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
xlabel('$ log_{10}(M_*/M_\odot) $',fontsize=20)
if flag24:
ylabel('$ R_iso(24) \ (arcsec) $',fontsize=20)
else:
ylabel('$ R_iso(r) \ (arcsec) $',fontsize=20)
#legend(loc='upper left',numpoints=1)
axis([8.8,12.4,2,75.])
flag=(self.isosampleflag) #& (self.sb_obs < sbcutobs)
#flag=ones(len(self.s.fcmag1),'bool')
x=log10(self.s.STELLARMASS[flag])
if flag24:
y=self.isorad.MIPS[flag]
erry=.3*y
else:
y=self.isorad.NSA[flag]
erry=.2*y
if sbflag:
color=self.sb_obs[flag]
v1=sbmin
v2=sbmax
else:
color=log10(self.ssfr[flag])
v1=-3.
v2=-.2
sp=scatter(x,y,s=30,c=color,vmin=v1,vmax=v2)
if plotsingle:
colorbar(sp)
xl=arange(8,12.5,.1)
yl=.28*(xl-10)+.9
plot(xl,10.**yl,'k--')
#plot(xl,.6*10.**yl,'k--')
#yl=sqrt(1./pi*10**((sbcutobs-xl)/2.5))#/mipspixelscale
#plot(xl,yl,'k--')
axhline(y=mipspixelscale,color='k',ls=':')
ax=pl.gca()
ax.set_yscale('log')
if plotsingle:
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRiso24vsmass.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRiso24vsmass.png')
def plotRe24vsRe(self,plotsingle=1,sbcutobs=20.,prefix=None,usemyflag=0,myflag=None,showerr=0,logy=True,fixPA=False):
#print 'hi'
if plotsingle:
figure(figsize=(10,8))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#axis([10.5,16.5,.9,60.])
xlabel('$ R_e(r) \ (arcsec)$',fontsize=20)
ylabel('$ R_e(24) \ (arcsec) $',fontsize=20)
#legend(loc='upper left',numpoints=1)
if usemyflag:
flag=myflag
else:
flag=self.sampleflag & (self.sb_obs < sbcutobs)
#flag=ones(len(self.s.fcmag1),'bool')
mflag=flag & self.membflag
fflag = flag & ~self.membflag
x=(self.s.SERSIC_TH50)
if fixPA:
y=self.s.fcre1*mipspixelscale
myerr=self.s.fcre1err*mipspixelscale
else:
y=self.s.fcre1*mipspixelscale
myerr=self.s.fcre1err*mipspixelscale
y=self.s.SUPER_RE1*mipspixelscale
myerr=self.s.SUPER_RE1ERR*mipspixelscale
if plotsingle:
print 'not printing errorbars'
else:
errorbar(x[flag],y[flag],yerr=myerr[flag],fmt=None,ecolor='k')
#color=self.sb_obs
#sp=scatter(x[mflag],y[mflag],s=100,marker='o',c=color[mflag],vmin=sbmin,vmax=sbmax)
#sp=scatter(x[fflag],y[fflag],s=100,marker='s',c=color[fflag],vmin=sbmin,vmax=sbmax)
color=self.logstellarmass
mstarmin=9.3
mstarmax=11
#color=self.s.DR_R200
#mstarmin=0
#mstarmax=2
#sp=scatter(x[flag & ~self.upperlimit],y[flag & ~self.upperlimit],s=100,marker='o',c=color[flag & ~self.upperlimit],vmin=mstarmin,vmax=mstarmax,cmap=cm.jet_r)
#sp=scatter(x[flag & self.upperlimit],y[flag & self.upperlimit],s=100,marker='v',c=color[flag & self.upperlimit],vmin=mstarmin,vmax=mstarmax,cmap=cm.jet_r)
sp=scatter(x[flag ],y[flag ],s=60,marker='o',c=color[flag ],vmin=mstarmin,vmax=mstarmax,cmap=cm.jet)
uflag = flag & self.upperlimit
print 'number of upper limits = ',sum(uflag)
uplimits=array(zip(ones(sum(uflag)), zeros(sum(uflag))))
errorbar(x[uflag],y[uflag],yerr=uplimits.T, lolims=True, fmt='*',ecolor='k',color='k',markersize=12)
#if 1.*sum(flag & self.upperlimit) > .1:
# sp=scatter(x[flag & self.upperlimit],y[flag & self.upperlimit],s=100,marker='v',c=color[flag & self.upperlimit],vmin=mstarmin,vmax=mstarmax,cmap=cm.jet_r)
#sp=scatter(x[fflag & ~self.upperlimit],y[fflag & ~self.upperlimit],s=60,marker='s',c=color[fflag & ~self.upperlimit],vmin=mstarmin,vmax=mstarmax)
#sp=scatter(x[fflag & self.upperlimit],y[fflag & self.upperlimit],s=60,marker='v',c=color[fflag & self.upperlimit],vmin=mstarmin,vmax=mstarmax)
if plotsingle:
colorbar(sp)
self.addlines(logflag=logy)
ax=pl.gca()
#axis([.1,30,.1,30])
if plotsingle:
#ax.set_yscale('log')
#ax.set_xscale('log')
#axis([1,130.,1,20.])
savefig(homedir+'research/LocalClusters/SamplePlots/plotRe24vsRestacked.eps')
savefig(homedir+'research/LocalClusters/SamplePlots/plotRe24vsRestacked.png')
def plotRiso24vsRiso(self,plotsingle=1,sbcutobs=20.,prefix=None,usemyflag=0,myflag=None,showerr=0,usesb=0):
#print 'hi'
if plotsingle:
figure(figsize=(10,8))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#axis([10.5,16.5,.9,60.])
xlabel('$ R_{iso}(r) \ (arcsec)$',fontsize=20)
ylabel('$ R_{iso}(24) \ (arcsec) $',fontsize=20)
#legend(loc='upper left',numpoints=1)
if usemyflag:
flag=myflag
else:
flag=self.isosampleflag #& ~self.agnflag#& (self.sb_obs < sbcutobs)
#flag=ones(len(self.s.fcmag1),'bool')
mflag=flag & self.membflag
fflag = flag & ~self.membflag
x=(self.isorad.NSA)
y=self.isorad.MIPS
myerr=.25*y
#if plotsingle:
# print 'not printing errorbars'
#else:
# errorbar(x[flag],y[flag],yerr=myerr[flag],fmt=None,ecolor='k')
if usesb:
color=self.sb_obs
v1=sbmin
v2=sbmax
else:
color=self.logstellarmass
v1=mstarmin
v2=mstarmax
#plot(x[mflag],y[mflag],'k.')
sp=scatter(x[mflag],y[mflag],s=60,marker='o',c=color[mflag],vmin=v1,vmax=v2)
sp=scatter(x[fflag],y[fflag],s=60,marker='^',c=color[fflag],vmin=v1,vmax=v2)
#if plotsingle:
# colorbar(sp)
xl=arange(0,60)
plot(xl,xl,'k-')
plot(xl,.7*xl,'k--')
#plot(xl,1.2*xl,'k:')
ax=pl.gca()
axis([-.2,30,-.2,30])
if plotsingle:
ax.set_yscale('log')
ax.set_xscale('log')
axis([1,130.,1,80.])
savefig(homedir+'research/LocalClusters/SamplePlots/plotRe24vsRestacked.eps')
savefig(homedir+'research/LocalClusters/SamplePlots/plotRe24vsRestacked.png')
def plotRe24vsRev2(self,plotsingle=1,sbcutobs=20.,prefix=None,usemyflag=0,myflag=None,showerr=0):
#print 'hi'
if plotsingle:
fig=figure(figsize=(12,6))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#axis([10.5,16.5,.9,60.])
xlabel('$ R_e(r) \ (arcsec)$',fontsize=20)
ylabel('$ R_e(24) \ (arcsec) $',fontsize=20)
#legend(loc='upper left',numpoints=1)
if usemyflag:
flag=myflag
else:
flag=self.sampleflag & ~self.agnflag #(self.sb_obs < sbcutobs)
#flag=ones(len(self.s.fcmag1),'bool')
mflag=flag & self.membflag
fflag = flag & ~self.membflag & self.dvflag
x=(self.s.SERSIC_TH50)
y=self.s.fcre1*mipspixelscale
myerr=self.s.fcre1err*mipspixelscale
if plotsingle:
print 'not printing errorbars'
else:
errorbar(x[flag],y[flag],yerr=myerr[flag],fmt=None,ecolor='k')
color=self.logstellarmass
subplots_adjust(bottom=.15,wspace=.02)
subplot(1,3,1)
if showerr:
errorbar(x[mflag],y[mflag],yerr=myerr[mflag],fmt=None,ecolor='k')
sp=scatter(x[mflag],y[mflag],s=100,marker='o',c=color[mflag],vmin=mstarmin,vmax=mstarmax)
cx=x[mflag]
cy=y[mflag]
ax1=gca()
self.addlines()
text(.1,.9,'$Cluster$',fontsize=18,horizontalalignment='left',transform=ax1.transAxes)
ylabel('$ R_e(24) \ (arcsec) $',fontsize=20)
subplot(1,3,2)
if showerr:
errorbar(x[fflag],y[fflag],yerr=myerr[fflag],fmt=None,ecolor='k')
sp=scatter(x[fflag],y[fflag],s=100,marker='^',c=color[fflag],vmin=mstarmin,vmax=mstarmax)
ax2=gca()
fx=x[fflag]
fy=y[fflag]
self.addlines()
text(.1,.9,'$Field$',fontsize=18,horizontalalignment='left',transform=ax2.transAxes)
text(-.05,-.14,'$R_e \ NSA \ (arcsec)$',fontsize=22,horizontalalignment='center',transform=ax2.transAxes)
#text(0,.-.2,'$ R_e(r) \ (arcsec)$',fontsize=20,transform=ax2.transAxes)#,horizontalalignment='center')
ax2.set_yticklabels(([]))
colorbar(ax=[ax1,ax2],fraction=.05)
subplots_adjust(right=0.8)
#subplot(1,3,3)
fig.add_axes([.72,.2,.25,.5])
mybins=arange(0,2,.1)
s1=cy/cx
s2=fy/fx
hist(cy/cx,bins=mybins,histtype='step',color='red',hatch='\\',label='$Cluster$')#,normed=True)
hist(fy/fx,bins=mybins,histtype='step',color='blue',hatch='/',label='$Field$')#,normed=True)
xlabel('$R_e(24)/R_e(NSA) $',fontsize=20)
axis([0,1.6,0,20])
legend(loc='upper left')
ks(s1,s2)
savefig(homedir+'research/LocalClusters/SamplePlots/plotRe24vsRestacked2panel.eps')
savefig(homedir+'research/LocalClusters/SamplePlots/plotRe24vsRestacked2panel.png')
def plotsizehist(self):
figure(figsize=plotsize_2panel)
pl.subplots_adjust(bottom=.2)
axes=[]
pl.subplot(1,2,1)
axes.append(pl.gca())
mybins=arange(0,2,.1)
hist(self.s.SIZE_RATIO[self.sampleflag & self.membflag & ~self.agnflag],bins=mybins,histtype='step',color='red',hatch='\\',label='$Cluster$')#,normed=True)
hist(self.s.SIZE_RATIO[self.sampleflag & ~self.membflag & ~self.agnflag],bins=mybins,histtype='step',color='blue',hatch='/',label='$Field$')#,normed=True)
pl.title('$ SF \ Galaxies $',fontsize=20)
pl.ylabel('$N_{gal}$')
print 'comparing cluster and field SF galaxies'
ks(self.s.SIZE_RATIO[self.sampleflag & self.membflag & ~self.agnflag],self.s.SIZE_RATIO[self.sampleflag & ~self.membflag & ~self.agnflag])
pl.subplot(1,2,2)
axes.append(pl.gca())
hist(self.s.SIZE_RATIO[self.sampleflag & self.membflag & self.agnflag],bins=mybins,histtype='step',color='red',hatch='\\',label='$Cluster$')#,normed=True)
hist(self.s.SIZE_RATIO[self.sampleflag & ~self.membflag & self.agnflag],bins=mybins,histtype='step',color='blue',hatch='/',label='$Field$')#,normed=True)
pl.title('$ AGN $',fontsize=20)
print 'comparing cluster and field AGN'
ks(self.s.SIZE_RATIO[self.sampleflag & self.membflag & self.agnflag],self.s.SIZE_RATIO[self.sampleflag & ~self.membflag & self.agnflag])
for a in axes:
pl.sca(a)
pl.axis([0,1.5,0,18])
pl.legend(loc='upper right')
pl.xlabel('$ R_e(24)/R_e(r) $')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizehist.eps')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizehist.png')
def plotRe24vsRev3(self,plotsingle=1,sbcutobs=20.,prefix=None,usemyflag=0,myflag=None,showerr=0):
#print 'hi'
if plotsingle:
figure(figsize=(10,6))
ax=gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#axis([10.5,16.5,.9,60.])
xlabel('$ R_e(r) \ (arcsec)$',fontsize=20)
ylabel('$ R_e(24) \ (arcsec) $',fontsize=20)
#legend(loc='upper left',numpoints=1)
if usemyflag:
flag=myflag
else:
flag=self.sampleflag & (self.sb_obs < sbcutobs)
#flag=ones(len(self.s.fcmag1),'bool')
flags=[self.zone1,self.zone2,self.zone3,self.zone4]
labels=['zone1','zone2','zone3','zone4']
subplots_adjust(wspace=.02)
allax=[]
for i in range(len(flags)):
subplot(1,4,i+1)
mflag=flag & flags[i]
x=(self.s.SERSIC_TH50)
y=self.s.fcre1*mipspixelscale
myerr=self.s.fcre1err*mipspixelscale
color=self.logstellarmass
if showerr:
errorbar(x[mflag],y[mflag],yerr=myerr[mflag],fmt=None,ecolor='k')
sp=scatter(x[mflag],y[mflag],s=100,marker='o',c=color[mflag],vmin=mstarmin,vmax=mstarmax)
if i == 0:
print x[mflag]
print y[mflag]
print myerr[mflag]
tflag = mflag & (myerr > .001)
b=fit_slope(x[tflag],y[tflag],yerr=myerr[tflag],yerrflag=1)
else:
b=fit_slope(x[mflag],y[mflag],yerr=myerr[mflag],yerrflag=1)
print labels[i],' intercept = ',b
print 'number of pts = ',sum(mflag)
xl=arange(1,30.,1)
plot(xl,xl*b,'r-')
ax1=gca()
self.addlines()
s='$'+labels[i]+'$'
text(.1,.9,s,fontsize=18,horizontalalignment='left',transform=ax1.transAxes)
allax.append(ax1)
if i == 0:
ylabel('$ R_e(24) \ (arcsec) $',fontsize=20)
if i > 0:
ax1.set_yticklabels(([]))
colorbar(ax=allax,fraction=.05)
savefig(homedir+'research/LocalClusters/SamplePlots/plotRe24vsRestacked4panel.eps')
savefig(homedir+'research/LocalClusters/SamplePlots/plotRe24vsRestacked4panel.png')
def addlines(self,logflag=True):
xl=arange(0,100,.5)
plot(xl,xl,'k-')
plot(xl,.68*xl,'k--')
#plot(xl,.45*xl,'k:')
if logflag:
ax=pl.gca()
ax.set_yscale('log')
ax.set_xscale('log')
axis([1,30.,1,30.])
def plotSFRvsStellarmassv2(self,plotsingle=1):
if plotsingle:
figure(figsize=(10,8))
ax=gca()
#ax.set_xscale('log')
ax.set_yscale('log')
axis([1.e9,1.e12,1.e-3,40.])
xlabel('$ Stellar \ Mass \ (M_\odot) $',fontsize=20)
ylabel('$ SFR_{IR} \ (M_\odot/yr) $',fontsize=20)
legend(loc='upper left',numpoints=1)
flag=self.mipsflag & ~self.agnflag
plot(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],'r.',label='_nolegend_')
xbin,ybin,ybinerr=my.binit(self.logstellarmass[flag],self.s.SFR_ZDIST[flag],7)
plot(xbin,ybin,'ro',markersize=10,label='Local Clusters')
errorbar(xbin,ybin,ybinerr,fmt=None,ecolor='r')
#flag=self.mipsflag & ~self.membflag & ~self.agnflag
#plot(self.s.STELLARMASS[flag],self.s.SFR_ZDIST[flag],'b.',label='_nolegend_')
#xbin,ybin,ybinerr=my.binit(self.s.STELLARMASS[flag],self.s.SFR_ZDIST[flag],7)
#plot(xbin,ybin,'bo',markersize=10,label='Field')
#errorbar(xbin,ybin,ybinerr,fmt=None,ecolor='b')
#flag=self.mipsflag & self.truncflag & self.sampleflag & ~self.agnflag
#plot(self.s.STELLARMASS[flag],self.s.SFR_ZDIST[flag],'k.',label='_nolegend_')
#xbin,ybin,ybinerr=my.binit(self.s.STELLARMASS[flag],self.s.SFR_ZDIST[flag],7)
#plot(xbin,ybin,'ko',markersize=10,label='Truncated')
#errorbar(xbin,ybin,ybinerr,fmt=None,ecolor='k')
def compare(self,var,baseflag=None,plotflag=0,xlab=None,plotname=None):
if baseflag == None:
f1 = self.membflag & ~self.agnflag
f2 = ~self.membflag &self.dvflag & ~self.agnflag
else:
f1=baseflag & self.membflag & ~self.agnflag
f2=baseflag & ~self.membflag & self.dvflag & ~self.agnflag
xmin=min(var[baseflag])
xmax=max(var[baseflag])
#print 'xmin, xmax = ',xmin,xmax
print 'KS test comparing members and field'
(D,p)=ks(var[f1],var[f2])
t=anderson.anderson_ksamp([var[f1],var[f2]])
print '%%%%%%%%% ANDERSON %%%%%%%%%%%'
print 'anderson statistic = ',t[0]
print 'critical values = ',t[1]
print 'p-value = ',t[2]
if plotflag:
pl.figure(figsize=(12,6))
pl.subplot(1,2,1)
pl.hist(var[f1],bins=len(var[f1]),cumulative=True,histtype='step',normed=True,label='Member',range=(xmin,xmax),color='r')
#print var[f2]
pl.hist(var[f2],bins=len(var[f2]),cumulative=True,histtype='step',normed=True,label='Field',range=(xmin,xmax),color='b')
pl.title('Member vs. Field ('+self.prefix+')')
pl.xlabel(xlab,fontsize=20)
pl.ylabel('$Cumulative \ Distribution $',fontsize=20)
legend(loc='lower right')
ylim(-.05,1.05)
ax=gca()
text(.05,.9,'$D = %4.2f$'%(D),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
if baseflag == None:
f1 = self.truncflag
f2 = ~self.truncflag
else:
f1=baseflag & self.truncflag
f2=baseflag & ~self.truncflag
print 'KS test comparing truncated and non-truncated spirals'
(D1,p1)=ks(var[f1],var[f2])
t=anderson.anderson_ksamp([var[f1],var[f2]])
print '%%%%%%%%% ANDERSON %%%%%%%%%%%'
print 'anderson statistic = ',t[0]
print 'critical values = ',t[1]
print 'p-value = ',t[2]
if plotflag:
pl.subplot(1,2,2)
pl.hist(var[f1],bins=len(var[f1]),cumulative=True,histtype='step',normed=True,label='Concentrated',range=(xmin,xmax),color='r')
pl.hist(var[f2],bins=len(var[f2]),cumulative=True,histtype='step',normed=True,label='Normal',range=(xmin,xmax),color='b')
title('Concentrated vs. Normal ('+self.prefix+')')
pl.xlabel(xlab,fontsize=20)
pl.ylabel('$Cumulative \ Distribution $',fontsize=20)
legend(loc='lower right')
ylim(-.05,1.05)
ax=gca()
text(.05,.9,'$D = %4.2f$'%(D1),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
text(.05,.8,'$p = %5.4f$'%(p1),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
figname=homedir+'research/LocalClusters/SamplePlots/'+plotname+'_'+str(self.prefix)+'_ks.png'
pl.savefig(figname)
return D, p, D1, p1
def compareiso(self,var,baseflag=None,plotflag=0,xlab=None,plotname=None):
if baseflag == None:
baseflag = self.isosampleflag
else:
baseflag = baseflag & self.isosampleflag
f1 = self.membflag & self.isosampleflag
f2 = ~self.membflag& self.isosampleflag
xmin=min(var[baseflag])
xmax=max(var[baseflag])
#print 'xmin, xmax = ',xmin,xmax
print 'KS test comparing members and field'
(D,p)=ks(var[f1],var[f2])
t=anderson.anderson_ksamp([var[f1],var[f2]])
print '%%%%%%%%% ANDERSON %%%%%%%%%%%'
print 'anderson statistic = ',t[0]
print 'critical values = ',t[1]
print 'p-value = ',t[2]
if plotflag:
pl.figure(figsize=(12,6))
pl.subplots_adjust(bottom=.15,left=.1,right=.95,top=.9,wspace=.25)
pl.subplot(1,2,1)
pl.hist(var[f1],bins=len(var[f1]),cumulative=True,histtype='step',normed=True,label='Member',range=(xmin,xmax),color='r')
#print var[f2]
pl.hist(var[f2],bins=len(var[f2]),cumulative=True,histtype='step',normed=True,label='Field',range=(xmin,xmax),color='b')
pl.title('Member vs. Field ('+self.prefix+')')
pl.xlabel(xlab,fontsize=20)
pl.ylabel('$Cumulative \ Distribution $',fontsize=20)
legend(loc='lower right')
ylim(-.05,1.05)
ax=gca()
text(.05,.9,'$D = %4.2f$'%(D),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
if baseflag == None:
baseflag=self.isosampleflag
else:
baseflag=baseflag & self.isosampleflag
f1 = baseflag & self.isotruncflag
f2 = baseflag & ~self.isotruncflag
print 'KS test comparing truncated and non-truncated spirals'
(D1,p1)=ks(var[f1],var[f2])
t=anderson.anderson_ksamp([var[f1],var[f2]])
print '%%%%%%%%% ANDERSON %%%%%%%%%%%'
print 'anderson statistic = ',t[0]
print 'critical values = ',t[1]
print 'p-value = ',t[2]
if plotflag:
pl.subplot(1,2,2)
pl.hist(var[f1],bins=len(var[f1]),cumulative=True,histtype='step',normed=True,label='Truncated',range=(xmin,xmax),color='r')
pl.hist(var[f2],bins=len(var[f2]),cumulative=True,histtype='step',normed=True,label='Normal',range=(xmin,xmax),color='b')
title('Truncated vs. Normal ('+self.prefix+')')
pl.xlabel(xlab,fontsize=20)
pl.ylabel('$Cumulative \ Distribution $',fontsize=20)
legend(loc='lower right')
ylim(-.05,1.05)
ax=gca()
text(.05,.9,'$D = %4.2f$'%(D1),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
text(.05,.8,'$p = %5.4f$'%(p1),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
figname=homedir+'research/LocalClusters/SamplePlots/'+plotname+'_'+str(self.prefix)+'_ks.png'
pl.savefig(figname)
return D, p, D1, p1
def plotHAEW(self):
keepflag=self.truncflag & self.sdssspecflag & self.sampleflag & ~self.agnflag
d1=self.s.HAEW[keepflag]
keepflag=~self.truncflag & self.sdssspecflag & self.sampleflag & ~self.agnflag
d2=self.s.HAEW[keepflag]
print 'KS comparing HA EW of truncated and non-truncated spirals (AGNFLAG)'
D,p=ks(d1,d2)
keepflag=self.truncflag & self.sdssspecflag & self.sampleflag & ~self.AGNKEWLEY
d1=self.s.HAEW[keepflag]
keepflag=~self.truncflag & self.sdssspecflag & self.sampleflag & ~self.AGNKEWLEY
d2=self.s.HAEW[keepflag]
print 'KS comparing HA EW of truncated and non-truncated spirals (AGNKEWLEY)'
D,p=ks(d1,d2)
keepflag=self.truncflag & self.sdssspecflag & self.sampleflag & ~self.agnflag
d1=self.s.HAEW[keepflag]
keepflag=~self.truncflag & self.sdssspecflag & self.sampleflag & ~self.agnflag
d2=self.s.HAEW[keepflag]
print 'KS comparing HA EW of truncated and non-truncated spirals (AGNFLAG)'
D,p=ks(d1,d2)
figure()#figsize=(10,7))
xmin=-5.
xmax=140.
pl.hist(d1,bins=len(d1),cumulative=True,range=(xmin,xmax),histtype='step',normed=True,label='Truncated',color='r')
pl.hist(d2,bins=len(d2),cumulative=True,range=(xmin,xmax),histtype='step',normed=True,label='Normal',color='b')
ax=gca()
pl.legend(loc='lower right')
text(.05,.9,'$D = %4.2f$'%(D),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
pl.axis([xmin,xmax,-.05,1.05])
pl.xlabel(r'$ H\alpha \ EW \ (Angstrom) $',fontsize=20)
pl.ylabel(r'$ Cumulative \ Distribution$',fontsize=20)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/HalphaCumulative.png')
def plotagn(self):
figure()
clf()
keepflag=self.sampleflag & self.sdssspecflag
keepflag=self.sdssspecflag
x=np.log10(self.s.N2FLUX/self.s.HAFLUX)
y=np.log10(self.s.O3FLUX/self.s.HBFLUX)
sp=pl.scatter(x[keepflag],y[keepflag],s=60,c=(self.s.SIZE_RATIO[keepflag]), cmap=cm.jet_r,vmax=1,label='_nolabel_')
pl.colorbar(sp)
#pl.plot(x[self.agnkewley],y[self.agnkewley],'co',markersize=12, label='_nolabel_')
pl.plot(x[self.AGNKAUFF & keepflag],y[self.AGNKAUFF & keepflag],'k*',mec='None',markersize=4, label='_nolabel_')
pl.plot(x[self.agnflag & keepflag],y[self.agnflag & keepflag],'k*',mec='None',markersize=14, label='_nolabel_')
#pl.plot(x[self.agnflag],y[self.agnflag],'ro',markersize=4, label='_nolabel_')
#draw AGN diagnostic lines
x=arange(-3,.4,.01)
y=(.61/(x-.47)+1.19)
#Kewley
plot(x,y,'c',label='Kewley & Dopita 2002')
x=arange(-3,.0,.01)
y =(.61/(x-.05)+1.3)#Kauffman 2003?
plot(x,y,'g',label='Kauffmann et al. 2003')
y = ((-30.787+(1.1358*x)+((.27297)*(x)**2))*tanh(5.7409*x))-31.093 #Stasinska 2006
plot(x,y,'r',label='Stasinska et al. 2006')
pl.axis([-1.5,.49,-1.,1.5])
pl.xlabel(r'$\log_{10}(NII/H\alpha)$',fontsize=20)
pl.ylabel(r'$\log_{10}(OIII/H\beta)$',fontsize=20)
pl.legend(loc='upper left',prop={'size':12})
pl.savefig(homedir+'research/LocalClusters/SamplePlots/AGNclassification.png')
def plotagnv2(self):
figure()
clf()
keepflag=self.emissionflag #sampleflag & self.sdssspecflag
x=np.log10(self.s.N2FLUX/self.s.HAFLUX)
y=np.log10(self.s.O3FLUX/self.s.HBFLUX)
plot(x[keepflag],y[keepflag],'ko',color='0.5',mec='0.5',alpha=0.5,label='_nolabel_')
keepflag=self.emissionflag & self.sampleflag & ~self.truncflag
plot(x[keepflag],y[keepflag],'bo',label='Normal')
keepflag=self.emissionflag & self.sampleflag & self.truncflag
plot(x[keepflag],y[keepflag],'ro',label='Truncated')
#keepflag=self.emissionflag & self.sampleflag & self.truncflag & ~self.agnflag
#plot(x[keepflag],y[keepflag],'g.',label='_nolabel_')
#draw AGN diagnostic lines
x=np.arange(-2,.4,.01)
y=(.61/(x-.47)+1.19)
#Kewley
pl.plot(x,y,'c',label='Kewley & Dopita 2002')
y =(.61/(x-.05)+1.3)#Kauffman 2003?
pl.plot(x[x<0],y[x<0],'g',label='Kauffmann et al. 2003')
y = ((-30.787+(1.1358*x)+((.27297)*(x)**2))*np.tanh(5.7409*x))-31.093 #Stasinska 2006
pl.plot(x,y,'r',label='Stasinska et al. 2006')
pl.axis([-1.5,.52,-1.5,1.5])
pl.xlabel(r'$\log_{10}(NII/H\alpha)$',fontsize=20)
pl.ylabel(r'$\log_{10}(OIII/H\beta)$',fontsize=20)
pl.legend(loc='upper left',prop={'size':12},numpoints=1)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/AGNclassification.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/AGNclassification.eps')
def plotwise(self):
figure(figsize=(12,6))
clf()
keepflag=self.sampleflag & self.sdssspecflag #& self.wiseflag
x=self.s.W3MAG_3-self.s.W4MAG_3
y=self.s.W1MAG_3-self.s.W2MAG_3
pl.subplots_adjust(wspace=.25,hspace=.35)
pl.subplot(1,2,1)
sp=pl.scatter(x[keepflag],y[keepflag],s=30,c=(self.sumagnflag[keepflag]), cmap=cm.jet,vmax=3,label='_nolabel_')
#pl.xlabel(r'$ [5.8] - [8.0]$',fontsize=20)
#pl.ylabel(r'$ [3.6] - [4.5]$',fontsize=20)
pl.xlabel(r'$ [12] - [22]$',fontsize=20)
pl.ylabel(r'$ [3.4] - [4.5]$',fontsize=20)
pl.axis([1,4.,-.3,.5])
pl.colorbar(sp)
pl.title('colorbar = AGN')
pl.subplot(1,2,2)
sp=pl.scatter(x[keepflag],y[keepflag],s=30,c=(self.s.SIZE_RATIO[keepflag]), cmap=cm.jet_r,vmax=1,label='_nolabel_')
pl.colorbar(sp)
pl.axis([1,4.,-.3,.5])
pl.xlabel(r'$ [5.8] - [8.0]$',fontsize=20)
pl.title('colorbar = size ratio')
#pl.plot(x[self.agnkewley],y[self.agnkewley],'co',markersize=12, label='_nolabel_')
#pl.plot(x[self.agnflag],y[self.agnflag],'go',markersize=8, label='_nolabel_')
#pl.plot(x[self.agnflag],y[self.agnflag],'ro',markersize=4, label='_nolabel_')
pl.legend(loc='upper left',prop={'size':12})
pl.savefig(homedir+'research/LocalClusters/SamplePlots/WISEcolor.png')
def plotwisecolorvssize(self):
figure(figsize=(10,4))
clf()
#keepflag=self.sampleflag & self.wiseflag #& self.sbflag
keepflag=self.wiseflag #& self.sbflag
#x=self.s.W2MAG_3-self.s.W3MAG_3
x=self.s.W1MAG_3-self.s.W2MAG_3
y=self.s.SIZE_RATIO
allax=[]
pl.subplots_adjust(bottom=.15,left=.1,right=.95,wspace=.3,hspace=.35)
pl.subplot(1,2,1)
allax.append(gca())
sp=pl.scatter(x[keepflag],y[keepflag],s=30,c=(self.logstellarmass[keepflag]), vmin=mstarmin,vmax=mstarmax,cmap=cm.jet,label='SF')
#pl.xlabel(r'$ [5.8] - [8.0]$',fontsize=20)
#pl.ylabel(r'$ [3.6] - [4.5]$',fontsize=20)
pl.xlabel(r'$ WISE \ [3.4] - [4.6]$',fontsize=20)
#pl.ylabel(r'$ [3.4] - [4.5]$',fontsize=20)
pl.ylabel(r'$ R_e(24)/R_e(r)$',fontsize=20)
pl.axis([-1,1,-.1,2])
pl.axvline(x=0.8,ls='--')
#pl.colorbar(sp)
#pl.title('colorbar = AGN')
pl.legend()
subplot(1,2,2)
allax.append(gca())
keepflag= self.agnflag & self.wiseflag
y=self.s.SIZE_RATIO
sp=pl.scatter(x[keepflag],y[keepflag],s=30,c=(self.logstellarmass[keepflag]), vmin=mstarmin,vmax=mstarmax,cmap=cm.jet,label='AGN')
pl.colorbar(sp,ax=allax,fraction=.1)
#pl.axis([1,4.,-.3,.5])
pl.axis([-1,1,-.1,2])
pl.axvline(x=0.8,ls='--')
pl.legend()
pl.ylabel(r'$ R_{iso}(24)/R_{iso}(r)$',fontsize=20)
pl.xlabel(r'$ WISE \ [3.4] - [4.6]$',fontsize=20)
#pl.title('colorbar = M*')
#pl.plot(x[self.agnkewley],y[self.agnkewley],'co',markersize=12, label='_nolabel_')
#pl.plot(x[self.agnflag],y[self.agnflag],'go',markersize=8, label='_nolabel_')
#pl.plot(x[self.agnflag],y[self.agnflag],'ro',markersize=4, label='_nolabel_')
#pl.legend(loc='upper left',prop={'size':12})
#pl.savefig(homedir+'research/LocalClusters/SamplePlots/WISEcolorsize.png')
def sizehist(self):
figure()
clf()
keepflag=self.sampleflag #& self.sdssspecflag #& self.wiseflag
t=(self.s.SIZE_RATIO[keepflag])
pl.hist(t,bins=40)
pl.xlabel(r'$ log_{10}(R_e(24)/R_e(r))$',fontsize=20)
pl.ylabel(r'$ Number$',fontsize=20)
pl.axvline(x=.5,ls='--',color='r')
xlim(0,2)
#pl.axis([1,4.,-.3,.5])
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizehist.png')
def sizeRe(self,sbcutobs=21.):
figure(figsize=(10,8))
clf()
flag=(~self.s['cnumerical_error_flag24']) & (self.sb_obs < sbcutobs) & (~self.agnflag)
y=(self.s.SIZE_RATIO[flag])
x=self.s.SERSIC_TH50[flag]
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color)
colorbar(sp)
pl.ylabel(r'$ R_e(24)/R_e(r)$',fontsize=20)
pl.xlabel(r'$ R_e(r)$',fontsize=20)
ax=pl.gca()
ax.set_xscale('log')
ax.set_yscale('log')
pl.axhline(y=.5,ls='--',color='k')
pl.axhline(y=1,ls='-',color='k')
#xlim(0,2)
pl.axis([1,150.,.01,5])
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeReall.png')
def plotsizedr(self,sbcutobs=20.5,usemass=1,usecolor=0,isoflag=0,blueflag=True):
figure(figsize=plotsize_single)
subplots_adjust(bottom=.15)
pl.clf()
#flag=(~self.s['cnumerical_error_flag24']) & (self.sb_obs < sbcutobs) & self.sampleflag
if blueflag:
flag= self.bluesampleflag & self.dvflag & ~self.agnflag
else:
flag= self.sampleflag & self.dvflag & ~self.agnflag
if isoflag:
flag=self.isosampleflag & self.dvflag
flag=self.sampleflag & self.dvflag
y=self.isorad.MIPS[flag]/self.isorad.NSA[flag]
ymin=0
ymax=2
ylab='$R_{iso}(24)/R_{iso}(r)$'
else:
y=(self.s.SIZE_RATIO[flag])
x=self.s.DR_R200[flag]
if usemass:
color=(self.logstellarmass[flag])
sp=pl.scatter(x,y,s=50,c=color,vmin=9.3,vmax=11.)
elif usecolor:
color=self.s.ABSMAG[:,3][flag]-self.s.ABSMAG[:,4][flag]
sp=pl.scatter(x,y,s=50,c=color,vmin=min(color),vmax=max(color))
else:
color=self.sb_obs[flag]
sp=pl.scatter(x,y,s=50,c=color,vmin=sbmin,vmax=sbmax)
colorbar(sp,fraction=.08)
if isoflag:
pl.ylabel(ylab,fontsize=24)
else:
pl.ylabel(r'$ R_e(24)/R_e(r)$',fontsize=18)
pl.xlabel(r'$ \Delta R/R_{200}$',fontsize=18)
ax=pl.gca()
pl.xticks(fontsize=12)
pl.yticks(fontsize=12)
#ax.set_xscale('log')
#ax.set_yscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
if isoflag:
pl.axis([0,3.5,ymin,ymax])
else:
pl.axis([0,3.5,.01,1.5])
xbin,ybin,ybinerr=my.binitbins(0,3.5,7,x,y)
print ybin
pl.plot(xbin,ybin,'ko',markersize=20)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
fieldflag = self.sampleflag & ~self.dvflag
if blueflag:
fieldflag = self.bluesampleflag & ~self.dvflag
field=mean(s.s.SIZE_RATIO[fieldflag])
fstd=std(s.s.SIZE_RATIO[fieldflag])/np.sqrt(1.*sum(fieldflag))
print 'field mean (far field) = ',field
pl.axhline(y=field,ls='-',color='k')
pl.axhline(y=field-fstd,ls='--',color='k')
pl.axhline(y=field+fstd,ls='--',color='k')
#pl.axhline(y=1,ls='-',color='k')
spearman(x,y)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizedr.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizedr.eps')
def plotsizeRe(self,sbcutobs=20.,usemass=0,usecolor=0):
figure(figsize=(10,8))
clf()
flag=(self.s.cnumerical_error_flag24 < 1.) & (self.sb_obs < sbcutobs) & self.sampleflag
flag= (self.sb_obs < sbcutobs) & self.sampleflag & self.dvflag & (self.sb_obs > 16)
y=(self.s.SIZE_RATIO[flag])
x=self.s.SERSIC_TH50[flag]
if usemass:
color=log10(self.s.STELLARMASS[flag])
sp=scatter(x,y,s=30,c=color,vmin=9,vmax=11.5)
elif usecolor:
color=self.s.ABSMAG[:,3][flag]-self.s.ABSMAG[:,4][flag]
sp=scatter(x,y,s=30,c=color,vmin=min(color),vmax=max(color))
else:
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
colorbar(sp)
pl.ylabel(r'$ R_e(24)/R_e(r)$',fontsize=20)
pl.xlabel(r'$R_e(r) \ (arcsec)$',fontsize=20)
ax=pl.gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
pl.axis([0,30,.01,1.5])
xbin,ybin,ybinerr=my.binitbins(0,20,7,x,y)
print ybin
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
field=mean(ybin[4:len(ybin)])
print 'field mean = ',field
pl.axhline(y=field,ls='--',color='k')
pl.axhline(y=1,ls='-',color='k')
spearman(x,y)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizedr.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizedr.eps')
def plotmassdr(self,sbcutobs=20.,usemass=0,usecolor=0):
figure(figsize=(10,8))
clf()
flag=(self.s.cnumerical_error_flag24 < 1.) & (self.sb_obs < sbcutobs) & self.sampleflag
flag= (self.sb_obs < sbcutobs) & self.sampleflag
y=log10(self.s.STELLARMASS[flag])
x=self.s.DR_R200[flag]
if usemass:
color=log10(self.s.STELLARMASS[flag])
sp=scatter(x,y,s=30,c=color,vmin=9,vmax=11.5)
elif usecolor:
color=self.s.ABSMAG[:,3][flag]-self.s.ABSMAG[:,4][flag]
sp=scatter(x,y,s=30,c=color,vmin=min(color),vmax=max(color))
else:
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
colorbar(sp)
pl.ylabel(r'$ M_* \ (M/M_\odot)$',fontsize=20)
pl.xlabel(r'$ \Delta R/R_{200}$',fontsize=20)
ax=pl.gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
pl.axis([0,3.5,9,12])
xbin,ybin,ybinerr=my.binit(x,y,5)
print ybin
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
field=mean(ybin[4:len(ybin)])
print 'field mean = ',field
pl.axhline(y=field,ls='--',color='k')
pl.axhline(y=1,ls='-',color='k')
spearman(x,y)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/massdr.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/massdr.eps')
def plotRedr(self,sbcutobs=20.,usemass=0,usecolor=0):
figure(figsize=(10,8))
clf()
flag=(self.s.cnumerical_error_flag24 < 1.) & (self.sb_obs < sbcutobs) & self.sampleflag
flag= (self.sb_obs < sbcutobs) & self.sampleflag
y=(self.s.SERSIC_TH50[flag])
x=self.s.DR_R200[flag]
if usemass:
color=log10(self.s.STELLARMASS[flag])
sp=scatter(x,y,s=30,c=color,vmin=9,vmax=11.5)
elif usecolor:
color=self.s.ABSMAG[:,3][flag]-self.s.ABSMAG[:,4][flag]
sp=scatter(x,y,s=30,c=color,vmin=min(color),vmax=max(color))
else:
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
colorbar(sp)
pl.ylabel(r'$ R_e(r) \ (arcsec)$',fontsize=20)
pl.xlabel(r'$ \Delta R/R_{200}$',fontsize=20)
ax=pl.gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
pl.axis([0,3.5,0,30])
xbin,ybin,ybinerr=my.binitbins(0,3.5,7,x,y)
print ybin
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
field=mean(ybin)
print 'field mean = ',field
pl.axhline(y=field,ls='--',color='k')
#pl.axhline(y=1,ls='-',color='k')
spearman(x,y)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/ReNSAdr.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/ReNSAdr.eps')
def plotsizemass(self,sbcutobs=20.,usemass=0):
figure(figsize=(10,8))
clf()
flag= (self.sb_obs < sbcutobs) & self.sampleflag & self.membflag
y=(self.s.SIZE_RATIO[flag])
x=(self.logstellarmass[flag])
if usemass:
color=log10(self.s.STELLARMASS[flag])
sp=scatter(x,y,s=30,c=color,vmin=9,vmax=11.5)
else:
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
colorbar(sp)
pl.ylabel(r'$ R_e(24)/R_e(r)$',fontsize=20)
pl.xlabel(r'$ M_* \ (M_\odot)$',fontsize=20)
ax=pl.gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
#pl.axis([9,12,.01,1.5])
xbin,ybin,ybinerr=my.binit(x,y,5)
print ybin
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
field=.682
pl.axhline(y=field,ls='--',color='k')
pl.axhline(y=1,ls='-',color='k')
spearman(x,y)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemass.eps')
def plotsizemassv2(self,sbcutobs=20.):
figure(figsize=(12,8))
clf()
flag= (self.sb_obs < sbcutobs) & self.sampleflag
yall=[(self.isorad.NSA[flag]),(self.isorad.MIPS[flag]),(self.s.SERSIC_TH50[flag]),(self.s.fcre1[flag]*mipspixelscale)]
ylabels=['$ R_{iso}(r) $','$ R_{iso}(24) $','$ R_{e}(r) $','$ R_{e}(24) $']
x=(self.logstellarmass[flag])
sb=self.sb_obs[flag]
subplots_adjust(wspace=.3,hspace=.3)
color=self.sb_obs[flag]
for i in range(len(yall)):
subplot(2,2,i+1)
y=yall[i]
ax=gca()
if i < 2:
ax.set_xticklabels(([]))
if i in [1,3]:
ax.set_yticklabels(([]))
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
xbin,ybin,ybinerr=my.binit(x,y,5)
pl.plot(xbin,ybin,'ko',markersize=12)
if i == 0:
xref=xbin
yref=ybin
else:
plot(xref,yref,'r')
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
spearman(x,y)
if i == 3:
xbin,ybin,ybinerr=my.binit(x[sb > 16],y[sb > 16],5)
pl.plot(xbin,ybin,'o',color='0.7',markersize=12)
spearman(x[sb > 16],y[sb > 16])
axhline(y=mipspixelscale,ls='--',color='k')
pl.xlabel(r'$ log_{10}(M_* \ (M_\odot))$',fontsize=20)
pl.ylabel(ylabels[i],fontsize=20)
gca().set_yscale('log')
axis([7.5,12,1,60])
#colorbar(sp)
ax=pl.gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#pl.axhline(y=.5,ls='--',color='k')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemass.eps')
def plotsizesb_all(self,sbcutobs=20.,usemass=0):
figure(figsize=(10,8))
clf()
flag = self.sampleflag
y=(self.s.SIZE_RATIO[flag])
x=(self.sb_obs[flag])
if usemass:
color=(self.logstellarmass[flag])
sp=scatter(x,y,s=30,c=color,vmin=mstarmin,vmax=mstarmax)
else:
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
colorbar(sp)
pl.ylabel(r'$ R_e(24)/R_e(r)$',fontsize=20)
pl.xlabel(r'$ \mu $',fontsize=20)
ax=pl.gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
pl.axis([sbmin,20.5,.01,1.5])
xbin,ybin,ybinerr=my.binit(x,y,5)
print ybin
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
field=.682
pl.axhline(y=field,ls='--',color='k')
pl.axhline(y=1,ls='-',color='k')
spearman(x,y)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemass.eps')
def plotsizessfr(self,sbcutobs=20.5,usemass=1,isoflag=0):
figure(figsize=(10,8))
clf()
flag= (self.sb_obs < sbcutobs) & self.sampleflag & ~self.agnflag #& self.dvflag
#flag = self.sampleflag
x=(self.s.SIZE_RATIO)
xerr=self.s.SIZE_RATIOERR
#x=self.s.fcre1*mipspixelscale/self.s.SERSIC_TH50
#xerr=self.s.fcre1err*mipspixelscale/self.s.SERSIC_TH50
xlab=r'$ R_e(24)/R_e(r)$'
if isoflag:
flag=self.isosampleflag & ~self.agnflag
y=(self.isosize[flag])
xlab='$R_{iso}(24)/R_{iso}(r) $'
y=(self.ssfr)
yerrp=(self.ssfrerr)
yerrm=(self.ssfrerr)
yerrpm=array(zip(yerrm,yerrp),'f')
if usemass:
color=(self.logstellarmass)
sp=scatter(x[flag],y[flag],s=80,c=color[flag],vmin=9,vmax=11.5,cmap=cm.jet)
errorbar(x[flag],y[flag],yerr=yerrpm[flag].T,xerr=xerr[flag],fmt=None,ecolor='k')
plot(x[flag & self.AGNKAUFF],y[flag & self.AGNKAUFF],'k*',mec='k',mfc='None',markersize=20)
#color=(self.logstellarmass[flag & self.membflag])
#sp=scatter(log10(self.ssfr[flag&self.membflag]),self.s.SIZE_RATIO[flag&self.membflag],s=120,c=color,marker='s',vmin=9,vmax=11.5)
else:
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
colorbar(sp,fraction=.08)
pl.axhline(y=(.08e-9),ls='-',color='k',lw=3)
gca().set_yscale('log')
pl.xlabel(xlab,fontsize=26)
pl.ylabel(r'$ sSFR \ (yr^{-1}) $',fontsize=26)
ax=pl.gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
#pl.axis([sbmin,20.5,.01,1.5])
xbin,ybin,ybinerr=my.binit(x,y,5)
#print ybin
#axis([-11.5,-9,0,2.7])
axis([0,2.7,10.**-11.5,10.**-9])
ax.tick_params(axis='both', which='major', labelsize=16)
#pl.plot(xbin,ybin,'ko',markersize=12)
#pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
#field=.682
#pl.axhline(y=field,ls='--',color='k')
#pl.axhline(y=1,ls='-',color='k')
spearman(x,y)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizesSFR.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizesSFR.eps')
def plotsizessfrv2(self,usemass=True):
pl.figure(figsize=plotsize_2panel)
pl.subplots_adjust(left=.1,bottom=.2,wspace=.08)
#pl.subplots_adjust(left=.1,bottom=.2,hspace=.01)
pl.clf()
flag= self.sampleflag & ~self.agnflag #& self.dvflag
#flag = self.sampleflag
y=(self.s.SIZE_RATIO)
yerr=self.s.SIZE_RATIOERR
#x=self.s.fcre1*mipspixelscale/self.s.SERSIC_TH50
#xerr=self.s.fcre1err*mipspixelscale/self.s.SERSIC_TH50
xlab=r'$ R_e(24)/R_e(r)$'
x=(self.ssfr)/.08e-9
xerrp=(self.ssfrerr)/.08e-9
xerrm=(self.ssfrerr)/.08e-9
xerrpm=array(zip(xerrm,xerrp),'f')
if usemass:
color=(self.logstellarmass)
v1=9.2
v2=11
#plot(x[flag & self.AGNKAUFF],y[flag & self.AGNKAUFF],'k*',mec='k',mfc='None',markersize=20)
#color=(self.logstellarmass[flag & self.membflag])
#sp=scatter(log10(self.ssfr[flag&self.membflag]),self.s.SIZE_RATIO[flag&self.membflag],s=120,c=color,marker='s',vmin=9,vmax=11.5)
else:
color=self.sb_obs[flag]
v1=sbmin
v2=sbmin
pl.subplot(1,2,1)
sp=pl.scatter(x[flag],y[flag],s=50,c=color[flag],vmin=v1,vmax=v2,cmap=cm.jet)
#errorbar(x[flag],y[flag],yerr=yerr[flag].T,xerr=xerrp[flag],fmt=None,ecolor='k')
ax1=gca()
pl.ylabel(xlab)#,fontsize=26)
subplot(1,2,2)
flag= self.sampleflag & self.agnflag #& self.dvflag
sp=scatter(x[flag],y[flag],s=50,c=color[flag],vmin=v1,vmax=v2,cmap=cm.jet)
#errorbar(x[flag],y[flag],yerr=yerr[flag].T,xerr=xerrp[flag],fmt=None,ecolor='k')
ax2=gca()
ax2.set_yticklabels(([]))
allax=[ax1,ax2]
colorbar(ax=allax,fraction=.03)
for a in allax:
pl.sca(a)
a.set_xscale('log')
pl.xlabel(r'$ sSFR/sSFR_{MS} $')#,fontsize=26)
axis([.01,10,0,2])
#spearman(x,y)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizesSFR.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizesSFR.eps')
def plotsizeBA(self,sbcutobs=20.,usemass=0,usecolor=0,isoflag=0):
figure(figsize=(10,8))
clf()
#flag=(self.s.cnumerical_error_flag24 < 1.) & (self.sb_obs < sbcutobs) & self.sampleflag
flag= self.sampleflag & ~self.agnflag
y=(self.s.SIZE_RATIO[flag])
ylab='$R_{e}(24)/R_{e}(r) $'
if isoflag:
flag=self.isosampleflag & ~self.agnflag
y=self.isosize[flag]
ylab='$R_{iso}(24)/R_{iso}(r) $'
x=self.s.SERSIC_BA[flag]
if usemass:
color=log10(self.s.STELLARMASS[flag])
sp=scatter(x,y,s=30,c=color,vmin=9,vmax=11.5)
elif usecolor:
color=self.s.ABSMAG[:,3][flag]-self.s.ABSMAG[:,4][flag]
sp=scatter(x,y,s=30,c=color,vmin=min(color),vmax=max(color))
else:
color=self.sb_obs[flag]
sp=scatter(x,y,s=30,c=color,vmin=sbmin,vmax=sbmax)
colorbar(sp)
pl.ylabel(ylab,fontsize=20)
pl.xlabel(r'$ NSA \ B/A$',fontsize=20)
ax=pl.gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
pl.axis([0,1.,.01,1.5])
xbin,ybin,ybinerr=my.binit(x,y,5)
print ybin
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
field=mean(ybin[4:len(ybin)])
print 'field mean = ',field
pl.axhline(y=field,ls='--',color='k')
pl.axhline(y=1,ls='-',color='k')
spearman(x,y)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBA.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBA.eps')
def plotsizeBTold(self,sbcutobs=20.,usemass=1,usecolor=0,usesersic=False,useagn=False):
pl.figure(figsize=plotsize_2panel)
pl.subplots_adjust(bottom=.2,left=.12)
pl.clf()
#flag=(self.s.cnumerical_error_flag24 < 1.) & (self.sb_obs < sbcutobs) & self.sampleflag
y=(self.s.SIZE_RATIO)
if usesersic:
x=self.s.SERSIC_N
axrange=[-.1,6.,.01,1.5]
if useagn:
flag= self.sampleflag
else:
flag= self.sampleflag & ~self.agnflag #& self.membflag
xl='$N\_SERSIC$'
else:
x=self.s.B_T_r
axrange=[-.1,1.,.01,1.5]
if useagn:
flag= self.sampleflag & self.gim2dflag
else:
flag= self.sampleflag & self.gim2dflag & ~self.agnflag #& self.membflag
xl='$GIM2D \ B/T$'
pl.subplot(1,2,1)
allax=[]
if usemass:
color=(self.logstellarmass)
v1=9.3
v2=11.
elif usecolor:
color=self.s.ABSMAG[:,3]-self.s.ABSMAG[:,4]
v1=min(color)
v2=max(color)
else:
color=self.sb_obs[flag]
v1=sbmin
v2=sbmax
sp=pl.scatter(x[flag],y[flag],s=100,c=color[flag],vmin=v1,vmax=v2)
allax.append(pl.gca())
pl.ylabel(r'$ R_e(24)/R_e(r)$')#,fontsize=20)
pl.title('$SF \ Galaxies $',fontsize=20)
rho,p=spearman(x[flag],y[flag])
ax=pl.gca()
pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.subplot(1,2,2)
flag= self.sampleflag & self.gim2dflag & self.agnflag #& self.membflag
sp=pl.scatter(x[flag],y[flag],s=100,c=color[flag],vmin=v1,vmax=v2)
pl.title('$AGN $',fontsize=20)
rho,p=spearman(x[flag],y[flag])
ax=pl.gca()
pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
allax.append(pl.gca())
for a in allax:
pl.sca(a)
pl.xlabel(r'$ GIM2D \ B/T$')#,fontsize=20)
pl.axis([-.1,1.,.01,1.5])
#xbin,ybin,ybinerr=my.binitbins(0,.5,5,x,y)
#print ybin
#pl.plot(xbin,ybin,'ko',markersize=18)
#pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
pl.colorbar(ax=allax,fraction=.03)
#xlim(0,2)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBTold.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBTold.eps')
def plotsizeclusterphi2(self,sbcutobs=20.,usemass=0,usecolor=1,useagn=False):
pl.figure(figsize=plotsize_2panel)
pl.subplots_adjust(bottom=.2,left=.12,wspace=.02)
pl.clf()
#flag=(self.s.cnumerical_error_flag24 < 1.) & (self.sb_obs < sbcutobs) & self.sampleflag
y=(self.s.SIZE_RATIO)
x=self.s.CLUSTER_PHI
limits=[-5,95,.01,1.5]
fieldflag=self.sampleflag & self.dvflag & ~self.membflag & ~self.agnflag #& self.membflag
field=mean(y[fieldflag])
fielderr=std(y[fieldflag])/sqrt(1.*sum(fieldflag))
xl='$\psi \ (degrees)$'
pl.subplot(1,2,1)
flag= self.sampleflag & self.membflag & ~self.agnflag #& self.membflag
allax=[]
if usemass:
color=(self.logstellarmass)
v1=9.3
v2=11.
elif usecolor:
color=self.s.ABSMAG[:,2]-self.s.ABSMAG[:,4]
v1=1
v2=3.
else:
color=self.sb_obs[flag]
v1=sbmin
v2=sbmax
sp=pl.scatter(x[flag],y[flag],s=100,c=color[flag],vmin=v1,vmax=v2)
pl.axhline(y=field,ls='-',color='k')
pl.axhline(y=field+fielderr,ls='--',color='k')
pl.axhline(y=field-fielderr,ls='--',color='k')
allax.append(pl.gca())
pl.ylabel(r'$ R_e(24)/R_e(r)$')#,fontsize=20)
pl.title('$SF \ Galaxies $',fontsize=20)
#rho,p=spearman(x[flag],y[flag])
ax=pl.gca()
#pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
#pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
#f2=flag & (self.logstellarmass < 10.4) #& (self.s.B_T_r < 0.2)
#print 'for log(M) < 10.4 galaxies only:'
#rho,p=spearman(x[f2],y[f2])
f2=flag & self.blueflag #
print 'for blue galaxies only:'
rho,p=spearman(x[f2],y[f2])
print 'ks test comparing psi < 30 and psi > 30'
ks(y[flag & (x < 30.)],y[flag & (x>30)])
pl.subplot(1,2,2)
flag= self.sampleflag & self.membflag & self.agnflag #& self.membflag
fieldflag= self.sampleflag & ~self.membflag & self.dvflag & self.agnflag #& self.membflag
field=mean(y[fieldflag])
fielderr=std(y[fieldflag])/sqrt(1.*sum(fieldflag))
pl.axhline(y=field,ls='-',color='k')
pl.axhline(y=field+fielderr,ls='--',color='k')
pl.axhline(y=field-fielderr,ls='--',color='k')
sp=pl.scatter(x[flag],y[flag],s=100,c=color[flag],vmin=v1,vmax=v2)
pl.title('$AGN $',fontsize=20)
#rho,p=spearman(x[flag],y[flag])
ax=pl.gca()
ax.set_yticklabels(([]))
#pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
#pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
allax.append(pl.gca())
for a in allax:
pl.sca(a)
pl.xlabel(xl)#,fontsize=20)
pl.axis(limits)
#xbin,ybin,ybinerr=my.binitbins(0,.5,5,x,y)
#print ybin
#pl.plot(xbin,ybin,'ko',markersize=18)
#pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
pl.colorbar(ax=allax,fraction=.03)
#xlim(0,2)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeclusterphi2.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeclusterphi2.eps')
def plotsizemassdens2panel(self,sbcutobs=20.,usemass=1,usecolor=0):
pl.figure(figsize=plotsize_2panel)
pl.subplots_adjust(bottom=.2,left=.12)
pl.clf()
#flag=(self.s.cnumerical_error_flag24 < 1.) & (self.sb_obs < sbcutobs) & self.sampleflag
y=(self.s.SIZE_RATIO)
x=self.massdensity
pl.subplot(1,2,1)
flag= self.sampleflag & ~self.agnflag #& self.membflag
allax=[]
if usemass:
color=(self.logstellarmass)
v1=9.3
v2=11.
elif usecolor:
color=self.s.ABSMAG[:,3]-self.s.ABSMAG[:,4]
v1=min(color)
v2=max(color)
else:
color=self.sb_obs[flag]
v1=sbmin
v2=sbmax
sp=pl.scatter(x[flag],y[flag],s=100,c=color[flag],vmin=v1,vmax=v2)
allax.append(pl.gca())
pl.ylabel(r'$ R_e(24)/R_e(r)$')#,fontsize=20)
pl.title('$SF \ Galaxies $',fontsize=20)
rho,p=spearman(x[flag],y[flag])
ax=pl.gca()
pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.subplot(1,2,2)
flag= self.sampleflag & self.agnflag #& self.membflag
sp=pl.scatter(x[flag],y[flag],s=100,c=color[flag],vmin=v1,vmax=v2)
rho,p=spearman(x[flag],y[flag])
ax=pl.gca()
pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.title('$AGN $',fontsize=20)
for a in allax:
pl.sca(a)
pl.xlabel(r'$log_{10}(M_*/\pi R_e^2)$')#,fontsize=20)
pl.axis([6,10.,.01,1.5])
#xbin,ybin,ybinerr=my.binitbins(0,.5,5,x,y)
#print ybin
#pl.plot(xbin,ybin,'ko',markersize=18)
#pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
pl.colorbar(ax=allax,fraction=.03)
#xlim(0,2)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemassdens2panel.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemassdens2panel.eps')
def plotsizemassradius2panel(self,sbcutobs=20.,usemass=1,usecolor=0):
pl.figure(figsize=plotsize_2panel)
pl.subplots_adjust(bottom=.2,left=.12)
pl.clf()
#flag=(self.s.cnumerical_error_flag24 < 1.) & (self.sb_obs < sbcutobs) & self.sampleflag
y=(self.s.SIZE_RATIO)
x=self.logstellarmass - np.log10(self.s.SERSIC_TH50*self.DA)
pl.subplot(1,2,1)
flag= self.sampleflag & ~self.agnflag #& self.membflag
allax=[]
if usemass:
color=(self.logstellarmass)
v1=9.3
v2=11.
elif usecolor:
color=self.s.ABSMAG[:,3]-self.s.ABSMAG[:,4]
v1=min(color)
v2=max(color)
else:
color=self.sb_obs[flag]
v1=sbmin
v2=sbmax
sp=pl.scatter(x[flag],y[flag],s=100,c=color[flag],vmin=v1,vmax=v2)
allax.append(pl.gca())
pl.ylabel(r'$ R_e(24)/R_e(r)$')#,fontsize=20)
pl.title('$SF \ Galaxies $',fontsize=20)
rho,p=spearman(x[flag],y[flag])
ax=pl.gca()
pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.subplot(1,2,2)
flag= self.sampleflag & self.agnflag #& self.membflag
sp=pl.scatter(x[flag],y[flag],s=100,c=color[flag],vmin=v1,vmax=v2)
pl.title('$AGN $',fontsize=20)
allax.append(pl.gca())
rho,p=spearman(x[flag],y[flag])
ax=pl.gca()
pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
for a in allax:
pl.sca(a)
pl.xlabel(r'$log_{10}(M_*/ R_e)$')#,fontsize=20)
pl.axis([8,11.,.01,1.5])
#xbin,ybin,ybinerr=my.binitbins(0,.5,5,x,y)
#print ybin
#pl.plot(xbin,ybin,'ko',markersize=18)
#pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
pl.colorbar(ax=allax,fraction=.03)
#xlim(0,2)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemassradius.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemassradius.eps')
def plotsizeNsersic(self,sbcutobs=20.,usemass=1,usecolor=0):
pl.figure(figsize=plotsize_2panel)
pl.subplots_adjust(bottom=.2,left=.12)
pl.clf()
#flag=(self.s.cnumerical_error_flag24 < 1.) & (self.sb_obs < sbcutobs) & self.sampleflag
y=(self.s.SIZE_RATIO)
x=self.s.SERSIC_N
pl.subplot(1,2,1)
flag= self.sampleflag & ~self.agnflag #& self.membflag
allax=[]
if usemass:
color=(self.logstellarmass)
v1=9.3
v2=11.
elif usecolor:
color=self.s.ABSMAG[:,3]-self.s.ABSMAG[:,4]
v1=min(color)
v2=max(color)
else:
color=self.sb_obs[flag]
v1=sbmin
v2=sbmax
sp=pl.scatter(x[flag],y[flag],s=100,c=color[flag],vmin=v1,vmax=v2)
allax.append(pl.gca())
pl.ylabel(r'$ R_e(24)/R_e(r)$')#,fontsize=20)
pl.title('$SF \ Galaxies $',fontsize=20)
rho,p=spearman(x[flag],y[flag])
ax=pl.gca()
pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.subplot(1,2,2)
flag= self.sampleflag & self.agnflag #& self.membflag
sp=pl.scatter(x[flag],y[flag],s=100,c=color[flag],vmin=v1,vmax=v2)
rho,p=spearman(x[flag],y[flag])
ax=pl.gca()
pl.text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=18)
pl.title('$AGN $',fontsize=20)
allax.append(pl.gca())
for a in allax:
pl.sca(a)
pl.xlabel(r'$ N\_ SERSIC$')#,fontsize=20)
pl.axis([-.1,7.,.01,1.5])
#xbin,ybin,ybinerr=my.binitbins(0,.5,5,x,y)
#print ybin
#pl.plot(xbin,ybin,'ko',markersize=18)
#pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
pl.colorbar(ax=allax,fraction=.03)
#xlim(0,2)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeNsersic.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeNsersic.eps')
def plotsizeHImass(self,sbcutobs=20.5,isoflag=0,r90flag=0):
figure(figsize=plotsize_single)
clf()
flag = self.sampleflag & (self.HIflag) & ~self.agnflag
print 'number of galaxies = ',sum(flag)
y=(self.s.SIZE_RATIO[flag])
x=np.log10(self.s.HIMASS[flag])
#color=self.logstellarmass[flag]
color=self.logstellarmass[flag]
sp=scatter(x,y,s=90,c=color,vmin=mstarmin,vmax=mstarmax)
rho,p=spearman(x,y)
ax=pl.gca()
text(.75,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=22)
text(.75,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=22)
print 'spearman for log(M*) < 10.41'
rho,p=spearman(x[color < 10.41],y[color<10.41])
colorbar(sp,fraction=.08)
pl.ylabel(r'$ R_e(24)/R_e(r)$')#,fontsize=26)
pl.xlabel(r'$ HI \ Mass$')#,fontsize=26)
#ax.tick_params(axis='both', which='major', labelsize=16)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeHImass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeHImass.eps')
def plotsizeHIfrac(self,sbcutobs=20.5,isoflag=0,r90flag=0):
pl.figure(figsize=plotsize_single)
pl.subplots_adjust(bottom=.2,left=.15)
pl.clf()
flag = self.sampleflag & (self.HIflag) & self.dvflag #& ~self.agnflag
print 'number of galaxies = ',sum(flag)
y=(self.s.SIZE_RATIO[flag])
x=np.log10(self.s.HIMASS[flag])-self.logstellarmass[flag]
#color=self.logstellarmass[flag]
color=self.logstellarmass[flag]
sp=pl.scatter(x,y,s=90,c=color,vmin=mstarmin,vmax=mstarmax)
rho,p=spearman(x,y)
ax=pl.gca()
text(.95,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='right',transform=ax.transAxes,fontsize=16)
text(.95,.8,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=16)
print 'spearman for log(M*) < 10.41'
rho,p=spearman(x[color < 10.41],y[color<10.41])
pl.colorbar(sp,fraction=.08)
pl.ylabel(r'$ R_e(24)/R_e(r)$')
pl.xlabel(r'$ log_{10}(M_{HI}/M_*)$')
ax.tick_params(axis='both', which='major', labelsize=16)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeHIfrac.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeHIfrac.eps')
def plotsizeHIdef(self,sbcutobs=20.5,isoflag=0,r90flag=0):
figure(figsize=plotsize_single)
pl.subplots_adjust(left=.15,bottom=.2)
clf()
flag = self.sampleflag & (self.HIflag) & self.dvflag
print 'number of galaxies = ',sum(flag)
y=(self.s.SIZE_RATIO[flag])
x=(self.s.HIDef[flag])
#color=self.logstellarmass[flag]
color=self.logstellarmass[flag]
sp=scatter(x,y,s=90,c=color,vmin=mstarmin,vmax=mstarmax)
rho,p=spearman(x,y)
ax=pl.gca()
text(.75,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
text(.75,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
print 'spearman for log(M*) < 10.41'
rho,p=spearman(x[color < 10.41],y[color<10.41])
colorbar(sp,fraction=.08)
pl.ylabel(r'$ R_e(24)/R_e(r)$')#,fontsize=26)
pl.xlabel(r'$ HI \ Deficiency$')#,fontsize=26)
#ax.tick_params(axis='both', which='major', labelsize=16)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeHIdef.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeHIdef.eps')
def plotsizetdepletion(self,sbcutobs=20.5,isoflag=0):
figure(figsize=(10,8))
clf()
flag = self.sampleflag & (self.HIflag) & ~self.agnflag
#flag = (self.s.HIflag > .1)
print 'number of galaxies = ',sum(flag)
if isoflag:
y=(self.isosize[flag])
else:
y=(self.s.SIZE_RATIO[flag])
x=(self.tdepletion[flag])/1.e9
rho,p=spearman(x,y)
ax=pl.gca()
text(.05,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=22)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=22)
color=self.logstellarmass[flag]
sp=scatter(x,y,s=100,c=color,vmin=mstarmin,vmax=mstarmax)
colorbar(sp,fraction=.08)
pl.ylabel(r'$ R_e(24)/R_e(r)$',fontsize=20)
pl.xlabel(r'$ Depletion \ timescale \ (Gyr)$',fontsize=20)
ax=pl.gca()
#ax.set_xscale('log')
#ax.set_yscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#flag2=self.spiralflag & self.HIflag
#plot(self.tdepletion[flag2],0.1*ones(sum(flag2)),'rx')
#xlim(0,2)
#pl.axis([9,12,.01,1.5])
#xbin,ybin,ybinerr=my.binit(x,y,5)
#print ybin
#pl.plot(xbin,ybin,'ko',markersize=12)
#pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
#spearman(x,y)
#flag = self.sampleflag & (self.HIflag) & self.agnflag
#x=(self.tdepletion[flag])/1.e9
#y=(self.s.SIZE_RATIO[flag])
#spearman(x,y)
#color=self.logstellarmass[flag]
#sp=scatter(x,y,s=50,marker='*', c=color,vmin=mstarmin,vmax=mstarmax)
if isoflag:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isosizeHIdef.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isosizeHIdef.eps')
else:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizetdeplete.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizetdeplete.eps')
def tdepletionssfr(self,sbcutobs=20.5,isoflag=0,showtrunc=0):
figure(figsize=(10,8))
clf()
flag = self.sbflag & self.sampleflag & (self.s.HIflag > .1)
if isoflag:
flag = self.isosampleflag & (self.HIflag)
else:
flag = self.sampleflag & (self.HIflag)
#flag = (self.s.HIflag > .1)
print 'number of galaxies = ',sum(flag)
y=log10(self.tdepletion[flag])
x=log10(self.ssfr[flag])
spearman(x,y)
color=self.logstellarmass[flag]
sp=scatter(x,y,s=100,c=color,vmin=mstarmin,vmax=mstarmax)
if showtrunc:
y=log10(self.tdepletion[flag & self.truncflag])
x=log10(self.ssfr[flag & self.truncflag])
plot(x,y,'r*',markersize=20)
axhline(y=log10(3.e9),color='k',ls=':')
colorbar(sp,fraction=.08)
pl.ylabel(r'$ log_{10}(t_{dep}(HI) \ (yr))$',fontsize=20)
pl.xlabel(r'$ log_{10}(SFR/M_*)$',fontsize=20)
xl=arange(-11.5,-9,.1)
yl= -0.724*xl+1.54
#yl= (-0.724 +/-0.039)*xl + (1.54 +/- 0.41)
plot(xl,yl,'k-')
plot(xl,yl+.039,'k--')
plot(xl,yl-.039,'k--')
axis([-11.5,-9,8,11])
if isoflag:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isotdepssfr.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isotdepssfr.eps')
else:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/tdepssfr.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/tdepssfr.eps')
def tdepletiontform(self,sbcutobs=20.5,isoflag=0,showtrunc=0):
figure(figsize=(10,8))
clf()
flag = self.sbflag & self.sampleflag & (self.s.HIflag > .1)
if isoflag:
flag = self.isosampleflag & (self.HIflag)
else:
flag = self.sampleflag & (self.HIflag)
#flag = (self.s.HIflag > .1)
print 'number of galaxies = ',sum(flag)
y=log10(self.tdepletion[flag])
x=log10(1./self.ssfr[flag])
spearman(x,y)
color=self.logstellarmass[flag]
sp=scatter(x,y,s=100,c=color,vmin=mstarmin,vmax=mstarmax)
if showtrunc:
y=log10(self.tdepletion[flag & self.truncflag])
x=log10(1./self.ssfr[flag & self.truncflag])
plot(x,y,'r*',markersize=20)
#axhline(y=log10(3.e9),color='k',ls=':')
colorbar(sp,fraction=.08)
pl.ylabel(r'$ log_{10}(t_{dep}(HI) \ (yr))$',fontsize=20)
pl.xlabel(r'$ log_{10}(M_*/SFR)$',fontsize=20)
xl=arange(9,11.5,.1)
#yl= -0.724*xl+1.54
#yl= (-0.724 +/-0.039)*xl + (1.54 +/- 0.41)
plot(xl,xl,'k-')
#plot(xl,yl+.039,'k--')
#plot(xl,yl-.039,'k--')
axis([8,12,8,12])
if isoflag:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isotdepssfr.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isotdepssfr.eps')
else:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/tdeptform.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/tdeptform.eps')
def plotsizeclusterphiblue(self):
flag = self.sampleflag & ~self.agnflag & self.blueflag & self.membflag
pl.figure()
pl.subplots_adjust(bottom=.15,left=.15)
pl.plot(self.s.CLUSTER_PHI[flag],self.s.SIZE_RATIO[flag],'bo')
pl.xlabel(r'$\psi \ (degrees)$')
pl.ylabel(r'$R_e(24)/R_e(r)$')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeclusterphiblue.eps')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeclusterphiblue.png')
def plotsizeclusterphi(self,sbcutobs=20.5,isoflag=0,masscut=2.55e10,r90flag=0):
# mass cut is from kauffmann+04, which is ~3e10
# I translated from Kroupa to Chabrier IMF using
# M_chabrier = M_kroupa - 0.07
mass_breaks=[log10(masscut)]#,10.**10.45]
figure(figsize=(8,8))
subplots_adjust(hspace=.05,wspace=.01,bottom=0.15,left=.15)
clf()
baseflag= self.sampleflag & ~self.agnflag & self.membflag
allax=[]
for j in range(2):
if j == 0:
flag=baseflag & (self.logstellarmass > mass_breaks[0])
slabel='$ log_{10}(M_*) > %5.2f $'%((mass_breaks[0]))
elif j == 1:
flag=baseflag & (self.logstellarmass <= mass_breaks[0])
slabel='$ log_{10}(M_*) < %5.2f $'%((mass_breaks[0]))#,log10(mass_breaks[0]))
#elif j == 2:
# flag=baseflag & (self.s.STELLARMASS <= mass_breaks[1])
# slabel='$ log_{10}(M_*) < %5.2f $'%(log10(mass_breaks[1]))
#
pl.subplot(2,1,j+1)
if isoflag:
y=(self.isosize[flag])
elif r90flag:
y=(self.r90size[flag])
else:
y=(self.s.SIZE_RATIO[flag])
pl.ylabel(r'$ R_e(24)/R_e(r)$',fontsize=20)
x=self.s.CLUSTER_PHI[flag]
color=self.logstellarmass[flag]
#sp=scatter(x,y,s=100,c=color,vmin=mstarmin,vmax=mstarmax)
color=self.sb_obs[flag]
sp=scatter(x,y,s=100,c=color,vmin=sbmin,vmax=sbmax)
ax=gca()
ax.tick_params(axis='both', which='major', labelsize=16)
if j < 1:
ax.set_xticklabels(([]))
else:
ax.set_yticklabels(([]))
if isoflag:
ymax=2.2
else:
ymax=1.5
pl.axis([0,90,0,ymax])
allax.append(ax)
text(.9,.9,slabel,transform=ax.transAxes,fontsize=16,horizontalalignment='right')
try:
(rho,p)=spearman(x,y)
except:
print 'trouble running spearman'
rho=-99
p=-99
#print rho,p
text(.05,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
xbin,ybin,ybinerr=my.binitbins(0,90.,3,x,y)
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
field=mean(y[x>1.5])
fielderr=std(y[x>1.5])/sqrt(1.*sum(x>1.5))
pl.axhline(y=field,ls='-',color='k')
pl.axhline(y=field+fielderr,ls='--',color='k')
pl.axhline(y=field-fielderr,ls='--',color='k')
#pl.axhline(y=1,ls='-',color='k')
#ax.set_yscale('log')
colorbar(ax=allax,fraction=.05)
pl.xlabel(r'$\psi$',fontsize=28)
ax=pl.gca()
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeclusterphi.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeclusterphi.eps')
def comparestellarmass(self):
# log10(chabrier) = log10(Salpeter) - .25 (SFR estimate)
# log10(chabrier) = log10(diet Salpeter) - 0.1 (Stellar mass estimates)
figure(figsize=(10,8))
plot(self.s.MSTAR_50,log10(self.s.STELLARMASS),'bo',label='Bell+2003')
plot(self.s.MSTAR_50,self.logstellarmassTaylor,'go',label='Taylor+2011')
xl=arange(7.8,12.5,.1)
xlabel('$ log_{10}(M_*) \ Moustakas $',fontsize=20)
ylabel('$ log_{10}(M_*) $',fontsize=20)
plot(xl,xl,'k-',lw=3,label='1:1')
dy=.4
plot(xl,xl+dy,'k--',label='1:1 + '+str(dy))
plot(xl,xl-.15,'r-',label='1:1 - 0.15 ')
legend(loc='upper left',numpoints=1)
axis([7.5,12.5,7.5,12.5])
savefig(homedir+'research/LocalClusters/SamplePlots/Stellarmass.png')
def plotsizedrbymass(self,masscut=2.55e10,sbcutobs=20.,isoflag=0,r90flag=0,fixPA=False):
# mass cut is from kauffmann+04, which is ~3e10
# I translated from Kroupa to Chabrier IMF using
# M_chabrier = M_kroupa - 0.07
mass_breaks=[log10(masscut)]#,10.**10.45]
figure(figsize=(8,8))
subplots_adjust(hspace=.05,bottom=0.15,left=.15)
clf()
if isoflag:
baseflag= self.isosampleflag & self.dvflag & ~self.agnflag
baseflag= self.sampleflag & self.dvflag & ~self.agnflag
elif r90flag:
baseflag= self.sampleflag & self.mipsflag & self.dvflag & ~self.agnflag
else:
baseflag= (self.sb_obs < sbcutobs) & self.sampleflag& self.dvflag & ~self.agnflag
allax=[]
for j in range(2):
if j == 0:
flag=baseflag & (self.logstellarmass > mass_breaks[0])
slabel='$ log_{10}(M_*) > %5.2f $'%((mass_breaks[0]))
elif j == 1:
flag=baseflag & (self.logstellarmass <= mass_breaks[0])
slabel='$ log_{10}(M_*) < %5.2f $'%((mass_breaks[0]))#,log10(mass_breaks[0]))
#elif j == 2:
# flag=baseflag & (self.s.STELLARMASS <= mass_breaks[1])
# slabel='$ log_{10}(M_*) < %5.2f $'%(log10(mass_breaks[1]))
#
print j, sum(flag)
pl.subplot(2,1,j+1)
yplot=(self.s.SIZE_RATIO)
y=(yplot[flag & self.upperlimit])
x=self.s.DR_R200[flag & self.upperlimit ]
#color=self.sb_obs[flag]
color=self.logstellarmass[flag & self.upperlimit]
errs=array(zip(.1*ones(len(x)),zeros(len(x))),'f')
errorbar(x,y,xerr=None,yerr=errs.T,fmt=None,ecolor='k', \
lolims=True,capsize=4,capthick=0,elinewidth=2,mew=1,label='Upper Lims')
sp=scatter(x,y,s=100,c=color,marker='v',vmin=mstarmin,vmax=mstarmax)
#plot(self.s.DR_R200[flag & self.pointsource],self.s.SIZE_RATIO[flag & self.pointsource],'k*',markersize=14)
#plot(self.s.DR_R200[flag & self.AGNKAUFF],yplot[flag & self.AGNKAUFF],'k*',mec='k',mfc='None',markersize=20)
if j == 0:
outfile=homedir+'research/LocalClusters/Rdata/sizedr_highmass.txt'
else:
outfile=homedir+'research/LocalClusters/Rdata/sizedr_lowmass.txt'
out1=open(outfile,'w')
for i in range(sum(self.s.SIZE_RATIO)):
if flag[i]:
s='%5.2f %5.2f %i %5.3f \n'%(self.s.DR_R200[i],self.s.SIZE_RATIO[i],self.upperlimit[i], self.s.fcre1[i])
out1.write(s)
out1.close()
y=(yplot[flag & ~self.upperlimit])
x=self.s.DR_R200[flag & ~self.upperlimit ]
#color=self.sb_obs[flag]
color=self.logstellarmass[flag & ~self.upperlimit]
sp=scatter(x,y,s=100,c=color,vmin=mstarmin,vmax=mstarmax)
ax=gca()
ax.tick_params(axis='both', which='major', labelsize=16)
if j < 1:
ax.set_xticklabels(([]))
if isoflag:
ymax=2.2
else:
ymax=1.5
pl.axis([0,3.5,0,ymax])
allax.append(ax)
text(.9,.9,slabel,transform=ax.transAxes,fontsize=16,horizontalalignment='right')
y=yplot[flag]
x=self.s.DR_R200[flag]
(rho,p)=spearman(x,y)
#print rho,p
text(.05,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
t=my.ratioerror(len(y[(x<1) & (y < 0.5)]),len(y[x<1]))
print t[0],t[1],t[2]
print 'fraction of size < 0.5 galaxies w/in R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
t=my.ratioerror(len(y[(x>1)&(y<0.5)]),len(y[x>1]))
print 'fraction of size < 0.5 galaxies outside R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
#xbin,ybin,ybinerr=my.binitbins(0,3.,3,x,y)
xbin,ybin,ybinerr=my.binit(x,y,7)
pl.plot(xbin,ybin,'ko',markersize=16)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None,ecolor='k')
field=median(y[x>1.5])
fielderr=std(y[x>1.5])/sqrt(1.*sum(x>1.5))
pl.axhline(y=field,ls='-',color='k')
pl.axhline(y=field+fielderr,ls='--',color='k')
pl.axhline(y=field-fielderr,ls='--',color='k')
#pl.axhline(y=1,ls='-',color='k')
#ax.set_yscale('log')
colorbar(ax=allax,fraction=.05)
pl.xlabel(r'$ \Delta R/R_{200}$',fontsize=28)
ax=pl.gca()
if isoflag:
xl=r'$ R_{iso}(24)/R_{iso}(r)$'
else:
xl=r'$ R_e(24)/R_e(r)$'
pl.text(-0.18,1,xl,fontsize=28,transform=ax.transAxes,rotation=90,verticalalignment='center')
#ax.set_xscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
if isoflag:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isosizedrbymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isosizedrbymass.eps')
else:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizedrbymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizedrbymass.eps')
def plotsizesigmabymass(self,masscut=2.55e10,sbcutobs=20.,isoflag=0,ssfrflag=0,NUV24flag=0,BTflag=0,r90flag=0):
# mass cut is from kauffmann+04, which is ~3e10
# I translated from Kroupa to Chabrier IMF using
# M_chabrier = M_kroupa - 0.07
mass_breaks=[log10(masscut)]#,10.**10.45]
figure(figsize=(10,6))
subplots_adjust(hspace=.05,wspace=.05,bottom=0.15,left=.1)
print 'r90flag = ',r90flag
clf()
allax=[]
for j in range(4):
if j == 0:
flag=self.sampleflag & self.dvflag & ~self.agnflag & (self.logstellarmass > mass_breaks[0])
slabel='$ log_{10}(M_*) > %5.2f $'%((mass_breaks[0]))
elif j == 2:
flag=self.sampleflag & self.dvflag & ~self.agnflag & (self.logstellarmass <= mass_breaks[0])
slabel='$ log_{10}(M_*) < %5.2f $'%((mass_breaks[0]))#,log10(mass_breaks[0]))
elif j == 3:
flag=self.sampleflag & self.dvflag & self.agnflag & (self.logstellarmass <= mass_breaks[0])
slabel='$ log_{10}(M_*) < %5.2f $'%((mass_breaks[0]))#,log10(mass_breaks[0]))
elif j == 1:
flag=self.sampleflag & self.dvflag & self.agnflag & (self.logstellarmass > mass_breaks[0])
slabel='$ log_{10}(M_*) > %5.2f $'%((mass_breaks[0]))#,log10(mass_breaks[0]))
#elif j == 2:
# flag=baseflag & (self.s.STELLARMASS <= mass_breaks[1])
# slabel='$ log_{10}(M_*) < %5.2f $'%(log10(mass_breaks[1]))
#
print j, sum(flag)
pl.subplot(2,2,j+1)
y=(self.s.SIZE_RATIO[flag])
x=log10(self.s.SIGMA_5[flag])
#color=self.sb_obs[flag]
color=self.logstellarmass[flag]
v1=mstarmin
v2=mstarmax
ccmap='jet'
if ssfrflag:
color=log10(self.ssfr[flag])
v1=ssfrmin
v2=ssfrmax
ccmap='jet_r'
elif NUV24flag:
color=self.NUV24color[flag]
v1=min(color)
v2=max(color)
ccmap='jet'
elif BTflag:
color=self.s.B_T_r[flag]
v1=min(color)
v2=max(color)
ccmap='jet'
sp=scatter(x,y,s=100,c=color,vmin=v1,vmax=v2,cmap=ccmap)
ax=gca()
pl.yticks(arange(0,1.5,.4))
ax.tick_params(axis='both', which='major', labelsize=16)
if j == 0:
pl.title('$SF \ Galaxies$',fontsize=20)
if j == 1:
pl.title('$AGN$',fontsize=20)
if j < 2:
ax.set_xticklabels(([]))
if (j == 1) | (j == 3):
ax.set_yticklabels(([]))
if isoflag:
ymax=2.2
else:
ymax=2.5
pl.axis([-1.1,2.1,0,1.5])
allax.append(ax)
pl.text(.95,.9,slabel,transform=ax.transAxes,fontsize=16,horizontalalignment='right')
if (len(x) > 0):
(rho,p)=spearman(x,y)
#print rho,p
text(.05,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
#t=my.ratioerror(len(y[(x<1) & (y < 0.3)]),len(y[x<1]))
#print t[0],t[1],t[2]
#print 'fraction of size < 0.5 galaxies w/in R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
#t=my.ratioerror(len(y[(x>1)&(y<0.3)]),len(y[x>1]))
#print 'fraction of size < 0.5 galaxies outside R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
#xbin,ybin,ybinerr=my.binitbins(-.5,2.,5,x,y)
#pl.plot(xbin,ybin,'ko',markersize=20,mfc='k')
#pl.errorbar(xbin,ybin,yerr=3.*ybinerr,fmt=None,ecolor='k')
#field=mean(y[x>1.5])
#fielderr=std(y[x>1.5])/sqrt(1.*sum(x>1.5))
#pl.axhline(y=field,ls='-',color='k')
#pl.axhline(y=field+fielderr,ls='--',color='k')
#pl.axhline(y=field-fielderr,ls='--',color='k')
#pl.axhline(y=1,ls='-',color='k')
#ax.set_yscale('log')
colorbar(ax=allax,fraction=.05)
ax=pl.gca()
if isoflag:
xl=r'$ R_{iso}(24)/R_{iso}(r)$'
else:
xl=r'$ R_e(24)/R_e(r)$'
pl.text(-1.3,1,xl,fontsize=28,transform=ax.transAxes,rotation=90,verticalalignment='center')
pl.text(0,-.3,r'$ log_{10}(\Sigma_5 \ (gal/Mpc^2))$',transform=ax.transAxes,horizontalalignment='center',fontsize=28)
#ax.set_xscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
if isoflag:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isosizesigmabymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isosizesigmabymass.eps')
else:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizesigmabymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizesigmabymass.eps')
def plotsbsigmabymass(self,masscut=2.55e10,sbcutobs=20.,isoflag=0,ssfrflag=0,NUV24flag=0,BTflag=0):
# mass cut is from kauffmann+04, which is ~3e10
# I translated from Kroupa to Chabrier IMF using
# M_chabrier = M_kroupa - 0.07
mass_breaks=[log10(masscut)]#,10.**10.45]
figure(figsize=(8,8))
subplots_adjust(hspace=.05,bottom=0.15,left=.15)
clf()
if isoflag:
baseflag= self.isosampleflag & self.dvflag & ~self.agnflag
baseflag= self.sampleflag & self.dvflag & ~self.agnflag
else:
baseflag= (self.sb_obs < sbcutobs) & self.sampleflag& self.dvflag & ~self.agnflag
allax=[]
for j in range(2):
if j == 0:
flag=baseflag & (self.logstellarmass > mass_breaks[0])
slabel='$ log_{10}(M_*) > %5.2f $'%((mass_breaks[0]))
elif j == 1:
flag=baseflag & (self.logstellarmass <= mass_breaks[0])
slabel='$ log_{10}(M_*) < %5.2f $'%((mass_breaks[0]))#,log10(mass_breaks[0]))
#elif j == 2:
# flag=baseflag & (self.s.STELLARMASS <= mass_breaks[1])
# slabel='$ log_{10}(M_*) < %5.2f $'%(log10(mass_breaks[1]))
#
print j, sum(flag)
pl.subplot(2,1,j+1)
y=(self.sb_obs[flag])
x=log10(self.s.SIGMA_5[flag])
color=self.sb_obs[flag]
color=self.logstellarmass[flag]
v1=mstarmin
v2=mstarmax
ccmap='jet'
if ssfrflag:
color=log10(self.ssfr[flag])
v1=ssfrmin
v2=ssfrmax
ccmap='jet_r'
elif NUV24flag:
color=self.NUV24color[flag]
v1=min(color)
v2=max(color)
ccmap='jet'
elif BTflag:
color=self.s.B_T_r[flag]
v1=min(color)
v2=max(color)
ccmap='jet'
sp=scatter(x,y,s=100,c=color,vmin=v1,vmax=v2,cmap=ccmap)
ax=gca()
ax.tick_params(axis='both', which='major', labelsize=16)
if j < 1:
ax.set_xticklabels(([]))
if isoflag:
ymax=2.2
else:
ymax=1.5
pl.axis([-1.1,2.1,sbmin,sbmax])
allax.append(ax)
text(.9,.9,slabel,transform=ax.transAxes,fontsize=16,horizontalalignment='right')
(rho,p)=spearman(x,y)
#print rho,p
text(.05,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
#t=my.ratioerror(len(y[(x<1) & (y < 0.3)]),len(y[x<1]))
#print t[0],t[1],t[2]
#print 'fraction of size < 0.5 galaxies w/in R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
#t=my.ratioerror(len(y[(x>1)&(y<0.3)]),len(y[x>1]))
#print 'fraction of size < 0.5 galaxies outside R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
xbin,ybin,ybinerr=my.binitbins(-.5,2.,5,x,y)
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
#field=mean(y[x>1.5])
#fielderr=std(y[x>1.5])/sqrt(1.*sum(x>1.5))
#pl.axhline(y=field,ls='-',color='k')
#pl.axhline(y=field+fielderr,ls='--',color='k')
#pl.axhline(y=field-fielderr,ls='--',color='k')
#pl.axhline(y=1,ls='-',color='k')
#ax.set_yscale('log')
colorbar(ax=allax,fraction=.05)
pl.xlabel(r'$ log_{10}(\Sigma_5 \ (gal/Mpc^2))$',fontsize=28)
ax=pl.gca()
if isoflag:
xl=r'$ R_{iso}(24)/R_{iso}(r)$'
else:
xl=r'$ \mu_{24} \ (mag/arcsec^2)$'
pl.text(-0.18,1,xl,fontsize=28,transform=ax.transAxes,rotation=90,verticalalignment='center')
#ax.set_xscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
if isoflag:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sbsizesigmabymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sbsizesigmabymass.eps')
else:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sbsigmabymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sbsigmabymass.eps')
def plotsizeLxbymass(self,masscut=2.55e10,sbcutobs=20.,isoflag=0):
# mass cut is from kauffmann+04, which is ~3e10
# I translated from Kroupa to Chabrier IMF using
# M_chabrier = M_kroupa - 0.07
mass_breaks=[log10(masscut)]#,10.**10.45]
figure(figsize=(8,8))
subplots_adjust(hspace=.05,bottom=.15,left=.15)
clf()
if isoflag:
baseflag= self.isosampleflag & self.dvflag & ~self.agnflag
else:
baseflag= (self.sb_obs < sbcutobs) & self.sampleflag& self.dvflag & ~self.agnflag
allax=[]
for j in range(2):
if j == 0:
flag=baseflag & (self.logstellarmass > mass_breaks[0])
slabel='$ log_{10}(M_*) > %5.2f $'%((mass_breaks[0]))
elif j == 1:
flag=baseflag & (self.logstellarmass <= mass_breaks[0])
slabel='$ log_{10}(M_*) < %5.2f $'%((mass_breaks[0]))#,log10(mass_breaks[0]))
#elif j == 2:
# flag=baseflag & (self.s.STELLARMASS <= mass_breaks[1])
# slabel='$ log_{10}(M_*) < %5.2f $'%(log10(mass_breaks[1]))
#
print j, sum(flag)
pl.subplot(2,1,j+1)
if isoflag:
y=(self.isosize[flag])
else:
y=(self.s.SIZE_RATIO[flag])
x=log10(self.s.CLUSTER_LX)-2.*log10(self.s.DR_R200)
x=x[flag]
color=self.sb_obs[flag]
color=self.logstellarmass[flag]
sp=scatter(x,y,s=100,c=color,vmin=mstarmin,vmax=mstarmax)
ax=gca()
ax.tick_params(axis='both', which='major', labelsize=16)
if j < 1:
ax.set_xticklabels(([]))
if isoflag:
ymax=2.2
else:
ymax=1.5
pl.axis([-2.8,2.8,0,ymax])
allax.append(ax)
text(.9,.9,slabel,transform=ax.transAxes,fontsize=16,horizontalalignment='right')
(rho,p)=spearman(x,y)
#print rho,p
text(.05,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
#t=my.ratioerror(len(y[(x<1) & (y < 0.3)]),len(y[x<1]))
#print t[0],t[1],t[2]
#print 'fraction of size < 0.5 galaxies w/in R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
#t=my.ratioerror(len(y[(x>1)&(y<0.3)]),len(y[x>1]))
#print 'fraction of size < 0.5 galaxies outside R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
xbin,ybin,ybinerr=my.binitbins(-.5,2.,5,x,y)
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=3.*ybinerr,fmt=None)
#field=mean(y[x>1.5])
#fielderr=std(y[x>1.5])/sqrt(1.*sum(x>1.5))
#pl.axhline(y=field,ls='-',color='k')
#pl.axhline(y=field+fielderr,ls='--',color='k')
#pl.axhline(y=field-fielderr,ls='--',color='k')
#pl.axhline(y=1,ls='-',color='k')
#ax.set_yscale('log')
colorbar(ax=allax,fraction=.05)
pl.xlabel(r'$ log_{10}(L_X/\Delta r^2 )$',fontsize=28)
ax=pl.gca()
if isoflag:
xl=r'$ R_{iso}(24)/R_{iso}(r)$'
else:
xl=r'$ R_e(24)/R_e(r)$'
pl.text(-0.18,1,xl,fontsize=28,transform=ax.transAxes,rotation=90,verticalalignment='center')
#ax.set_xscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
if isoflag:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isosizeLxbymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isosizeLxbymass.eps')
else:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeLxbymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeLxbymass.eps')
def plotsizeBTbymass(self,masscut=2.55e10,sbcutobs=20.,isoflag=False):
# mass cut is from kauffmann+04, which is ~3e10
# I translated from Kroupa to Chabrier IMF using
# M_chabrier = M_kroupa - 0.07
mass_breaks=[log10(masscut)]#,10.**10.45]
figure(figsize=(8,8))
subplots_adjust(hspace=.05,bottom=.15,left=.15)
clf()
if isoflag:
baseflag= self.isosampleflag & self.dvflag & ~self.agnflag
baseflag= self.sampleflag & self.gim2dflag & ~self.agnflag & self.dvflag
else:
baseflag= self.sampleflag &self.dvflag & self.gim2dflag & ~self.agnflag
allax=[]
for j in range(2):
if j == 0:
flag=baseflag & (self.logstellarmass > mass_breaks[0]) #& self.membflag
slabel='$ log_{10}(M_*) > %5.2f $'%((mass_breaks[0]))
elif j == 1:
flag=baseflag & (self.logstellarmass <= mass_breaks[0])#& self.membflag
slabel='$ log_{10}(M_*) < %5.2f $'%((mass_breaks[0]))#,log10(mass_breaks[0]))
#elif j == 2:
# flag=baseflag & (self.s.STELLARMASS <= mass_breaks[1])
# slabel='$ log_{10}(M_*) < %5.2f $'%(log10(mass_breaks[1]))
#
print j, sum(flag)
pl.subplot(2,1,j+1)
if isoflag:
y=(self.isosize)
else:
y=(self.s.SIZE_RATIO)
x=self.s.B_T_r
#color=self.sb_obs[flag]
color=self.logstellarmass
sp=scatter(x[flag],y[flag],s=100,c=color[flag],vmin=mstarmin,vmax=mstarmax)
ax=gca()
ax.tick_params(axis='both', which='major', labelsize=16)
if j < 1:
ax.set_xticklabels(([]))
if isoflag:
ymax=2.2
else:
ymax=1.5
pl.axis([-.05,.805,0,ymax])
allax.append(ax)
text(.9,.9,slabel,transform=ax.transAxes,fontsize=16,horizontalalignment='right')
(rho,p)=spearman(x[flag],y[flag])
#print rho,p
text(.05,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
#t=spearman_boot(x[flag],y[flag])
#print 'Spearman Rank Test w/bootstrap:'
#print 'rho = %6.2f'%(t[0])
#print 'p-vale = %6.5f (prob that samples are uncorrelated)'%(t[1])
#t=my.ratioerror(len(y[(x<1) & (y < 0.3)]),len(y[x<1]))
#print t[0],t[1],t[2]
#print 'fraction of size < 0.5 galaxies w/in R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
#t=my.ratioerror(len(y[(x>1)&(y<0.3)]),len(y[x>1]))
#print 'fraction of size < 0.5 galaxies outside R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
#xbin,ybin,ybinerr=my.binitbins(0,.5,5,x,y)
xbin,ybin,ybinerr=my.binit(x[flag],y[flag],5)
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
#field=mean(y[x>1.5])
#fielderr=std(y[x>1.5])/sqrt(1.*sum(x>1.5))
#pl.axhline(y=field,ls='-',color='k')
#pl.axhline(y=field+fielderr,ls='--',color='k')
#pl.axhline(y=field-fielderr,ls='--',color='k')
#pl.axhline(y=1,ls='-',color='k')
#ax.set_yscale('log')
print 'all masses'
spearman(x[baseflag],y[baseflag])
colorbar(ax=allax,fraction=.05)
pl.xlabel(r'$ B/T$',fontsize=28)
ax=pl.gca()
if isoflag:
xl=r'$ R_{iso}(24)/R_{iso}(r)$'
else:
xl=r'$ R_e(24)/R_e(r)$'
pl.text(-0.18,1,xl,fontsize=28,transform=ax.transAxes,rotation=90,verticalalignment='center')
#ax.set_xscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
if isoflag:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBTbymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBTbymass.eps')
else:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBTbymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBTbymass.eps')
def plotsizeBTbyenv(self,masscut=2.55e10,sbcutobs=20.,isoflag=0):
# mass cut is from kauffmann+04, which is ~3e10
# I translated from Kroupa to Chabrier IMF using
# M_chabrier = M_kroupa - 0.07
mass_breaks=[log10(masscut)]#,10.**10.45]
figure(figsize=(8,8))
subplots_adjust(hspace=.05,bottom=.15,left=.15)
clf()
if isoflag:
baseflag= self.isosampleflag & self.dvflag & ~self.agnflag
baseflag= self.sampleflag & ~self.agnflag & self.dvflag
else:
baseflag= (self.sb_obs < sbcutobs) & self.sampleflag & ~self.agnflag &self.dvflag
allax=[]
for j in range(2):
if j == 0:
flag=baseflag & self.membflag
slabel='$ Cluster $'
binmarker='ko'
elif j == 1:
flag=baseflag & ~self.membflag
slabel='$ Field $'
binmarker='k^'
#elif j == 2:
# flag=baseflag & (self.s.STELLARMASS <= mass_breaks[1])
# slabel='$ log_{10}(M_*) < %5.2f $'%(log10(mass_breaks[1]))
#
print j, sum(flag)
pl.subplot(2,1,j+1)
if isoflag:
y=(self.isosize[flag])
else:
y=(self.s.SIZE_RATIO[flag])
x=self.s.B_T_r
x=x[flag]
color=self.sb_obs[flag]
color=self.logstellarmass[flag]
sp=scatter(x,y,s=100,c=color,vmin=mstarmin,vmax=mstarmax)
ax=gca()
ax.tick_params(axis='both', which='major', labelsize=16)
if j < 1:
ax.set_xticklabels(([]))
if isoflag:
ymax=2.2
else:
ymax=1.5
pl.axis([-.05,.805,0,ymax])
allax.append(ax)
text(.9,.9,slabel,transform=ax.transAxes,fontsize=16,horizontalalignment='right')
(rho,p)=spearman(x,y)
#print rho,p
text(.05,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
#t=my.ratioerror(len(y[(x<1) & (y < 0.3)]),len(y[x<1]))
#print t[0],t[1],t[2]
#print 'fraction of size < 0.5 galaxies w/in R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
#t=my.ratioerror(len(y[(x>1)&(y<0.3)]),len(y[x>1]))
#print 'fraction of size < 0.5 galaxies outside R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
if j == 1:
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
xbin,ybin,ybinerr=my.binitbins(0,.6,3,x,y)
pl.plot(xbin,ybin,binmarker,markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None)
#field=mean(y[x>1.5])
#fielderr=std(y[x>1.5])/sqrt(1.*sum(x>1.5))
#pl.axhline(y=field,ls='-',color='k')
#pl.axhline(y=field+fielderr,ls='--',color='k')
#pl.axhline(y=field-fielderr,ls='--',color='k')
#pl.axhline(y=1,ls='-',color='k')
#ax.set_yscale('log')
colorbar(ax=allax,fraction=.05)
pl.xlabel(r'$ B/T$',fontsize=28)
ax=pl.gca()
if isoflag:
xl=r'$ R_{iso}(24)/R_{iso}(r)$'
else:
xl=r'$ R_e(24)/R_e(r)$'
pl.text(-0.18,1,xl,fontsize=28,transform=ax.transAxes,rotation=90,verticalalignment='center')
#ax.set_xscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
if isoflag:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBTbymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBTbymass.eps')
else:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBTbymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizeBTbymass.eps')
def plotsizemassdensbymass(self,masscut=2.55e10,sbcutobs=20.,isoflag=0,clusterflag=0,envflag=0):
# mass cut is from kauffmann+04, which is ~3e10
# I translated from Kroupa to Chabrier IMF using
# M_chabrier = M_kroupa - 0.07
mass_breaks=[log10(masscut)]#,10.**10.45]
figure(figsize=(8,8))
subplots_adjust(hspace=.05,bottom=.15,left=.15)
clf()
if isoflag:
baseflag= self.isosampleflag & self.dvflag & ~self.agnflag
baseflag= self.sampleflag & ~self.agnflag & self.dvflag
else:
baseflag= (self.sb_obs < sbcutobs) & self.sampleflag & ~self.agnflag &self.dvflag
allax=[]
xvar=self.massdensity
for j in range(2):
if clusterflag:
if j == 0:
flag=baseflag & (self.membflag)
slabel='$ Cluster $'
elif j == 1:
flag=baseflag & ~self.membflag
slabel='$ Field$'
color=log10(self.s.SIGMA_5[flag])
v1=-1
v2=2
elif envflag:
if j == 0:
flag=baseflag & (log10(self.s.SIGMA_5) > .75)
slabel='$ log_{10}(\Sigma_5) > 0.75 $'
elif j == 1:
flag=baseflag & (log10(self.s.SIGMA_5) < .75)
slabel='$ log_{10}(\Sigma_5) < 0.75 $'
color=log10(self.s.SIGMA_5[flag])
v1=-1
v2=2
else:
if j == 0:
flag=baseflag & (self.logstellarmass > mass_breaks[0])
slabel='$ log_{10}(M_*) > %5.2f $'%((mass_breaks[0]))
elif j == 1:
flag=baseflag & (self.logstellarmass <= mass_breaks[0])
slabel='$ log_{10}(M_*) < %5.2f $'%((mass_breaks[0]))#,log10(mass_breaks[0]))
color=self.logstellarmass[flag]
v1=mstarmin
v2=mstarmax
#elif j == 2:
# flag=baseflag & (self.s.STELLARMASS <= mass_breaks[1])
# slabel='$ log_{10}(M_*) < %5.2f $'%(log10(mass_breaks[1]))
#
print j, sum(flag)
pl.subplot(2,1,j+1)
if isoflag:
y=(self.isosize[flag])
else:
y=(self.s.SIZE_RATIO[flag])
x=xvar[flag]
sp=scatter(x,y,s=100,c=color,vmin=v1,vmax=v2)
ax=gca()
ax.tick_params(axis='both', which='major', labelsize=16)
if j < 1:
ax.set_xticklabels(([]))
if isoflag:
ymax=2.2
else:
ymax=1.5
pl.axis([4.,9,0,ymax])
allax.append(ax)
text(.9,.9,slabel,transform=ax.transAxes,fontsize=16,horizontalalignment='right')
(rho,p)=spearman(x,y)
#print rho,p
text(.05,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
#t=my.ratioerror(len(y[(x<1) & (y < 0.3)]),len(y[x<1]))
#print t[0],t[1],t[2]
#print 'fraction of size < 0.5 galaxies w/in R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
#t=my.ratioerror(len(y[(x>1)&(y<0.3)]),len(y[x>1]))
#print 'fraction of size < 0.5 galaxies outside R200 = %5.2f - %5.2f + %5.2f'%(t[0],t[1],t[2])
xbin,ybin,ybinerr=my.binitbins(5,8,3,x,y)
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None,ecolor='k')
#field=mean(y[x>1.5])
#fielderr=std(y[x>1.5])/sqrt(1.*sum(x>1.5))
#pl.axhline(y=field,ls='-',color='k')
#pl.axhline(y=field+fielderr,ls='--',color='k')
#pl.axhline(y=field-fielderr,ls='--',color='k')
#pl.axhline(y=1,ls='-',color='k')
#ax.set_yscale('log')
colorbar(ax=allax,fraction=.05)
pl.xlabel(r'$ log_{10}(M_*/\pi R_e^2)$',fontsize=28)
ax=pl.gca()
if isoflag:
xl=r'$ R_{iso}(24)/R_{iso}(r)$'
else:
xl=r'$ R_e(24)/R_e(r)$'
pl.text(-0.18,1,xl,fontsize=28,transform=ax.transAxes,rotation=90,verticalalignment='center')
#ax.set_xscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
if isoflag:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemassdensbymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemassdensbymass.eps')
else:
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemassdensbymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemassdensbymass.eps')
def plotsizemassdens(self,masscut=2.55e10,sbcutobs=20.,envflag=0,ageflag=0):
# mass cut is from kauffmann+04, which is ~3e10
# I translated from Kroupa to Chabrier IMF using
# M_chabrier = M_kroupa - 0.07
mass_breaks=[log10(masscut)]#,10.**10.45]
figure(figsize=(7,6))
subplots_adjust(hspace=.05,bottom=.15,left=.15)
clf()
flag= self.sampleflag & ~self.agnflag #& self.dvflag & (self.s.SIZE_RATIOERR < .2)
xvar=self.massdensity
color=log10(self.s.SIGMA_5[flag])
if envflag:
color=log10(self.s.SIGMA_5[flag])
v1=-1
v2=2
elif ageflag:
color=self.jmass.SFRAGE_50[flag]
v1=0
v2=12
else:
color=self.logstellarmass[flag]
v1=mstarmin
v2=mstarmax
y=(self.s.SIZE_RATIO[flag])
erry=(self.s.SIZE_RATIOERR[flag])
x=xvar[flag]
errorbar(x,y,erry,fmt=None,ecolor='k')
sp=scatter(x,y,s=60,c=color,vmin=v1,vmax=v2)
ax=gca()
ax.tick_params(axis='both', which='major', labelsize=16)
ymax=1.5
pl.axis([4.,8.5,0,ymax])
print 'ALL GALAXIES'
(rho,p)=spearman(x,y)
print 'GALAXIES WITH SIZE < .5'
(rho,p)=spearman(x[y<.5],y[y<.5])
#print rho,p
#text(.05,.9,r'$\rho = %4.2f$'%(rho),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
#text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=16)
#xbin,ybin,ybinerr=my.binitbins(5,8,3,x,y)
#pl.plot(xbin,ybin,'ko',markersize=12)
#pl.errorbar(xbin,ybin,yerr=ybinerr,fmt=None,ecolor='k')
colorbar(fraction=.05)
pl.xlabel(r'$ log_{10}(M_*/\pi R_e^2)$',fontsize=28)
ax=pl.gca()
xl=r'$ R_e(24)/R_e(r)$'
pl.text(-0.18,.5,xl,fontsize=28,transform=ax.transAxes,rotation=90,verticalalignment='center')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemassdens.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/sizemassdens.eps')
def plotisosizedrbymass(self,masscut=9.e10,sbcutobs=20.,massflag=0):
mass_breaks=[log10(masscut)]#,10.**10.45]
figure(figsize=(10,8))
subplots_adjust(hspace=.05)
clf()
baseflag= self.isosampleflag & ~self.agnflag
if massflag:
color=self.logstellarmass
v1=mstarmin
v2=mstarmax
else:
color=self.sb_obs
v1=sbmin
v2=sbmax
for j in range(2):
if j == 0:
flag=baseflag & (self.logstellarmass > mass_breaks[0])
slabel='$ log_{10}(M_*) > %5.2f $'%((mass_breaks[0]))
elif j == 1:
flag=baseflag & (self.logstellarmass <= mass_breaks[0])
slabel='$ log_{10}(M_*) < %5.2f $'%((mass_breaks[0]))#,log10(mass_breaks[0]))
pl.ylabel(r'$ R_e(24)/R_e(r)$',fontsize=20)
#elif j == 2:
# flag=baseflag & (self.s.STELLARMASS <= mass_breaks[1])
# slabel='$ log_{10}(M_*) < %5.2f $'%(log10(mass_breaks[1]))
#
print j, sum(flag)
pl.subplot(2,1,j+1)
y=(self.isorad.MIPS[flag]/self.isorad.NSA[flag])
x=self.s.DR_R200[flag]
sp=scatter(x,y,s=100,c=color[flag],vmin=v1,vmax=v2)
ax=gca()
if j < 1:
ax.set_xticklabels(([]))
pl.axis([0,3.5,0,1.5])
text(.9,.85,slabel,transform=ax.transAxes,fontsize=14,horizontalalignment='right')
xbin,ybin,ybinerr=my.binitbins(0,3.,3,x,y)
pl.plot(xbin,ybin,'ko',markersize=12)
pl.errorbar(xbin,ybin,yerr=3.*ybinerr,fmt=None)
field=mean(y[x>1.5])
pl.axhline(y=field,ls='--',color='k')
pl.axhline(y=1,ls='-',color='k')
spearman(x,y)
#ax.set_yscale('log')
pl.xlabel(r'$ \Delta R/R_{200}$',fontsize=20)
ax=pl.gca()
#ax.set_xscale('log')
#pl.axhline(y=.5,ls='--',color='k')
#xlim(0,2)
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isosizedrbymass.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/isosizedrbymass.eps')
def compareRiso(self):
figure(figsize=(10,6))
subplots_adjust(wspace=0.01,hspace=.3,bottom=.1,left=.1,top=.95,right=.95)
subplot(1,2,1)
flag=self.isosampleflag & self.membflag
cb=scatter(self.isorad.NSA[flag],self.isorad.MIPS[flag],s=50,c=self.logstellarmass[flag],vmin=8.5,vmax=12.)
#colorbar(cb)
xlabel('$R_{iso}(r) $',fontsize=20)
ylabel('$R_{iso}(24) $',fontsize=20)
xl=arange(1,70)
plot(xl,xl,'k--')
plot(xl,.7*xl,'k:')
plot(xl,1.3*xl,'k:')
axis([0,70,-2,50])
ax1=gca()
text(.1,.9,'$Cluster$',transform=ax1.transAxes,horizontalalignment='left',fontsize=18)
subplot(1,2,2)
flag=self.isosampleflag & ~self.membflag
cb=scatter(self.isorad.NSA[flag],self.isorad.MIPS[flag],s=50,c=self.logstellarmass[flag],vmin=8.5,vmax=12.)
plot(xl,xl,'k--')
plot(xl,.7*xl,'k:')
plot(xl,1.3*xl,'k:')
ax2=gca()
colorbar(cb,ax=[ax1,ax2])
ax2.set_yticklabels(([]))
axis([0,70,-2,50])
text(.1,.9,'$Field$',transform=ax2.transAxes,horizontalalignment='left',fontsize=18)
xlabel('$R_{iso}(r) $',fontsize=20)
def plotRevsRiso(self,useE0=0):
figure(figsize=(10,6))
subplots_adjust(wspace=0.2,hspace=.35,bottom=.15,left=.1,top=.95,right=.95)
flag=self.isosampleflag & self.dvflag & ~self.agnflag
flag2=self.sampleflag & self.dvflag & ~self.agnflag
if useE0:
x=self.isorad.MIPSE0[flag]/self.isorad.NSA[flag]
x2=self.isorad.MIPSE0[flag2]/self.isorad.NSA[flag2]
else:
x=self.isorad.MIPS[flag]/self.isorad.NSA[flag]
x2=self.isorad.MIPS[flag2]/self.isorad.NSA[flag2]
y=self.s.fcre1[flag]*mipspixelscale/self.s.SERSIC_TH50[flag]
y2=self.s.fcre1[flag2]*mipspixelscale/self.s.SERSIC_TH50[flag2]
subplot(2,2,2)
hist(y2,bins=arange(0,2,.1),histtype='step')
xlabel('$R_{e}(24)/R_{e}(r) $',fontsize=20)
subplot(2,2,4)
hist(x,bins=arange(0,2,.1),histtype='step')
hist(x2,bins=arange(0,2,.1),histtype='step')
xlabel('$R_{iso}(24)/R_{iso}(r) $',fontsize=20)
axis([0,2,0,40])
subplot(1,2,1)
#color=self.logstellarmass[flag]
aflag=self.agnflag[flag]
mflag=self.membflag[flag]
color=log10(self.ssfr[flag2])
v1=ssfrmin
v2=ssfrmax
#color=(self.logstellarmass[flag])
#v1=mstarmin
#v2=mstarmax
#color=log10(self.s.SIGMA_5[flag])#maybe something
#color=(self.s.CLUSTER_PHI[flag])#maybe something
#color=log10(self.s.SIGMA_NN[flag])#nothing
#color=(self.dv[flag])#nothing
#color=(self.s.NUVr_color[flag])#yes, w/iso size
#color=(self.s.B_T_r[flag])#yes, w/Re size
#color=(self.s.AV[flag])#nah
#color=(self.s.HAEW[flag])#yes, something
#color=(self.s.SERSIC_N[flag])#yes, mainly with Re size
#color=(self.s.ZDIST[flag])#no
#color=(self.s.SERSIC_BA[flag])#no
#v1,v2=scoreatpercentile(color,[5.,80.])#,limit=[0,15])
#sp=scatter(x[aflag],y[aflag],s=70,marker='*',c=color[aflag],vmin=v1,vmax=v2,cmap='jet_r')
sp=scatter(x2,y2,s=20,c=color,vmin=v1,vmax=v2,cmap='jet_r')
#sp=scatter(x[~mflag],y[~mflag],s=20,marker='s',c=color[~mflag],vmin=v1,vmax=v2)
colorbar(sp)
#gca().set_yscale('log')
#gca().set_xscale('log')
#plot(x,y,'bo')
xlabel('$R_{iso}(24)/R_{iso}(r) $',fontsize=20)
ylabel('$R_{e}(24)/R_{e}(r) $',fontsize=20)
axis([.1,2.8,.1,2.8])
axis([-0.2,2.8,-0.2,2.8])
axvline(x=.7,ls='--',color='k')
axvline(x=1.2,ls='--',color='k')
axhline(y=1,ls='--',color='k')
axhline(y=.5,ls='--',color='k')
def plotconcentration(self,useE0=0):
figure(figsize=(10,6))
subplots_adjust(wspace=0.2,hspace=.35,bottom=.15,left=.1,top=.95,right=.95)
flag=(self.isorad.NSA > 0.) & (self.s.fcmag1 > 0) & (self.s.cnumerical_error_flag24 < .5)
flag2=(self.isorad.NSA > 0.)
if useE0:
x=self.isorad.MIPSE0[flag]/self.isorad.NSA[flag]
x2=self.isorad.MIPSE0[flag2]/self.isorad.NSA[flag2]
else:
x=self.isorad.MIPS[flag]/self.isorad.NSA[flag]
x2=self.isorad.MIPS[flag2]/self.isorad.NSA[flag2]
x=self.s.SERSIC_TH50[flag]/self.isorad.NSA[flag]
y=self.s.fcre1[flag]*mipspixelscale/self.isorad.MIPS[flag]
#y=self.s.fcre1[flag]*mipspixelscale/self.isorad.NSA[flag]
subplot(2,2,2)
hist(y,bins=arange(0,2,.1),histtype='step')
xlabel('$R_{e}(24)/R_{iso}(24) $',fontsize=20)
subplot(2,2,4)
hist(x,bins=arange(0,2,.1),histtype='step')
#hist(x2,bins=arange(0,2,.1),histtype='step')
xlabel('$R_{e}(r)/R_{iso}(r) $',fontsize=20)
#axis([0,2,0,40])
subplot(1,2,1)
color=self.logstellarmass[flag]
sp=scatter(x,y,s=100,c=color,vmin=8.5,vmax=11.5)
colorbar(sp)
gca().set_yscale('log')
gca().set_xscale('log')
#plot(x,y,'bo')
xlabel('$R_{e}(r)/R_{iso}(r) $',fontsize=20)
ylabel('$R_{e}(24)/R_{iso}(24) $',fontsize=20)
axis([.1,20,.1,20])
axvline(x=.5,ls='--',color='k')
#axvline(x=1.2,ls='--',color='k')
#axhline(y=1,ls='--',color='k')
axhline(y=.5,ls='--',color='k')
def plotsize_LIR(self):
figure(figsize=(12,10))
subplots_adjust(hspace=.3,wspace=.3)
subplot(2,3,1)
sp=scatter(log10(self.LIR_BEST[self.sampleflag]),self.s.SIZE_RATIO[self.sampleflag],s=60,c=self.logstellarmass[self.sampleflag],vmin=9,vmax=11)
colorbar(sp,fraction=0.08)
ylabel('$R_e(24)/R_e(r) $')
xlabel('$log_{10}(L_{IR})$')
subplot(2,3,2)
sp=scatter((self.logstellarmass[self.sampleflag]),self.s.SIZE_RATIO[self.sampleflag],s=60,c=log10(self.LIR_BEST[self.sampleflag]),vmin=9,vmax=11)
sp=scatter((self.logstellarmass[self.sampleflag]),self.size_ratio_corr[self.sampleflag],marker='*',s=20,c=log10(self.LIR_BEST[self.sampleflag]),vmin=9,vmax=11)
colorbar(sp,fraction=.08)
ylabel('$R_e(24)/R_e(r) $')
xlabel('$log_{10}(M_*)$')
subplot(2,3,4)
#plot(log10(self.LIR_BEST[self.sampleflag])-self.logstellarmass[self.sampleflag],self.s.SIZE_RATIO[self.sampleflag],'bo')#,c=self.LIR_BEST[self.sampleflag])
sp=scatter(log10(self.LIR_BEST[self.sampleflag])-self.logstellarmass[self.sampleflag],self.s.SIZE_RATIO[self.sampleflag],s=60,c=log10(self.LIR_BEST[self.sampleflag]),vmin=9, vmax=11)
colorbar(sp,fraction=.08)
ylabel('$R_e(24)/R_e(r) $')
xlabel('$log_{10}(L_{IR}/M_*)$')
subplot(2,3,3)
#plot(log10(self.LIR_BEST[self.sampleflag])-self.logstellarmass[self.sampleflag],self.s.SIZE_RATIO[self.sampleflag],'bo')#,c=self.LIR_BEST[self.sampleflag])
sp=scatter(self.logstellarmass[self.sampleflag],log10(self.LIR_BEST[self.sampleflag]),c=self.s.SIZE_RATIO[self.sampleflag],s=60,vmin=.1, vmax=1,cmap='jet_r')
xlabel('$log_{10}(M_*) $')
ylabel('$log_{10}(Lir) $')
colorbar(sp,fraction=.08)
subplot(2,3,5)
#plot(log10(self.LIR_BEST[self.sampleflag])-self.logstellarmass[self.sampleflag],self.s.SIZE_RATIO[self.sampleflag],'bo')#,c=self.LIR_BEST[self.sampleflag])
markercolor=(log10(self.LIR_BEST[self.sampleflag]))#-self.logstellarmass[self.sampleflag])
v1=9
v2=11
sp=scatter(self.s.SIZE_RATIO[self.sampleflag],self.s.fcnsersic1[self.sampleflag],c=markercolor,s=60,vmin=v1, vmax=v2,cmap='jet_r')
xlabel('$R_e(24)/R_e(r)$')
ylabel('$Sersic \ n$')
colorbar(sp,fraction=.08)
axis([-.09,1.2,-.02,6])
subplot(2,3,6)
markercolor=(log10(self.LIR_BEST[self.sampleflag])-self.logstellarmass[self.sampleflag])
v1=-2.
v2=.5
sp=scatter(self.s.SIZE_RATIO[self.sampleflag],self.s.fcnsersic1[self.sampleflag],c=markercolor,s=60,vmin=v1, vmax=v2,cmap='jet_r')
xlabel('$R_e(24)/R_e(r)$')
ylabel('$Sersic \ n$')
colorbar(sp,fraction=.08)
axis([-.09,1.2,-.02,6])
def agnfraction(self):
baseflag=self.sampleflag & self.sdssspecflag
print 'fraction of AGN among truncated galaxies = ',1.0*sum(self.agnflag[baseflag & self.truncflag])/len(self.agnflag[baseflag & self.truncflag])
print 'fraction of AGN among non-truncated galaxies = ',1.0*sum(self.agnflag[baseflag & ~self.truncflag])/len(self.agnflag[baseflag & self.truncflag])
print '##### ISO RADIUS #####'
baseflag=self.isosampleflag & self.sdssspecflag
print 'fraction of AGN among truncated galaxies = ',1.0*sum(self.agnflag[baseflag & self.isotruncflag])/len(self.agnflag[baseflag & self.isotruncflag])
print 'fraction of AGN among non-truncated galaxies = ',1.0*sum(self.agnflag[baseflag & ~self.isotruncflag])/len(self.agnflag[baseflag & self.isotruncflag])
def compare_single(self,var,baseflag=None,plotsingle=True,xlab=None,plotname=None):
if baseflag == None:
f1 = self.sampleflag & self.membflag & ~self.agnflag
f2 = self.sampleflag & ~self.membflag &self.dvflag & ~self.agnflag
else:
f1=baseflag & self.sampleflag & self.membflag & ~self.agnflag
f2=baseflag & self.sampleflag & ~self.membflag & self.dvflag & ~self.agnflag
xmin=min(var[baseflag])
xmax=max(var[baseflag])
#print 'xmin, xmax = ',xmin,xmax
print 'KS test comparing members and field'
(D,p)=ks(var[f1],var[f2])
#t=anderson.anderson_ksamp([var[f1],var[f2]])
#print '%%%%%%%%% ANDERSON %%%%%%%%%%%'
#print 'anderson statistic = ',t[0]
#print 'critical values = ',t[1]
#print 'p-value = ',t[2]
if plotsingle:
pl.figure()#figsize=(12,6))
pl.title('Member vs. Field ('+self.prefix+')')
pl.xlabel(xlab,fontsize=18)
#pl.ylabel('$Cumulative \ Distribution $',fontsize=20)
pl.legend(loc='lower right')
pl.hist(var[f1],bins=len(var[f1]),cumulative=True,histtype='step',normed=True,label='Member',range=(xmin,xmax),color='r')
#print var[f2]
pl.hist(var[f2],bins=len(var[f2]),cumulative=True,histtype='step',normed=True,label='Field',range=(xmin,xmax),color='b')
ylim(-.05,1.05)
ax=gca()
text(.8,.25,'$D = %4.2f$'%(D),horizontalalignment='right',transform=ax.transAxes,fontsize=16)
text(.8,.1,'$p = %5.4f$'%(p),horizontalalignment='right',transform=ax.transAxes,fontsize=16)
return D, p
def compare_cluster_field(self):
pl.figure(figsize=plotsize_single)
pl.subplots_adjust(bottom=.15,hspace=.4,top=.95)
pl.subplot(2,2,1)
self.compare_single((self.logstellarmass),baseflag=(self.sampleflag & ~self.agnflag & self.sbflag),plotsingle=False,xlab='$ log_{10}(M_*/M_\odot) $',plotname='stellarmass')
pl.legend(loc='upper left')
pl.xticks(np.arange(9,13,1))
pl.subplot(2,2,2)
self.compare_single(self.s.B_T_r,baseflag=(self.sampleflag & self.gim2dflag & self.sdssspecflag & ~self.agnflag),plotsingle=False,xlab='$GIM2D \ B/T $',plotname='BT')
pl.xticks(np.arange(0,.9,.2))
pl.subplot(2,2,3)
self.compare_single(self.s.SERSIC_TH50,baseflag=(self.sampleflag & ~self.agnflag),plotsingle=False,xlab='$NSA \ R_e(r) $',plotname='Rer')
pl.subplot(2,2,4)
self.compare_single(self.s.SERSIC_N,baseflag=(self.sampleflag & ~self.agnflag),plotsingle=False,xlab='$ NSA\ SERSIC \ N $',plotname='Rer')
pl.text(-1.5,1,'$Cumulative \ Distribution$',fontsize=22,transform=pl.gca().transAxes,rotation=90,verticalalignment='center')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/cluster_field.png')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/cluster_field.eps')
def compare_BT(self,isoflag=0,blueflag=False):
if isoflag:
self.compareiso(self.s.B_T_r,baseflag=(self.gim2dflag & self.sdssspecflag & ~self.agnflag),plotflag=1,xlab='$GIM2D \ B/T $',plotname='BTiso')
elif blueflag:
self.compare(self.s.B_T_r,baseflag=(self.bluesampleflag & self.gim2dflag & self.sdssspecflag & ~self.agnflag),plotflag=1,xlab='$GIM2D \ B/T $',plotname='BT')
else:
self.compare(self.s.B_T_r,baseflag=(self.sampleflag & self.gim2dflag & self.sdssspecflag & ~self.agnflag),plotflag=1,xlab='$GIM2D \ B/T $',plotname='BT')
def compare_BA(self,isoflag=0):
if isoflag:
self.compareiso(self.s.SERSIC_BA,baseflag=(self.isosampleflag & ~self.agnflag),plotflag=1,xlab='$B/A $',plotname='BAiso')
else:
self.compare(self.s.SERSIC_BA,baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$B/A $',plotname='BA')
def compare_redshift(self):
self.compare(self.s.ZDIST,baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ ZDIST $',plotname='ZDIST')
def compare_sersicn(self,isoflag=0):
if isoflag:
self.compareiso(self.s.fcnsersic1,baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ 24um \ SERSIC \ N $',plotname='sersicn24iso')
else:
self.compare(self.s.fcnsersic1,baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ 24um \ SERSIC \ N $',plotname='sersicn24')
def compare_ssfr(self,isoflag=0):
if isoflag:
print 'log(M*) < 10.41'
self.compareiso(self.ssfr,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass < 10.41)),plotflag=1,xlab='$sSFR $',plotname='ssfriso')
print 'log(M*) > 10.41'
self.compareiso(self.ssfr,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass > 10.41)),plotflag=1,xlab='$sSFR $',plotname='ssfriso')
else:
print 'log(M*) < 10.41'
self.compare(self.ssfr,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass < 10.41)),plotflag=1,xlab='$ sSFR$',plotname='ssfr_lm')
print 'log(M*) > 10.41'
self.compare(self.ssfr,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass > 10.41)),plotflag=1,xlab='$ sSFR$',plotname='ssfr_hm')
def compare_mass_bymass(self,isoflag=0):
x=self.logstellarmass
if isoflag:
print 'log(M*) < 10.41'
self.compareiso(x,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass < 10.41)),plotflag=1,xlab='$M* $',plotname='massiso_lm')
print 'log(M*) > 10.41'
self.compareiso(x,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass > 10.41)),plotflag=1,xlab='M* $',plotname='massiso_hm')
else:
print 'log(M*) < 10.41'
self.compare(x,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass < 10.41)),plotflag=1,xlab='$ M* \ (low \ mass)$',plotname='mass_lm')
print 'log(M*) > 10.41'
self.compare(x,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass > 10.41)),plotflag=1,xlab='$ M* \ (high \ mass)$',plotname='mass_hm')
def compare_BT_bymass(self,isoflag=0):
if isoflag:
print 'log(M*) < 10.41'
self.compareiso(self.s.B_T_r,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass < 10.41)),plotflag=1,xlab='$B/T \ iso \ (low \ mass) $',plotname='BTiso_lm')
print 'log(M*) > 10.41'
self.compareiso(self.s.B_T_r,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass > 10.41)),plotflag=1,xlab='$B/T \ iso \ (high \ mass) $',plotname='BTiso_hm')
else:
print 'log(M*) < 10.41'
self.compare(self.ssfr,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass < 10.41)),plotflag=1,xlab='$ B/T \ (low \ mass)$',plotname='BT_lm')
print 'log(M*) > 10.41'
self.compare(self.ssfr,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass > 10.41)),plotflag=1,xlab='$ B/T \ (high \ mass)$',plotname='BT_hm')
def compare_HAEW_conc(self,isoflag=0):
haflag=(self.s.HAEW > 0.1)
if isoflag:
self.compareiso(self.s.HAEW,baseflag=(self.sampleflag & ~self.agnflag & haflag & (self.logstellarmass < 10.41)),plotflag=1,xlab=r'$H\alpha \ EW $',plotname='haewiso')
else:
self.compare(self.s.HAEW,baseflag=(self.sampleflag & ~self.agnflag & haflag & (self.logstellarmass < 10.41)),plotflag=1,xlab=r'$H \alpha \ EW$',plotname='haew')
def compare_HI(self,isoflag=0):
if isoflag:
self.compareiso(self.s.HIDef,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass < 10.41) & self.HIflag),plotflag=1,xlab='$HI \ Def $',plotname='ssfriso')
else:
self.compare(self.s.HIDef,baseflag=(self.sampleflag & ~self.agnflag & (self.logstellarmass < 10.41) & self.HIflag),plotflag=1,xlab='$ HI \ Def$',plotname='ssfr')
def compare_nsasersicn(self,isoflag=0):
if isoflag:
self.compareiso(self.s.SERSIC_N,baseflag=(self.isosampleflag & ~self.agnflag),plotflag=1,xlab='$ r-band \ SERSIC \ N $',plotname='sersicnr')
else:
self.compare(self.s.SERSIC_N,baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ r-band \ SERSIC \ N $',plotname='sersicnr')
def compare_nsasersicth50(self):
self.compare(self.s.SERSIC_TH50,baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ r-band \ SERSIC \ R_e $',plotname='Rer')
def compare_stellarmass(self,isoflag=0):
if isoflag:
self.compareiso((self.logstellarmass),baseflag=(self.isosampleflag & ~self.agnflag),plotflag=1,xlab='$ log_{10}(M_*/M_\odot) $',plotname='stellarmassiso')
else:
self.compare((self.logstellarmass),baseflag=(self.sampleflag & ~self.agnflag & self.sbflag),plotflag=1,xlab='$ log_{10}(M_*/M_\odot) $',plotname='stellarmass')
def compare_stellarmasssurfden(self,isoflag=0):
if isoflag:
self.compareiso((self.logstellarmass-log10(pi*self.isorad.NSA**2)),baseflag=(self.isosampleflag & ~self.agnflag),plotflag=1,xlab='$ log_{10}(M_*/(\pi R_{iso}^2)) $',plotname='stellarmasssurfdeniso')
else:
self.compare((self.logstellarmass-log10(pi*self.isorad.NSA**2)),baseflag=(self.sampleflag & ~self.agnflag & self.sbflag),plotflag=1,xlab='$ log_{10}(M_*/M_\odot) $',plotname='stellarmasssurfden')
def compare_LIRstellarmass(self):
self.compare(np.log10(self.s.LIR_ZDIST/self.s.STELLARMASS),baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ log_{10}(L_{IR}/M_*) (L_\odot/M_\odot) $',plotname='LIRstellarmass')
def compare_LIR(self):
self.compare(np.log10(self.s.LIR_ZDIST),baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ log_{10}(L_{IR}) (L_\odot) $',plotname='LIR')
def compare_SFR24stellarmass(self,isoflag=0):
if isoflag:
self.compareiso(log10((self.s.SFR_ZDIST)/(10.**(self.logstellarmass-9))),baseflag=(self.isosampleflag & ~self.agnflag & (self.s.SFR_ZDIST > 0.)),plotflag=1,xlab='$log_{10}(sSFR_{24} (Gyr^{-1})) $',plotname='sSFR24iso')
else:
self.compare(np.log10(self.s.SFR_ZDIST/(self.s.STELLARMASS/1.e9)),baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ log_{10}(sSFR_{24} (Gyr^{-1})) $',plotname='sSFR24')
def compare_NUV24color(self,isoflag=0):
x=self.s.NUVr_color + self.s.RMAG - self.s.fcmag1
if isoflag:
self.compareiso(x,baseflag=(self.isosampleflag & ~self.agnflag),plotflag=1,xlab='$ NUV - 24$',plotname='NUV24coloriso')
else:
self.compare(x,baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ NUV - 24$',plotname='NUV24color')
def compare_dr(self,isoflag=0):
if isoflag:
self.compareiso(self.s.DR_R200,baseflag=(self.isosampleflag & self.dvflag & ~self.agnflag),plotflag=1,xlab='$ \Delta r/R_{200} $',plotname='drR200iso')
else:
self.compare(self.s.DR_R200,baseflag=(self.sampleflag & ~self.agnflag & self.dvflag),plotflag=1,xlab='$ \Delta r/R_{200} $',plotname='drR200')
def compare_drtrunc(self,isoflag=0):
if isoflag:
self.compareiso(self.s.DR_R200,baseflag=(self.isosampleflag & self.dvflag & ~self.agnflag),plotflag=1,xlab='$ \Delta r/R_{200} $',plotname='drR200iso')
else:
self.compare(self.s.DR_R200,baseflag=(self.sampleflag & ~self.agnflag & self.dvflag),plotflag=1,xlab='$ \Delta r/R_{200} $',plotname='drR200')
def compare_color(self):
self.compare(self.s.NUVr_color,baseflag=(self.sampleflag & ~self.agnflag ),plotflag=1,xlab='$ NUV - r $',plotname='NUVr')
def compare_mag24(self):
self.compare(self.s.fcmag1,baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ mag_{24} $',plotname='mag24')
def compare_asymi(self):
self.compare(self.s.ASYMMETRY[:,6],baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ ASYMMETRY \ i $',plotname='asymi')
def compare_asymu(self,isoflag=0):
if isoflag:
self.compareiso(self.s.ASYMMETRY[:,2],baseflag=(self.isosampleflag & ~self.agnflag),plotflag=1,xlab='$ ASYMMETRY \ u $',plotname='asymi')
else:
self.compare(self.s.ASYMMETRY[:,2],baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ ASYMMETRY \ u $',plotname='asymi')
def compare_clumpyi(self):
self.compare(self.s.CLUMPY[:,6],baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ CLUMPY \ i $',plotname='clumpyi')
def compare_clumpyu(self):
self.compare(self.s.CLUMPY[:,2],baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ CLUMPY \ u $',plotname='clumpyu')
def compare_pcs(self):
self.compare(self.s.p_cs,baseflag=(self.sampleflag & ~self.agnflag & self.zooflag),plotflag=1,xlab='$ p\_cs $',plotname='pcs')
def compare_pel(self):
self.compare(self.s.p_el,baseflag=(self.sampleflag & ~self.agnflag & self.zooflag),plotflag=1,xlab='$p\_el $',plotname='pel')
def compare_pedge(self):
self.compare(self.s.p_cs,baseflag=(self.sampleflag & ~self.agnflag & self.zooflag),plotflag=1,xlab='$ p\_cs $',plotname='pcs')
def compare_merger(self,isoflag=0):
if isoflag:
self.compareiso(self.s.p_mg,baseflag=( ~self.agnflag & self.zooflag),plotflag=1,xlab='$ p\_cs $',plotname='pcs')
else:
self.compare(self.s.p_mg,baseflag=(self.sampleflag & ~self.agnflag & self.zooflag),plotflag=1,xlab='$ p\_cs $',plotname='pcs')
def compare_n2(self):
self.compare(self.s.N2FLUX,baseflag=(self.sampleflag & ~self.agnflag & self.sdssspecflag &(self.s.N2FLUX > -5)),plotflag=1,xlab='$NII \ Flux $',plotname='n2')
def compare_av(self):
self.compare(self.s.AV,baseflag=(self.sampleflag & ~self.agnflag & self.emissionflag & (self.s.AV > -1.)),plotflag=1,xlab='$A_V$',plotname='av')
def compare_HImass(self,isoflag=0):
if isoflag:
self.compareiso(np.log10(self.s.HIMASS),baseflag=(self.isosampleflag & ~self.agnflag & self.HIflag),plotflag=1,xlab='$ log_{10}(M_{HI}/M_\odot )$',plotname='HImassiso')
else:
self.compare(np.log10(self.s.HIMASS),baseflag=(self.sampleflag & ~self.agnflag & self.HIflag),plotflag=1,xlab='$ log_{10}(M_{HI}/M_\odot )$',plotname='HImass')
def compare_HaEW(self,isoflag=0):
if isoflag:
self.compareiso(self.s.HAEW,baseflag=(self.isosampleflag & ~self.agnflag & self.sdssspecflag &(self.s.HAFLUX > -5)),plotflag=1,xlab='$ H-alpha \ EW $',plotname='haEWiso')
else:
self.compare(self.s.HAEW,baseflag=(self.sampleflag & ~self.agnflag & self.sdssspecflag &(self.s.HAFLUX > -5)),plotflag=1,xlab='$ H-alpha \ EW $',plotname='haEW')
def compare_Ha(self):
self.compare(self.s.HAFLUX,baseflag=(self.sampleflag & ~self.agnflag & self.sdssspecflag &(self.s.HAFLUX > -5)),plotflag=1,xlab='$ H-alpha \ flux $',plotname='ha')
def compare_Hb(self):
self.compare(self.s.HAFLUX,baseflag=(self.sampleflag & ~self.agnflag & self.sdssspecflag &(self.s.HAFLUX > -5)),plotflag=1,xlab='$ H-alpha \ flux $',plotname='hb')
def compare_gasfrac(self,isoflag=0):
if isoflag:
self.compareiso(np.log10(self.s.HIMASS/self.s.STELLARMASS),baseflag=(self.isosampleflag & ~self.agnflag & self.HIflag),plotflag=1,xlab='$ log_{10}(M_{HI}/M_* )$',plotname='HImassfrac')
else:
self.compare(np.log10(self.s.HIMASS/self.s.STELLARMASS),baseflag=(self.sampleflag & ~self.agnflag & self.HIflag),plotflag=1,xlab='$ log_{10}(M_{HI}/M_* )$',plotname='HImassfrac')
def compare_localdens(self,isoflag=0):
if isoflag:
self.compareiso(self.s.SIGMA_NN,baseflag=(self.isosampleflag & ~self.agnflag),plotflag=1,xlab='$ \Sigma_{NN} $',plotname='SIGMANNiso')
self.compareiso(self.s.SIGMA_5,baseflag=(self.isosampleflag & ~self.agnflag),plotflag=1,xlab='$ \Sigma_{5} $',plotname='SIGMA5iso')
self.compareiso(self.s.SIGMA_10,baseflag=(self.isosampleflag & ~self.agnflag),plotflag=1,xlab='$ \Sigma_{10} $',plotname='SIGMA10iso')
else:
self.compare(self.s.SIGMA_NN,baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ \Sigma_{NN} $',plotname='SIGMANN')
self.compare(self.s.SIGMA_5,baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ \Sigma_{5} $',plotname='SIGMA5')
self.compare(self.s.SIGMA_10,baseflag=(self.sampleflag & ~self.agnflag),plotflag=1,xlab='$ \Sigma_{10} $',plotname='SIGMA10')
def plot_colorcolor24(self):
# plot u-r vs r-24
# color code by (1) sSFR, (2) M*, (3) M*/pire^2, (4) M*/piRiso^2, (5) size_re, (6) size_iso
figure(figsize=(10,8))
subplots_adjust(wspace=.01,hspace=.01,bottom=.1,top=.95,left=.1,right=.95)
colors=[log10(self.ssfr),self.logstellarmass,self.s.SIZE_RATIO,self.isosize]
v1=[ssfrmin,mstarmin,0,0]
v2=[ssfrmax,mstarmax,1.5,1.5]
cmaps=['jet_r','jet','jet_r','jet_r']
colorlabel=['$log_{10}(sSFR_{24})$','$log_{10}(M_*)$','$R_e(24)/R_e(r)$','$R_{iso}(24)/R_{iso}(r)$']
cbticks=[arange(ssfrmin,ssfrmax+1,1),arange(9.5,12.5,1),arange(0,1.8,.4),arange(0,1.8,.4)]
y=self.nsamag[:,2] - self.nsamag[:,4]
x=self.nsamag[:,4]-self.mag24
#x=self.nsamag[:,4]-self.s.fcmag1
flag=self.isosampleflag
for i in range(len(colors)):
subplot(2,2,i+1)
#hexbin(x[flag],y[flag],C=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i],gridsize=7,alpha=0.5)#,extent=(0,2.,0,1.5))
sp=scatter(x[flag],y[flag],s=40,c=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i])
ax=gca()
text(.78,.05,colorlabel[i],transform=ax.transAxes,horizontalalignment='right',fontsize=18)
if i < 2:
ax.set_xticklabels(([]))
if i in [1,3]:
ax.set_yticklabels(([]))
axis([-5,5,.3,3.1])
axins1 = inset_axes(ax,
width="5%", # width = 10% of parent_bbox width
height="40%", # height : 50%
bbox_to_anchor=(.8,0.05,1,1),
bbox_transform=ax.transAxes,
borderpad=0,
loc=3)
cb=colorbar(sp,cax=axins1,ticks=cbticks[i])
yl='$u - r$'
xl='$r - 24$'
text(-.0,-.15,xl,transform=ax.transAxes,horizontalalignment='center',fontsize=28)
text(-1.2,1,yl,transform=ax.transAxes,verticalalignment='center',fontsize=28,rotation=90)
savefig(homedir+'research/LocalClusters/SamplePlots/colorcolor24.png')
savefig(homedir+'research/LocalClusters/SamplePlots/colorcolor24.eps')
def plot_r24colormag(self):
# plot u-r vs r-24
# color code by (1) sSFR, (2) M*, (3) M*/pire^2, (4) M*/piRiso^2, (5) size_re, (6) size_iso
figure(figsize=(8,6))
subplots_adjust(wspace=.01,hspace=.01,bottom=.15,top=.95,left=.1,right=.95)
colors=[log10(self.ssfr),self.logstellarmass,self.s.SIZE_RATIO,self.s.p_cs]
v1=[ssfrmin,mstarmin,.0,0]
v2=[ssfrmax,mstarmax,1,1.]
cmaps=['jet_r','jet','jet_r','jet_r']
colorlabel=['$log_{10}(sSFR_{24})$','$log_{10}(M_*)$','$R_e(24)/R_e(r)$','$Zoo \ p_{cs}$']
cbticks=[arange(ssfrmin,ssfrmax+1,1),arange(9.5,12.5,1),arange(0,1.8,.4),arange(0,1.8,.4)]
#x=self.nsamag[:,4]
x=self.gi_corr
y=self.nsamag[:,4]-self.mag24
#x=self.nsamag[:,4]-self.s.fcmag1
flag=self.sampleflag
nplot=1
for i in range(4):
subplot(2,2,nplot)
nplot += 1
#hexbin(x[flag],y[flag],C=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i],gridsize=7,alpha=0.5)#,extent=(0,2.,0,1.5))
sp=scatter(x[flag],y[flag],s=40,c=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i])
ax=gca()
text(.78,.05,colorlabel[i],transform=ax.transAxes,horizontalalignment='right',fontsize=18)
if i < 2:
ax.set_xticklabels(([]))
if i in [1,3]:
ax.set_yticklabels(([]))
axis([-.5,2,-6,5])
axins1 = inset_axes(ax,
width="5%", # width = 10% of parent_bbox width
height="40%", # height : 50%
bbox_to_anchor=(.8,0.05,1,1),
bbox_transform=ax.transAxes,
borderpad=0,
loc=3)
cb=colorbar(sp,cax=axins1,ticks=cbticks[i])
xl='$g - r$'
yl='$r - 24$'
text(-.0,-.2,xl,transform=ax.transAxes,horizontalalignment='center',fontsize=28)
text(-1.2,1.,yl,transform=ax.transAxes,verticalalignment='center',fontsize=28,rotation=90)
savefig(homedir+'research/LocalClusters/SamplePlots/colormag24.png')
savefig(homedir+'research/LocalClusters/SamplePlots/colormag24.eps')
def plot_salim07colormag_old(self,sbcutobs=20.5):
figure(figsize=(10,5))
subplots_adjust(bottom=.15,left=.1,wspace=.05)
v1=0.1
v2=1.
xl='$M_r$'
yl='$NUV - r$'
limits=[-22.8,-16.8,.5,6.9]
y=self.nsamag[:,1] - self.nsamag[:,4]
x=self.s.ABSMAG[:,4]
subplot(1,2,1)
flag=self.sfsampleflag & ~self.sampleflag & ~self.agnflag
plot(x[flag],y[flag],'kx',markersize=8,label='No Fit')
flag=self.sampleflag & ~self.agnflag
z=self.s.SIZE_RATIO
sp=scatter(x[flag],y[flag],c=z[flag],s=50,vmin=v1,vmax=v2,cmap='jet_r')
xlabel(xl,fontsize=22)
ylabel(yl,fontsize=22)
axis(limits)
ax1=gca()
#text(0.9,0.9,'$SF $',transform=gca().transAxes,horizontalalignment='right',fontsize=20)
title('$SF \ Galaxies$',fontsize=20)
subplot(1,2,2)
flag=self.sfsampleflag & ~self.sampleflag & self.agnflag
plot(x[flag],y[flag],'kx',markersize=8,label='No Fit')
flag=self.sampleflag & self.agnflag
z=self.s.SIZE_RATIO
sp=scatter(x[flag],y[flag],c=z[flag],s=50,vmin=v1,vmax=v2,cmap='jet_r')
ax2=gca()
cb=colorbar(ax=[ax1,ax2],fraction=0.03)
xl='$M_r$'
yl='$NUV - r$'
xlabel(xl,fontsize=22)
gca().set_yticks([])
axis(limits)
#text(0.9,0.9,'$AGN $',transform=gca().transAxes,horizontalalignment='right',fontsize=20)
title('$AGN$',fontsize=20)
savefig(homedir+'research/LocalClusters/SamplePlots/salim_colormag.png')
savefig(homedir+'research/LocalClusters/SamplePlots/salim_colormag.eps')
def plot_colorcolor(self):
figure()
x=self.nsamag[:,2] - self.nsamag[:,4]
#x=self.gi_corr
y=self.nsamag[:,1]-self.s.fcmag1
flag=self.sampleflag & ~self.agnflag
#plot(x[flag],y[flag],'bo')
flag=self.sampleflag & ~self.agnflag
#plot(x[flag],y[flag],'ro')
xl='$u - r$'
yl='$NUV - 24$'
xlabel(xl,fontsize=20)
ylabel(yl,fontsize=20)
figure()
flag=self.sampleflag & ~self.agnflag
z=self.s.SIZE_RATIO
sp=scatter(x[flag],y[flag],c=z[flag],vmin=.0,vmax=1.,cmap='jet_r')
cb=colorbar(sp)
xlabel(xl,fontsize=20)
ylabel(yl,fontsize=20)
def plot_wolfcolor(self):
figure(figsize=(6,4))
subplots_adjust(bottom=.15,left=.15)
x=self.nsamag[:,4] - self.nsamag[:,5]
#y=self.s.NUVr_color
y=self.nsamag[:,2]-self.nsamag[:,3]
flag=self.sampleflag & ~self.agnflag
plot(x[flag],y[flag],'bo')
flag=self.sampleflag & self.agnflag
plot(x[flag],y[flag],'ro')
xlabel('$r - i$',fontsize=20)
ylabel('$u - g$',fontsize=20)
axis([-.2,.8,.2,2.5])
figure(figsize=(6,4))
subplots_adjust(bottom=.15,left=.15)
flag=self.sampleflag & ~self.agnflag
z=self.s.SIZE_RATIO
sp=scatter(x[flag],y[flag],c=z[flag],vmin=0.1,vmax=1.,cmap='jet_r')
cb=colorbar(sp, fraction=0.08)
axis([-.2,.8,.2,2.5])
xlabel('$r - i$',fontsize=20)
ylabel('$u - g$',fontsize=20)
def plot_ReRiso(self):
# plot r-band concentratio vs 24-micron concentration
# color code by (1) sSFR, (2) M*, (3) M*/pire^2, (4) M*/piRiso^2
figure(figsize=(10,8))
subplots_adjust(wspace=.01,hspace=.01,bottom=.1,top=.95,left=.1,right=.95)
colors=[log10(self.ssfr),self.logstellarmass,self.logstellarmass-log10(2*pi*self.s.SERSIC_TH50**2*self.s.SERSIC_BA),self.logstellarmass-log10(2*pi*self.isorad.NSA**2*self.s.SERSIC_BA)]
v1=[ssfrmin,mstarmin,7,7]
v2=[ssfrmax,mstarmax,9,9]
cmaps=['jet_r','jet','jet_r','jet_r']
colorlabel=['$log_{10}(sSFR_{24})$','$log_{10}(M_*)$','$M_*/\pi R_e(r)^2$','$M_* / \pi R_{iso}^2$']
cbticks=[arange(ssfrmin,ssfrmax+1,1),arange(9.5,12.5,1),arange(v1[2],v2[2]+1,1),arange(v1[3],v2[3]+1,1)]
#y=self.s.fcre1*mipspixelscale/self.isorad.MIPS
#x=self.s.SERSIC_TH50/self.isorad.NSA
y=self.s.fcre1*mipspixelscale/self.s.SERSIC_TH50
x=self.isorad.MIPS/self.isorad.NSA
flag=self.isosampleflag & (self.s.cnumerical_error_flag24 < .1)
for i in range(len(colors)):
subplot(2,2,i+1)
axis([-.1,2.2,-.1,1.9])
#hexbin(x[flag],y[flag],C=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i],gridsize=7,alpha=0.5,extent=(0,2.,0,1.5))
sp=scatter(x[flag],y[flag],s=40,c=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i])
ax=gca()
text(.8,.9,colorlabel[i],transform=ax.transAxes,horizontalalignment='right',fontsize=18)
if i < 2:
ax.set_xticklabels(([]))
if i in [1,3]:
ax.set_yticklabels(([]))
drawbox([1.1,.7,.6,.6,0],'k-')
axins1 = inset_axes(ax,
width="5%", # width = 10% of parent_bbox width
height="40%", # height : 50%
bbox_to_anchor=(.82,0.55,1,1),
bbox_transform=ax.transAxes,
borderpad=0,
loc=3)
cb=colorbar(sp,cax=axins1,ticks=cbticks[i])
yl='$R_e(24)/R_{e}(r)$'
xl='$R_{iso}(24)/R_{iso}(r)$'
text(-.0,-.15,xl,transform=ax.transAxes,horizontalalignment='center',fontsize=28)
text(-1.2,1,yl,transform=ax.transAxes,verticalalignment='center',fontsize=28,rotation=90)
savefig(homedir+'research/LocalClusters/SamplePlots/concentration.png')
savefig(homedir+'research/LocalClusters/SamplePlots/concentration.eps')
def plot_ReRisoenv(self):
# plot r-band concentratio vs 24-micron concentration
# color code by (1) sSFR, (2) M*, (3) M*/pire^2, (4) M*/piRiso^2
figure(figsize=(10,8))
subplots_adjust(wspace=.01,hspace=.01,bottom=.1,top=.95,left=.1,right=.95)
colors=[log10(self.s.SIGMA_5),self.s.DR_R200,self.s.CLUSTER_PHI,self.s.HIDef]
v1=[-.5,0,0,0]
v2=[1.5,2,90,1]
cmaps=['jet_r','jet','jet_r','jet_r']
colorlabel=['$log_{10}(\Sigma_{5})$','$\Delta r/R_{200}$','$\Phi$','$HI \ Def$']
cbticks=[arange(v1[0],v2[0]+1,1),arange(v1[1],v2[1]+1,1),arange(v1[2],v2[2]+1,20),arange(v1[3],v2[3]+1,1)]
#y=self.s.fcre1*mipspixelscale/self.isorad.MIPS
#x=self.s.SERSIC_TH50/self.isorad.NSA
y=self.s.fcre1*mipspixelscale/self.s.SERSIC_TH50
x=self.isorad.MIPS/self.isorad.NSA
flag=self.isosampleflag & (self.s.cnumerical_error_flag24 < .1) & (self.dvflag)
for i in range(len(colors)):
subplot(2,2,i+1)
hexbin(x[flag],y[flag],C=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i],gridsize=7,alpha=0.5,extent=(0,2.,0,1.5))
sp=scatter(x[flag],y[flag],s=40,c=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i])
ax=gca()
text(.8,.9,colorlabel[i],transform=ax.transAxes,horizontalalignment='right',fontsize=18)
if i < 2:
ax.set_xticklabels(([]))
if i in [1,3]:
ax.set_yticklabels(([]))
axis([-.1,2.2,-.1,1.9])
drawbox([1.1,.7,.6,.6,0],'k-')
axins1 = inset_axes(ax,
width="5%", # width = 10% of parent_bbox width
height="40%", # height : 50%
bbox_to_anchor=(.82,0.55,1,1),
bbox_transform=ax.transAxes,
borderpad=0,
loc=3)
cb=colorbar(sp,cax=axins1,ticks=cbticks[i])
yl='$R_e(24)/R_{e}(r)$'
xl='$R_{iso}(24)/R_{iso}(r)$'
text(-.0,-.15,xl,transform=ax.transAxes,horizontalalignment='center',fontsize=28)
text(-1.2,1,yl,transform=ax.transAxes,verticalalignment='center',fontsize=28,rotation=90)
savefig(homedir+'research/LocalClusters/SamplePlots/concentration.png')
savefig(homedir+'research/LocalClusters/SamplePlots/concentration.eps')
def plot_Risoenv(self):
# plot r-band concentratio vs 24-micron concentration
# color code by (1) sSFR, (2) M*, (3) M*/pire^2, (4) M*/piRiso^2
figure(figsize=(10,8))
subplots_adjust(wspace=.01,hspace=.01,bottom=.1,top=.95,left=.1,right=.95)
colors=[log10(self.s.SIGMA_5),self.s.DR_R200,log10(self.ssfr),self.logstellarmass-log10(2*pi*self.s.SERSIC_TH50**2*self.s.SERSIC_BA)]
v1=[-.2,0,-12,6.5]
v2=[1.2,2.5,-9,8.5]
cmaps=['jet','jet_r','jet_r','jet']
colorlabel=['$log_{10}(\Sigma_{5})$','$\Delta r/R_{200}$','$log_{10}(sSFR)$','$log_{10}(M_*/\pi R_e^2)$']
cbticks=[arange(v1[0],v2[0]+1,1),arange(v1[1],v2[1]+1,1),arange(v1[2],v2[2]+1,1),arange(v1[3],v2[3]+1,1)]
#y=self.s.fcre1*mipspixelscale/self.isorad.MIPS
#x=self.s.SERSIC_TH50/self.isorad.NSA
x=self.logstellarmass
y=self.isorad.MIPS/self.isorad.NSA
flag=self.isosampleflag & (self.dvflag)
for i in range(len(colors)):
subplot(2,2,i+1)
hexbin(x[flag],y[flag],C=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i],gridsize=7,alpha=0.5,extent=(8.5,11.5,0,1.5))
sp=scatter(x[flag],y[flag],s=40,c=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i])
ax=gca()
text(.8,.9,colorlabel[i],transform=ax.transAxes,horizontalalignment='right',fontsize=18)
if i < 2:
ax.set_xticklabels(([]))
if i in [1,3]:
ax.set_yticklabels(([]))
axis([8,12.5,-.1,1.9])
#drawbox([1.1,.7,.6,.6,0],'k-')
axins1 = inset_axes(ax,
width="5%", # width = 10% of parent_bbox width
height="40%", # height : 50%
bbox_to_anchor=(.82,0.55,1,1),
bbox_transform=ax.transAxes,
borderpad=0,
loc=3)
cb=colorbar(sp,cax=axins1,ticks=cbticks[i])
xl='$M_* (M_\odot)$'
yl='$R_{iso}(24)/R_{iso}(r)$'
text(-.0,-.15,xl,transform=ax.transAxes,horizontalalignment='center',fontsize=28)
text(-1.2,1,yl,transform=ax.transAxes,verticalalignment='center',fontsize=28,rotation=90)
savefig(homedir+'research/LocalClusters/SamplePlots/isosizeenv.png')
savefig(homedir+'research/LocalClusters/SamplePlots/isosizeenv.eps')
def plot_Rmasscolor(self,colors,v1,v2,cmaps,colorlabel,cbticks,reflag=1):
# plot r-band concentratio vs 24-micron concentration
# color code by (1) sSFR, (2) M*, (3) M*/pire^2, (4) M*/piRiso^2
figure(figsize=(10,8))
subplots_adjust(wspace=.01,hspace=.01,bottom=.1,top=.95,left=.1,right=.95)
#y=self.s.fcre1*mipspixelscale/self.isorad.MIPS
#x=self.s.SERSIC_TH50/self.isorad.NSA
x=self.logstellarmass
if reflag:
y=self.s.fcre1*mipspixelscale/self.s.SERSIC_TH50
flag=self.sampleflag & (self.dvflag) & ~self.agnflag
else:
y=self.isorad.MIPS/self.isorad.NSA
flag=self.isosampleflag & (self.dvflag)& ~self.agnflag
for i in range(len(colors)):
subplot(2,2,i+1)
hexbin(x[flag],y[flag],C=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i],gridsize=7,alpha=0.5,extent=(8.5,11.5,0,1.5))
sp=scatter(x[flag],y[flag],s=40,c=colors[i][flag],vmin=v1[i],vmax=v2[i],cmap=cmaps[i])
ax=gca()
text(.8,.9,colorlabel[i],transform=ax.transAxes,horizontalalignment='right',fontsize=18)
if i < 2:
ax.set_xticklabels(([]))
if i in [1,3]:
ax.set_yticklabels(([]))
axis([8,12.5,-.1,1.9])
#drawbox([1.1,.7,.6,.6,0],'k-')
axins1 = inset_axes(ax,
width="5%", # width = 10% of parent_bbox width
height="40%", # height : 50%
bbox_to_anchor=(.82,0.55,1,1),
bbox_transform=ax.transAxes,
borderpad=0,
loc=3)
cb=colorbar(sp,cax=axins1,ticks=cbticks[i])
xl='$M_* (M_\odot)$'
if reflag:
yl='$R_{e}(24)/R_{e}(r)$'
else:
yl='$R_{iso}(24)/R_{iso}(r)$'
text(-.0,-.15,xl,transform=ax.transAxes,horizontalalignment='center',fontsize=28)
text(-1.2,1,yl,transform=ax.transAxes,verticalalignment='center',fontsize=28,rotation=90)
def plotRenv1(self):
colors=[log10(self.s.SIGMA_5),self.s.DR_R200,log10(self.ssfr),self.logstellarmass-log10(2*pi*self.s.SERSIC_TH50**2*self.s.SERSIC_BA)]
v1=[-.2,0,-12,6.5]
v2=[1.2,2.,-9,8.5]
cmaps=['jet','jet_r','jet_r','jet']
colorlabel=['$log_{10}(\Sigma_{5})$','$\Delta r/R_{200}$','$log_{10}(sSFR)$','$log_{10}(M_*/\pi R_e^2)$']
cbticks=[arange(v1[0],v2[0]+1,1),arange(v1[1],v2[1]+1,1),arange(v1[2],v2[2]+1,1),arange(v1[3],v2[3]+1,1)]
self.plot_Rmasscolor(colors,v1,v2,cmaps,colorlabel,cbticks)
savefig(homedir+'research/LocalClusters/SamplePlots/Resizeenv1.png')
savefig(homedir+'research/LocalClusters/SamplePlots/Resizeenv1.eps')
self.plot_Rmasscolor(colors,v1,v2,cmaps,colorlabel,cbticks,reflag=0)
savefig(homedir+'research/LocalClusters/SamplePlots/Risosizeenv1.png')
savefig(homedir+'research/LocalClusters/SamplePlots/Risosizeenv1.eps')
def plotRenv2(self):
colors=[log10(self.s.HAEW),self.s.CLUSTER_LX*self.membflag + zeros(len(self.s.CLUSTER),'f')*~self.membflag,self.s.B_T_r,self.s.SERSIC_N]
v1=[0,0,0,0.5]
v2=[2,3,.5,4]
cmaps=['jet_r','jet','jet','jet']
colorlabel=[r'$log_{10}(H \alpha \ EW)$','$L_X$','$B/T$','$Sersic_n$']
cbticks=[arange(v1[0],v2[0]+1,1),arange(v1[1],v2[1]+1,2),arange(v1[2],v2[2]+1,.2),arange(v1[3],v2[3]+1,1)]
self.plot_Rmasscolor(colors,v1,v2,cmaps,colorlabel,cbticks)
savefig(homedir+'research/LocalClusters/SamplePlots/Resizeenv2.png')
savefig(homedir+'research/LocalClusters/SamplePlots/Resizeenv2.eps')
self.plot_Rmasscolor(colors,v1,v2,cmaps,colorlabel,cbticks,reflag=0)
savefig(homedir+'research/LocalClusters/SamplePlots/Risosizeenv2.png')
savefig(homedir+'research/LocalClusters/SamplePlots/Risosizeenv2.eps')
def plotSNRSE_LIR(self):
for i in range(len(clusternames)):
c=clusternames[i]
flag= (c == self.s.CLUSTER)
plot(log10(self.s.LIR_ZDIST[flag]),self.s.SNR_SE[flag],'k.',color=colors[i],marker=shapes[i])
def plotall(self):
self.compare_BT()
self.compare_sersicn()
self.compare_dr()
self.compare_color()
self.compare_mag24()
self.compare_asymu()
#self.compare_clumpyu()
self.compare_pcs()
self.compare_pel()
self.compare_nsasersicn()
self.compare_localdens()
#self.compare_n2()
self.compare_HaEW()
self.compare_Ha()
self.compare_Hb()
self.compare_av()
self.compare_gasfrac()
self.compare_SFR24stellarmass()
self.compare_NUV24color()
self.compare(self.s.SNR_SE,baseflag=self.sampleflag,plotflag=1,xlab='$ SNR\_SE $',plotname='SNRSE')
self.compare(np.log10(self.s.LIR_ZDIST),baseflag=self.sampleflag,plotflag=1,xlab='$ log_{10}(LIR\_ZDIST/L_\odot) $',plotname='LIRZDIST')
#self.compare_nsasersicth50()
def compare_all(self,inputcolumns,tablesuffix=''):
allcolumns=nsa_columns+n_columns+galfit24_columns+gim2d_columns+zoo_columns+ce_columns+ld_columns+my_columns
allcolumns=inputcolumns
sdssspecflag=['D4000','HAEW','VDISP','HAFLUX','N2FLUX','HBFLUX','O3FLUX','AHDEW','AV']
cnames=[]
d1=[]
p1=[]
d2=[]
p2=[]
for name in allcolumns:
print '******************************************'
baseflag=self.sampleflag & ~self.agnflag & self.sbflag
if name in sdssspecflag:
baseflag=baseflag & self.emissionflag #& self.sdssspecflag
if name in gim2d_columns:
baseflag = baseflag & self.gim2dflag
if name in zoo_columns:
baseflag = baseflag & self.zooflag
if name.find('HI') > -1:
baseflag = baseflag & self.HIflag
if (name.find('CLUMPY') > -1) | (name.find('ASYMMETRY') > -1):
for j in range(7):
print '################################'
print name+'[:,'+str(j)+']'
a,b,c,d=self.compare(self.s[name][:,j],baseflag=baseflag)
d1.append(a)
p1.append(b)
d2.append(c)
p2.append(d)
cnames.append(name+'[:,'+str(j)+']')
else:
print name
#t=self.compare(self.s[name],baseflag=baseflag)
#print t
a,b,c,d=self.compare(self.s[name],baseflag=baseflag)
print a,b,c,d
d1.append(a)
p1.append(b)
d2.append(c)
p2.append(d)
cnames.append(name)
self.d1=d1
self.p1=p1
self.d2=d2
self.p2=p2
self.cnames=cnames
self.ksresults=Table()
arrays=[self.cnames,self.d1,self.p1,self.d2,self.p2]
colnames=['VARIABLE','KSD-CF','KSP-CF','KSD-TN','KSP-TN']
datatypes=['S16','f','f','f','f']
print 'got here 1'
for i in range(len(self.cnames)):
self.cnames[i]=self.cnames[i].replace('_','\_')
print self.cnames
newcol=Column(data=np.array(self.cnames,'S16'),name='VARIABLE',format='%16s')
self.ksresults.add_column(newcol)
print 'got here 2'
newcol=Column(data=np.array(self.d1,'f'),name=colnames[1],format='%5.4f')
self.ksresults.add_column(newcol)
print 'got here 3'
newcol=Column(data=np.array(self.p1,'f'),name=colnames[2],format='%5.4f')
self.ksresults.add_column(newcol)
print 'got here 4'
newcol=Column(data=np.array(self.d2,'f'),name=colnames[3],format='%5.4f')
self.ksresults.add_column(newcol)
print 'got here 5'
newcol=Column(data=np.array(self.p2,'f'),name=colnames[4],format='%5.4f')
self.ksresults.add_column(newcol)
outfile=homedir+'research/LocalClusters/NSAmastertables/KS_results'+tablesuffix+'.tex'
print outfile
self.ksresults.write(outfile,format='latex')
def plotsizevsStellarmass(self,plotsingle=1,plotagn=0):
pflag=self.sampleflag & ~self.agnflag #& self.membflag
if plotsingle:
figure()
subplots_adjust(bottom=.15,left=.15)
plot(self.logstellarmass[pflag & ~self.upperlimit],self.s.SIZE_RATIO[pflag & ~self.upperlimit],'ko',label='Star-Forming')
spearman(self.logstellarmass[pflag & ~self.upperlimit],self.s.SIZE_RATIO[pflag & ~self.upperlimit])
xbin,ybin,ybinerr=my.binit(self.logstellarmass[pflag & ~self.upperlimit],self.s.SIZE_RATIO[pflag & ~self.upperlimit],4)
plot(xbin,ybin,'bo',markersize=16,label='Binned SF')
errorbar(xbin,ybin,ybinerr,fmt=None,ecolor='k',label='_nolegend_')
plot(self.logstellarmass[pflag & self.upperlimit & ~self.pointsource],self.s.SIZE_RATIO[pflag & self.upperlimit & ~self.pointsource],'kv',markersize=10)
plot(self.logstellarmass[pflag & self.pointsource],self.s.SIZE_RATIO[pflag & self.pointsource],'k*',markersize=10)
if plotagn:
plot(self.logstellarmass[self.sampleflag & self.AGNKAUFF],self.s.SIZE_RATIO[self.sampleflag & self.AGNKAUFF],'k*',mec='0.5',mfc='None',markersize=10,label='AGN')
plot(self.logstellarmass[self.sampleflag & self.unknownagn],self.s.SIZE_RATIO[self.sampleflag & self.unknownagn],'k*',mec='c',mfc='None',markersize=10,label='AGN-unknown')
axis([9,11,.1,3])
gca().set_yscale('log')
legend(numpoints=1)
xlabel('$log_{10}(M_*/M_\odot) $',fontsize=20)
ylabel('$R_e(24)/R_e(r) $',fontsize=20)
def plothistssfr(self,minmass=None,maxmass=None,plotsingle=True,sfms=False):
'''
sfms flag normalizes sSFR by sSFR of MS = 0.08
'''
if plotsingle:
pl.figure()
pl.subplots_adjust(bottom=.15,left=.15)
f1=self.lirflag & self.membflag & ~self.agnflag
f2=self.lirflag & ~self.membflag & ~self.agnflag
if minmass != None:
f1 = f1 & (self.logstellarmass > minmass)
f2 = f2 & (self.logstellarmass > minmass)
if maxmass != None:
f1 = f1 & (self.logstellarmass < maxmass)
f2 = f2 & (self.logstellarmass < maxmass)
normfactor = 1.e9
mybins=arange(-2.2,1,.2)
# uncomment if you want to normalize by mass of sfms
if sfms:
normfactor=1.e9/.08
mybins=arange(-2.2,1,.2)
pl.hist(log10(self.ssfr[f1]*normfactor),bins=mybins,histtype='step',label='Cluster',color='r',hatch='\\',normed=True)
pl.hist(log10(self.ssfr[f2]*normfactor),bins=mybins,histtype='step',label='Field',color='b',hatch='/',normed=True)
ssfr1=np.log10(self.ssfr[f1]*normfactor)
ssfr2=np.log10(self.ssfr[f2]*normfactor)
print 'CLUSTER sSFR: mean (median) +/- std (error mean) = %5.2f (%5.2f) +/- %5.2f (%5.2f)'%(np.mean(ssfr1),np.median(ssfr1),np.std(ssfr1),np.std(ssfr1)/np.sqrt(1.*sum(f1)))
print 'CLUSTER N_TOTAL:', sum(f1)
print 'FIELD sSFR: mean (median) +/- std (error mean) = %5.2f (%5.2f) +/- %5.2f (%5.2f)'%(np.mean(ssfr2),np.median(ssfr2),np.std(ssfr2),np.std(ssfr2)/np.sqrt(1.*sum(f2)))
print 'FIELD N_TOTAL:', sum(f2)
if plotsingle:
if sfms:
pl.xlabel('$log_{10}(sSFR/sSFR_{MS}) $')
pl.axvline(x=0,ls='--',color='k')
else:
pl.xlabel('$log_{10}(sSFR/Gyr) $')
pl.ylabel('$ Frequency $')
pl.legend(loc='upper left')
print 'comparing sSFR:'
ks(ssfr1,ssfr2)
print 'comparing Stellar Mass:'
ks(self.logstellarmass[f1],self.logstellarmass[f2])
print 'comparing Re(24)/Re(r):'
ks(self.logstellarmass[f1 & self.sampleflag],self.logstellarmass[f2 & self.sampleflag])
print np.mean(self.logstellarmass[f1]),np.mean(self.logstellarmass[f2])
def plotssfrhistbymass(self):
pl.figure()
m1=[9.3,9.8,10.3]
m2=[9.8,10.3,10.8]
for i in range(3):
pl.subplot(3,1,i+1)
print '#######################################'
print '##### ',m1[i],'< log(M) < ',m2[i],' ######'
print '#######################################'
self.plothistssfr(minmass=m1[i],maxmass=m2[i],plotsingle=False)
pl.savefig(homedir+'/research/LocalClusters/SamplePlots/ssfrhistbymass.eps')
pl.savefig(homedir+'/research/LocalClusters/SamplePlots/ssfrhistbymass.png')
def calc_size_starburst(self):
# combine field and cluster galaxies
f1=self.starburst & self.bluesampleflag & ~self.agnflag
f2=~self.starburst & self.bluesampleflag & ~self.agnflag
print 'mean (median) size of starburst galaxies = %5.2f (%5.2f) +/- %5.2f'%(mean(self.s.SIZE_RATIO[f1]),median(self.s.SIZE_RATIO[f1]),std(self.s.SIZE_RATIO[f1])/sqrt((1.*sum(f1))))
print 'mean (median) size of non-starburst galaxies = %5.2f (%5.2f) +/- %5.4f'%(mean(self.s.SIZE_RATIO[f2]),median(self.s.SIZE_RATIO[f2]),std(self.s.SIZE_RATIO[f2])/sqrt(1.*sum(f2)))
# CLUSTER ONLY
print '\n CLUSTER ONLY \n'
f1=self.starburst & self.bluesampleflag & self.membflag
f2=~self.starburst & self.bluesampleflag & self.membflag
print 'mean (median) size of starburst galaxies = %5.2f (%5.2f) +/- %5.2f'%(mean(self.s.SIZE_RATIO[f1]),median(self.s.SIZE_RATIO[f1]),std(self.s.SIZE_RATIO[f1])/sqrt(1.*sum(f1)))
print 'mean (median) size of non-starburst galaxies = %5.2f (%5.2f) +/- %5.4f'%(mean(self.s.SIZE_RATIO[f2]),median(self.s.SIZE_RATIO[f2]),std(self.s.SIZE_RATIO[f2])/sqrt(1.*sum(f2)))
# FIELD ONLY
print '\n FIELD ONLY \n'
f1=self.starburst & self.bluesampleflag & ~self.membflag
f2=~self.starburst & self.bluesampleflag & ~self.membflag
print 'mean (median) size of starburst galaxies = %5.2f (%5.2f) +/- %5.2f'%(mean(self.s.SIZE_RATIO[f1]),median(self.s.SIZE_RATIO[f1]),std(self.s.SIZE_RATIO[f1])/sqrt(1.*sum(f1)))
print 'mean (median) size of non-starburst galaxies = %5.2f (%5.2f) +/- %5.4f'%(mean(self.s.SIZE_RATIO[f2]),median(self.s.SIZE_RATIO[f2]),std(self.s.SIZE_RATIO[f2])/sqrt(1.*sum(f2)))
def print_tables():
s.compare_all(nsa_columns,tablesuffix='nsa')
s.compare_all(galfit24_columns,tablesuffix='galfit24')
s.compare_all(zoo_columns,tablesuffix='zoo')
s.compare_all(gim2d_columns,tablesuffix='gim2d')
s.compare_all(n_columns+ld_columns+ce_columns,tablesuffix='ldce')
s.compare_all(my_columns,tablesuffix='my')
def print_tables_nc():
nc.compare_all(nsa_columns,tablesuffix='nsa_nc')
nc.compare_all(galfit24_columns,tablesuffix='galfit24_nc')
nc.compare_all(zoo_columns,tablesuffix='zoo_nc')
nc.compare_all(gim2d_columns,tablesuffix='gim2d_nc')
nc.compare_all(n_columns+ld_columns+ce_columns,tablesuffix='ldce_nc')
nc.compare_all(my_columns,tablesuffix='my_nc')
def plotRevsmagboth(absmagflag=0):
figure(figsize=(10,5))
subplots_adjust(wspace=0.02,bottom=.15,left=.12,top=.95,right=.95)
subplot(1,2,1)
s.plotRevsmag(plotsingle=0,absmagflag=absmagflag)
ylabel('$ R_e \ (arcsec) $',fontsize=24)
ax=gca()
text(.7,.9,'$r-band $',transform=ax.transAxes,fontsize=20)
subplot(1,2,2)
s.plotRe24vsmag(plotsingle=0,absmagflag=absmagflag)
ax=gca()
text(.7,.9,'$24 \mu m $',transform=ax.transAxes,fontsize=20)
ax.set_yticklabels(([]))
text(-.025,-.09,'$ m_{24}$',transform=ax.transAxes,horizontalalignment='center',fontsize=24)
if absmagflag:
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRevsM24both.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRevsM24both.png')
else:
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRevsmagboth.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRevsmagboth.png')
def plotRevsrmagboth():
figure(figsize=(10,5))
subplots_adjust(wspace=0.02,bottom=.15,left=.12,top=.95,right=.95)
subplot(1,2,1)
s.plotRevsrmag(plotsingle=0)
ylabel('$ R_e \ (arcsec) $',fontsize=24)
ax=gca()
text(.1,.9,'$r-band $',transform=ax.transAxes,fontsize=20)
subplot(1,2,2)
s.plotRe24vsrmag(plotsingle=0)
ax=gca()
text(.1,.9,'$24 \mu m $',transform=ax.transAxes,fontsize=20)
ax.set_yticklabels(([]))
text(-.02,-.12,'$ M_r$',transform=ax.transAxes,horizontalalignment='center',fontsize=24)
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRevsrmagboth.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRevsrmagboth.png')
def plotRisovsmassboth():
figure(figsize=(10,5))
subplots_adjust(wspace=0.02,bottom=.15,left=.12,top=.95,right=.95)
subplot(1,2,1)
s.plotRisovsmass(plotsingle=0,flag24=0)
ylabel('$ R_{iso} \ (arcsec) $',fontsize=24)
ax1=gca()
text(.1,.9,'$r-band $',transform=ax1.transAxes,fontsize=20)
subplot(1,2,2)
s.plotRisovsmass(plotsingle=0,flag24=1)
ax2=gca()
text(.1,.9,'$24 \mu m $',transform=ax2.transAxes,fontsize=20)
ax2.set_yticklabels(([]))
colorbar(ax=[ax1,ax2])
text(-.02,-.12,'$ log_{10}(M_*/M_\odot)$',transform=ax2.transAxes,horizontalalignment='center',fontsize=24)
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRisovsmassboth.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRisovsmassboth.png')
def plotRevsmassboth():
figure(figsize=(10,5))
subplots_adjust(wspace=0.02,bottom=.15,left=.12,top=.95,right=.95)
subplot(1,2,1)
s.plotRevsmass(plotsingle=0,flag24=0)
ylabel('$ R_e \ (arcsec) $',fontsize=24)
ax1=gca()
text(.1,.9,'$r-band $',transform=ax1.transAxes,fontsize=20)
subplot(1,2,2)
s.plotRevsmass(plotsingle=0,flag24=1)
ax2=gca()
text(.1,.9,'$24 \mu m $',transform=ax2.transAxes,fontsize=20)
ax2.set_yticklabels(([]))
text(-.02,-.12,'$ log_{10}(M_*/M_\odot)$',transform=ax2.transAxes,horizontalalignment='center',fontsize=24)
colorbar(ax=[ax1,ax2])
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRevsmassboth.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/plotRevsmassboth.png')
def plotsizevsMclall(sbcutobs=20,masscut=0):
figure(figsize=(10,8))
subplots_adjust(hspace=.02,wspace=.02,bottom=.15,left=.15)
i=0
for cl in clusternamesbylx:
flag = (s.s.CLUSTER == cl) & s.sampleflag & (s.sb_obs < sbcutobs) & s.membflag & ~s.agnflag
if cl == 'MKW8':
print 'number in MKW8 = ',sum(flag)
print s.s.SIZE_RATIO[flag]
if masscut:
flag=flag & (log10(s.logstellarmass) < 10.41)
x=clusterLx[cl]
y=median(s.s.SIZE_RATIO[flag])
BT=mean(s.s.B_T_r[flag & s.gim2dflag])
erry=std(s.s.SIZE_RATIO[flag])/sum(flag)
plot(x,y,'k.',color=colors[i],marker=shapes[i],markersize=20,label=cl)
errorbar(x,y,yerr=erry,fmt=None,ecolor=colors[i])
#plot(x,BT,'b^',markersize=15)
i+=1
legend(loc='upper right',numpoints=1,markerscale=.75)
flag = s.sampleflag & (s.sb_obs < sbcutobs) & ~s.membflag & s.dvflag
fieldvalue=mean(s.s.SIZE_RATIO[flag])
errfieldvalue=std(s.s.SIZE_RATIO[flag])/(sum(flag))
#axhline(y=fieldvalue,color='k',ls='-')
#axhline(y=fieldvalue+errfieldvalue,color='k',ls='--')
#axhline(y=fieldvalue-errfieldvalue,color='k',ls='--')
ax=gca()
ax.set_xscale('log')
ax.tick_params(axis='both', which='major', labelsize=16)
xl=arange(-1.2,2,.1)
yl=-.3*(xl)+.64
plot(10.**xl,yl,'k--')
xlabel('$ L_X \ (10^{43} \ erg \ s^{-1} )$',fontsize = 28)
ylabel('$R_e(24)/R_e(r)$',fontsize = 28)
axis([.05,10,0.,1.09])
savefig(homedir+'/research/LocalClusters/SamplePlots/sizevsLxall.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/sizsevsLxall.png')
def plotsizevsMclallwhisker(sbcutobs=20,masscut=False,drcut=1.,blueflag=False):
figure(figsize=(10,8))
subplots_adjust(hspace=.02,wspace=.02,bottom=.15,left=.15)
i=0
x1=[]
y1=[]
y2all=[]
y3all=[]
for cl in clusternamesbylx:
flag = (s.s.CLUSTER == cl) & s.sampleflag & s.membflag & ~s.agnflag #& ~s.blueflag
if blueflag:
flag = flag & self.blueflag2
print 'number in ',cl,' = ',sum(flag)
if masscut:
flag=flag & (s.logstellarmass < 10.41)
x=log10(clusterLx[cl])+43
y=(s.s.SIZE_RATIO[flag])
y2=(s.size_ratio_corr[flag])
BT=mean(s.s.B_T_r[flag & s.gim2dflag])
erry=std(s.s.SIZE_RATIO[flag])/sum(flag)
boxplot([y],positions=[x])
plot(x,median(y),'k.',color=colors[i],marker=shapes[i],markersize=20,label=cl)
#plot(x,median(y2),'k.',label='_nolegend_')
x1.append(x)
y1.append(median(y))
y2all.append(median(y2))
y3all.append(mean(y2))
#errorbar(x,y,yerr=erry,fmt=None,ecolor=colors[i])
#plot(x,BT,'b^',markersize=15)
i+=1
legend(loc='upper right',numpoints=1,markerscale=.75)
flag = s.sampleflag & ~s.membflag & ~s.agnflag #& s.dvflag
fieldvalue=mean(s.s.SIZE_RATIO[flag])
errfieldvalue=std(s.s.SIZE_RATIO[flag])/sqrt(1.*sum(flag))
axhline(y=fieldvalue,color='k',ls='-')
axhline(y=fieldvalue+errfieldvalue,color='k',ls='--')
axhline(y=fieldvalue-errfieldvalue,color='k',ls='--')
#print 'size corrected by B/A'
#spearman(x1,y2all)
#print y1
#print y2all
#print 'size corrected by B/A, mean'
#spearman(x1,y3all)
ax=gca()
#ax.set_xscale('log')
xl=arange(41,45,.1)
yl=-.3*(xl-43.)+.64
#plot(xl,yl,'k--')
xlabel('$ log_{10}(L_X \ erg \ s^{-1} )$',fontsize = 28)
ylabel('$R_e(24)/R_e(r)$',fontsize = 28)
xticks(arange(41,46.,1))
axis([41.5,44.5,0.,1.2])
ax.tick_params(axis='both', which='major', labelsize=16)
savefig(homedir+'/research/LocalClusters/SamplePlots/sizevsLxall_whisker.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/sizsevsLxall_whisker.png')
print x1
print y1
spearman(np.array(x1),np.array(y1))
def plotsizevsMclall(sbcutobs=20,masscut=0):
figure(figsize=(10,8))
subplots_adjust(hspace=.02,wspace=.02,bottom=.15,left=.15)
i=0
for cl in clusternamesbylx:
flag = (s.s.CLUSTER == cl) & s.sampleflag & (s.sb_obs < sbcutobs) & s.membflag & ~s.agnflag
if cl == 'MKW8':
print 'number in MKW8 = ',sum(flag)
print s.s.SIZE_RATIO[flag]
if masscut:
flag=flag & (log10(s.logstellarmass) < 10.41)
x=clusterLx[cl]
y=median(s.s.SIZE_RATIO[flag])
BT=mean(s.s.B_T_r[flag & s.gim2dflag])
erry=std(s.s.SIZE_RATIO[flag])/sum(flag)
plot(x,y,'k.',color=colors[i],marker=shapes[i],markersize=20,label=cl)
errorbar(x,y,yerr=erry,fmt=None,ecolor=colors[i])
#plot(x,BT,'b^',markersize=15)
i+=1
legend(loc='upper right',numpoints=1,markerscale=.75)
flag = s.sampleflag & (s.sb_obs < sbcutobs) & ~s.membflag & s.dvflag
fieldvalue=mean(s.s.SIZE_RATIO[flag])
errfieldvalue=std(s.s.SIZE_RATIO[flag])/(sum(flag))
#axhline(y=fieldvalue,color='k',ls='-')
#axhline(y=fieldvalue+errfieldvalue,color='k',ls='--')
#axhline(y=fieldvalue-errfieldvalue,color='k',ls='--')
ax=gca()
ax.set_xscale('log')
ax.tick_params(axis='both', which='major', labelsize=16)
xl=arange(-1.2,2,.1)
yl=-.3*(xl)+.64
plot(10.**xl,yl,'k--')
xlabel('$ L_X \ (10^{43} \ erg \ s^{-1} )$',fontsize = 28)
ylabel('$R_e(24)/R_e(r)$',fontsize = 28)
axis([.05,10,0.,1.09])
savefig(homedir+'/research/LocalClusters/SamplePlots/sizevsLxall.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/sizsevsLxall.png')
def plotsizevsBTall(sbcutobs=20,masscut=0):
figure(figsize=(10,8))
subplots_adjust(hspace=.02,wspace=.02,bottom=.15,left=.15)
i=0
for cl in clusternamesbylx:
flag = (s.s.CLUSTER == cl) & s.sampleflag & (s.sb_obs < sbcutobs) & s.membflag & ~s.agnflag
if cl == 'MKW8':
print 'number in MKW8 = ',sum(flag)
print s.s.SIZE_RATIO[flag]
if masscut:
flag=flag & (log10(s.logstellarmass) < 10.41)
x=clusterLx[cl]
y=median(s.s.SIZE_RATIO[flag])
BT=mean(s.s.B_T_r[flag & s.gim2dflag])
erry=std(s.s.SIZE_RATIO[flag])/sum(flag)
plot(x,y,'k.',color=colors[i],marker=shapes[i],markersize=20,label=cl)
errorbar(x,y,yerr=erry,fmt=None,ecolor=colors[i])
#plot(x,BT,'b^',markersize=15)
i+=1
legend(loc='upper right',numpoints=1,markerscale=.75)
flag = s.sampleflag & (s.sb_obs < sbcutobs) & ~s.membflag & s.dvflag
fieldvalue=mean(s.s.SIZE_RATIO[flag])
errfieldvalue=std(s.s.SIZE_RATIO[flag])/(sum(flag))
#axhline(y=fieldvalue,color='k',ls='-')
#axhline(y=fieldvalue+errfieldvalue,color='k',ls='--')
#axhline(y=fieldvalue-errfieldvalue,color='k',ls='--')
ax=gca()
ax.set_xscale('log')
ax.tick_params(axis='both', which='major', labelsize=16)
xl=arange(-1.2,2,.1)
yl=-.3*(xl)+.64
plot(10.**xl,yl,'k--')
xlabel('$ L_X \ (10^{43} \ erg \ s^{-1} )$',fontsize = 28)
ylabel('$R_e(24)/R_e(r)$',fontsize = 28)
axis([.05,10,0.,1.09])
savefig(homedir+'/research/LocalClusters/SamplePlots/sizevsLxall.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/sizsevsLxall.png')
def plotsffracvsMclall(sbcutobs=20,masscut=0):
figure(figsize=(10,8))
subplots_adjust(hspace=.02,wspace=.02,bottom=.15,left=.15)
i=0
for cl in clusternamesbylx:
flag = (s.s.CLUSTER == cl) & s.sampleflag & s.membflag
denom = (s.s.CLUSTER == cl) & s.sfsampleflag & s.membflag
if cl == 'MKW8':
print 'number in MKW8 = ',sum(flag)
print s.s.SIZE_RATIO[flag]
x=clusterLx[cl]
y,errdown,errup=my.ratioerror(1.*sum(flag),1.*sum(denom))
#erry=std(s.s.SIZE_RATIO[flag])/sum(flag)
plot(x,y,'k.',color=colors[i],marker=shapes[i],markersize=20,label=cl)
#errorbar(x,y,yerr=[errdown,errup],fmt=None,ecolor=colors[i])
i+=1
legend(loc='upper right',numpoints=1,markerscale=.75)
fflag=s.sampleflag & (s.sb_obs < sbcutobs) & s.membflag
fdemon = s.spiralflag & (s.logstellarmass > minmass) & (s.s.SERSIC_TH50*s.DA > minsize_kpc) & ~s.membflag & s.dvflag
fieldvalue=mean(s.s.SIZE_RATIO[flag])
errfieldvalue=std(s.s.SIZE_RATIO[flag])/(sum(flag))
#axhline(y=fieldvalue,color='k',ls='-')
#axhline(y=fieldvalue+errfieldvalue,color='k',ls='--')
#axhline(y=fieldvalue-errfieldvalue,color='k',ls='--')
ax=gca()
ax.set_xscale('log')
ax.tick_params(axis='both', which='major', labelsize=16)
xlabel('$ L_X \ (10^{43} \ erg \ s^{-1} )$',fontsize = 28)
ylabel('$SF \ Frac$',fontsize = 28)
axis([.05,10,0.,1.05])
savefig(homedir+'/research/LocalClusters/SamplePlots/sffracvsLxall.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/sffracvsLxall.png')
def plotRe24vsReall(sbcutobs=20,plotcolorbar=1,fixPA=False,logyflag=True):
figure(figsize=(10,8))
subplots_adjust(hspace=.02,wspace=.02,left=.1,bottom=.15)
i=1
allax=[]
# for cl in clusternamesbydistance:
for cl in clusternamesbylx:
subplot(3,3,i)
flag = (s.s.CLUSTER == cl) & s.sampleflag & (s.sb_obs < sbcutobs) & ~s.agnflag
s.plotRe24vsRe(plotsingle=0,usemyflag=1,myflag=flag,sbcutobs=sbcutobs,logy=logyflag,fixPA=fixPA)
ax=gca()
cname='$'+cl+'$'
text(.1,.8,cname,fontsize=18,transform=ax.transAxes,horizontalalignment='left')
#ax.set_xscale('log')
#ax.set_yscale('log')
#axis([1,30,.8,20])
allax.append(ax)
multiplotaxes(i)
i+=1
if plotcolorbar:
colorbar(ax=allax,fraction=0.08)
text(-.5,-.25,'$R_e \ NSA \ (arcsec)$',fontsize=22,horizontalalignment='center',transform=ax.transAxes)
text(-2.4,1.5,'$R_e \ 24\mu m \ (arcsec) $',fontsize=22,verticalalignment='center',rotation=90,transform=ax.transAxes,family='serif')
savefig(homedir+'/research/LocalClusters/SamplePlots/Re24vsReall.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/Re24vsReall.png')
def plotdvdrall(sbcutobs=20,plotcolorbar=1,fixPA=False,logyflag=True,scalepoint=0,hexbinmax=20):
pl.figure(figsize=(9,6))
pl.subplots_adjust(hspace=.02,wspace=.02,left=.12,bottom=.12,right=.85)
i=1
allax=[]
for cl in clusternamesbylx:
pl.subplot(3,3,i)
#flag = (s.s.CLUSTER == cl) & s.sampleflag #& (s.sb_obs < sbcutobs) & ~s.agnflag
s.plotsizedvdr(plotsingle=0,cluster=cl,plothexbin=True,hexbinmax=hexbinmax,scalepoint=scalepoint,plotHI=True)
ax=pl.gca()
allax.append(ax)
cname='$'+cl+'$'
text(.1,.8,cname,fontsize=18,transform=ax.transAxes,horizontalalignment='left')
pl.axis([-.1,1.6,-.1,3.2])
pl.xticks(arange(0,1.6,.5))
pl.yticks(arange(0,3.5,1))
#pl.gca().set_xscale('log')
multiplotaxes(i)
i+=1
if plotcolorbar:
c=colorbar(ax=allax,fraction=0.1)
c.ax.text(2.2,.5,'$R_e(24)/R_e(r)$',rotation=-90,verticalalignment='center',fontsize=20)
pl.text(-.5,-.4,'$\Delta r/R_{200}$',fontsize=26,horizontalalignment='center',transform=ax.transAxes)
pl.text(-2.4,1.5,'$\Delta v/\sigma_v$',fontsize=26,verticalalignment='center',rotation=90,transform=ax.transAxes,family='serif')
pl.savefig(homedir+'/research/LocalClusters/SamplePlots/sizedvdrall.eps')
pl.savefig(homedir+'/research/LocalClusters/SamplePlots/sizedvdrall.png')
def plotsigmavsdrall():
pl.figure(figsize=(6.4,8))
pl.subplots_adjust(left=.2,hspace=.02,wspace=.02)
i=1
xl='$\Sigma_5 $'
yl='$\Delta r/R_{200}$'
allax=[]
for cl in clusternamesbylx:
pl.subplot(9,1,i)
flag = (s.s.CLUSTER == cl) & s.dvflag & s.sfsampleflag
s.plotdrsigma(flag,plotsingle=0)
ax=pl.gca()
cname='$'+cl+'$'
pl.text(.05,.3,cname,fontsize=18,transform=ax.transAxes,horizontalalignment='left')
#ax.set_xscale('log')
#ax.set_yscale('log')
#axis([1,30,.8,20])
allax.append(ax)
if i < 9:
pl.gca().set_xticklabels([])
#multiplotaxes(i)
i+=1
pl.text(.5,-.5,xl,fontsize=24,horizontalalignment='center',transform=ax.transAxes)
pl.text(-.2,4.5,yl,fontsize=24,verticalalignment='center',rotation=90,transform=ax.transAxes,family='serif')
pl.savefig(homedir+'/research/LocalClusters/SamplePlots/drvssigmaall.eps')
pl.savefig(homedir+'/research/LocalClusters/SamplePlots/drvssigmaall.png')
def plotRiso24vsRisoall(sbcutobs=20):
figure(figsize=(10,8))
subplots_adjust(hspace=.02,wspace=.02)
i=1
for cl in clusternamesbylx:
subplot(3,3,i)
print cl
flag = (s.s.CLUSTER == cl) & s.isosampleflag #& (s.sb_obs < sbcutobs)
s.plotRiso24vsRiso(plotsingle=0,usemyflag=1,myflag=flag,sbcutobs=sbcutobs)
ax=gca()
cname='$'+cl+'$'
text(.1,.8,cname,fontsize=18,transform=ax.transAxes,horizontalalignment='left')
ax.set_xscale('log')
ax.set_yscale('log')
axis([8,150,2,120])
multiplotaxes(i)
i+=1
text(-.5,-.25,'$R_{iso} \ NSA \ (arcsec)$',fontsize=22,horizontalalignment='center',transform=ax.transAxes)
text(-2.4,1.5,'$R_{iso} \ 24\mu m \ (arcsec) $',fontsize=22,verticalalignment='center',rotation=90,transform=ax.transAxes,family='serif')
savefig(homedir+'/research/LocalClusters/SamplePlots/Riso24vsRisoall.eps')
savefig(homedir+'/research/LocalClusters/SamplePlots/Riso24vsRisoall.png')
def showhighsb():
ind=s.s.NSAID[(s.sb_obs < 16) & s.sampleflag]
for i in ind:
os.system('open '+homedir+'research/LocalClusters/EllipseProfiles/*'+str(i)+'*profiles.png')
try:
os.system('open '+homedir+'research/LocalClusters/EllipseProfiles/*'+str(i)+'*profiles-Ha.png')
except:
print 'no Halpha for ',i
def showspirals(cut=.8):
index=arange(len(s.s.RA))
ind=index[s.spiralflag]
for i in ind:
st='cp '+homedir+'research/LocalClusters/EllipseProfiles/'+str(s.s.CLUSTER[i])+'-'+str(s.s.NSAID[i])+'-ellipse-profiles.png '+homedir+'research/LocalClusters/EllipseProfiles/PureSpirals/.'
print st
os.system(st)
#try:
#os.system('cp '+homedir+'research/LocalClusters/EllipseProfiles/*'+str(i)+'*profiles-Ha.png '+homedir+'research/LocalClusters/EllipseProfiles/PureSpirals/*'+str(i)+'*profiles-Ha.png ')
#except:
#print 'no Halpha for ',i
def makepaperplots():
#s.plotsizedr()
plotRe24vsReall()
s.plotRe24vsRe()
s.plotsizedrbymass()
#s.plotsizemass()
s.plotsizesigmabymass()
s.plotsizeBT()
s.plotsizeHIdef()
s.plotsizetdepletion()
plotsizevsMclallwhisker()
#plotRevsmagboth()
#plotRevsrmagboth()
#plotRevsmassboth()
def talkplots():
s.compare_dr()
s.plotsizedrbymass(masscut=10.**10.41,isoflag=1)
s.plotsizedrbymass(masscut=10.**10.41,isoflag=0)
plotRevsmassboth()
s.compare_BT()
s.compare_BT(isoflag=1)
def show_enhanced():
for id in s.s.NSAID[s.enhanced]: os.system('open '+homedir+'research/LocalClusters/EllipseProfiles/*'+str(id)+'*.png')
def show_enhanced():
for id in s.s.NSAID[s.enhanced]: os.system('open '+homedir+'research/LocalClusters/EllipseProfiles/*'+str(id)+'*.png')
def show_depleted():
for id in s.s.NSAID[s.depleted]: os.system('open '+homedir+'research/LocalClusters/EllipseProfiles/*'+str(id)+'*.png')
def show_normaltrunc():
for id in s.s.NSAID[s.normaltrunc]: os.system('open '+homedir+'research/LocalClusters/EllipseProfiles/*'+str(id)+'*.png')
def show_R90trunc():
for id in s.s.NSAID[s.r90size[s.mipsflag] < 0.5]: os.system('open '+homedir+'research/LocalClusters/EllipseProfiles/*'+str(id)+'*.png')
def show_normalconc():
for id in s.s.NSAID[s.normalconc]: os.system('open '+homedir+'research/LocalClusters/EllipseProfiles/*'+str(id)+'*.png')
def comparepops(plotflag=1,printflag=1):
dmasscut=(s.logstellarmass > 10.) & (s.logstellarmass < 11.3)
xflags=[s.normalgalfit,s.normal,s.normalgalfit,s.normal,(s.normal & dmasscut),s.normalgalfit,s.normal]
yflags=[s.normalconc,s.normaltrunc,s.enhanced,s.lowsfr,(s.depleted & dmasscut),s.truncflag,s.isotruncflag]
yname=['normal-concentrated','normal-truncated','enhanced','low ssfr','depleted','concentrated','truncated']
compvar=[s.s.DR_R200,s.logstellarmass,s.s.B_T_r,s.s.HAEW]
varname=['DR_R200','M*','B/T','Halpha']
nsubplots=4
varlabel=['$ \Delta R/R_{200} $', '$ M_* \ (M_\odot/yr) $', '$B/T $',r'$H \alpha \ EW$']
iplots=[0,1,2,3,4,5,6]
#for i in range(len(xflags)):
for i in iplots:
if plotflag:
pl.figure(figsize=(10,8))
subplots_adjust(bottom=.1,left=.1,wspace=.3,hspace=.35)
for j in range(nsubplots):
if j == 2:
x=compvar[j][xflags[i] & s.gim2dflag & ~yflags[i]]
y=compvar[j][yflags[i] & s.gim2dflag]
elif j == 3:
x=compvar[j][xflags[i] & (s.s.HAEW > 0.)& ~yflags[i]]
y=compvar[j][yflags[i] & (s.s.HAEW > 0.)]
else:
x=compvar[j][xflags[i] & ~yflags[i]]
y=compvar[j][yflags[i]]
xmin=min(min(x),min(y))
xmax=max(max(x),max(y))
if printflag:
print ''
print ''
print '#############################################'
print 'len(x),len(y) = ',len(x),len(y)
print 'comparing '+varname[j]+' of '+yname[i]+' vs normal'
(D,p)=ks(x,y)
t=anderson.anderson_ksamp([x,y])
print_anderson(t)
if plotflag:
pl.subplot(2,2,j+1)
#print 'x = ',len(x),x
#print 'y = ',len(y),y
pl.hist(x,bins=len(x),cumulative=True,histtype='step',normed=True,label='Normal',color='b',range=(xmin,xmax))
pl.hist(y,bins=len(y),cumulative=True,histtype='step',normed=True,label=yname[i],color='r',range=(xmin,xmax))
if j < 1:
pl.title(yname[i]+' vs normal')
legend(loc='lower right')
if j in [0,2]:
pl.ylabel('$Cumulative \ Distribution $',fontsize=20)
pl.xlabel(varlabel[j],fontsize=20)
ylim(-.05,1.05)
ax=gca()
text(.05,.9,'$D = %4.2f$'%(D),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
text(.05,.8,'$p = %5.4f$'%(p),horizontalalignment='left',transform=ax.transAxes,fontsize=14)
figname=homedir+'research/LocalClusters/SamplePlots/'+yname[i]+'_ks.png'
pl.savefig(figname)
figname=homedir+'research/LocalClusters/SamplePlots/'+yname[i]+'_ks.eps'
pl.savefig(figname)
def print_anderson(t):
print '%%%%%%%%% ANDERSON %%%%%%%%%%%'
print 'anderson statistic = ',t[0]
print 'critical values = ',t[1]
print 'p-value = ',t[2]
def plotsigmaLx():
figure(figsize=[7,6])
clf()
subplots_adjust(left=.16,bottom=.16,right=.95,top=.95,wspace=.3)
i=0
errp=[]
errm=[]
x=[]
y=[]
for cl in clusternames:
plot(clusterLx[cl],clusterbiweightscale[cl],'ko',color=colors[i],marker=shapes[i],markersize=16,label=cl)
errm.append(clusterbiweightscale_errm[cl])
errp.append(clusterbiweightscale_errp[cl])
x.append(clusterLx[cl])
y.append(clusterbiweightscale[cl])
i += 1
errm=array(errm)
errp=array(errp)
yerror=array(zip(errm, errp),'f')
#print 'yerror = ',yerror
errorbar(x,y,yerr=yerror.T,fmt=None,ecolor='k')
gca().set_xscale('log')
xlabel('$L_X \ (10^{43} erg/s)$',fontsize=26)
ylabel('$\sigma \ (km/s) $',fontsize=26)
axis([.06,10,300,1000])
leg=legend(numpoints=1,loc='upper left',scatterpoints=1,markerscale=.9,borderpad=.2,labelspacing=.2,handletextpad=.2,prop={'size':14})
gca().tick_params(axis='both', which='major', labelsize=16)
savefig(homedir+'research/LocalClusters/SamplePlots/sigmalxall.eps')
def computePCA():
flag=s.sampleflag & s.dvflag & ~s.agnflag
fields=[s.logstellarmass,s.s.SIZE_RATIO,s.massdensity,s.ssfr,s.s.DR_R200,s.s.SIGMA_5]
fields=[s.logstellarmass,s.s.ABSMAG[:,4],s.s.ABSMAG[:,2],s.s.SFR_ZDIST]
dat=[]
for f in fields:
dat.append(f[flag].tolist())
dataMatrix=np.array(dat)
mpca=mlabPCA(dataMatrix.T)
print('PC axes in terms of the measurement axes'\
' scaled by the standard deviations: \n')
print mpca.Wt
figure()
plot(mpca.Y[:,0],mpca.Y[:,1],'o',label='class1')
xlabel('Principal Axis')
ylabel('Second Axis')
return dataMatrix,mpca
def paperTable5(sbcutobs=20,masscut=0):
#clustersigma={'MKW11':361, 'MKW8':325., 'AWM4':500., 'A2063':660., 'A2052':562., 'NGC6107':500., 'Coma':1000., 'A1367':745., 'Hercules':689.}
#clusterz={'MKW11':.022849,'MKW8':.027,'AWM4':.031755,'A2063':.034937,'A2052':.035491,'NGC6107':.030658,'Coma':.023,'A1367':.028,'Hercules':.037,'MKW10':.02054}
#clusterbiweightcenter={'MKW11':6897,'MKW8':8045,'AWM4':9636,'A2063':10426,'A2052':10354,'NGC6107':9397,'Coma':7015,'A1367':6507,'Hercules':10941}
#clusterbiweightcenter_errp={'MKW11':45,'MKW8':36,'AWM4':51,'A2063':63,'A2052':64,'NGC6107':48,'Coma':41,'A1367':48,'Hercules':48}
#clusterbiweightcenter_errm={'MK
outfile=open(homedir+'/Dropbox/Research/MyPapers/LCSpaper1/Table3.tex','w')
outfile.write('\\begin{deluxetable*}{lcccccccc} \n')
outfile.write('\\tablecaption{Rank Correlation Test Between \size \ and Cluster/Galaxy Properties \label{statTests}} \n')
#outfile.write('\\tablehead{\colhead{Cluster} &\colhead{Biweight Central Velocity} & \colhead{Lit.} & \colhead{Biweight Scale} & \colhead{Lit} & \colhead{N$_{spiral}$} & \colhead{N$_{spiral}$} } \n')# % \\\\ & \colhead{(km/s)} & \colhead{(km/s)} & \colhead{(km/s)} & \colhead{(km/s)} & \colhead{Member} & \colhead{Field}} \n')
outfile.write('\\tablehead{& \multicolumn{4}{c}{With Coma} & \multicolumn{4}{c}{Without Coma} \\\\ & \multicolumn{2}{c}{All} & \multicolumn{2}{c}{$log_{10}(M_*) < 10.41$} & \multicolumn{2}{c}{All} & \multicolumn{2}{c}{$log_{10}(M_*) < 10.41$} \\\\ & {$\\rho$} & {P} & {$\\rho$} &{P}& {$\\rho$} & {P} & {$\\rho$} & {P}}\n')
outfile.write('\startdata \n')
labels=['$\Delta r/R_{200}$','$\Sigma_5$','$log_{10}(M_*)$','$B/T$','$HI \\ Def$']
params=[s.s.DR_R200,s.s.SIGMA_5,s.logstellarmassTaylor,s.s.B_T_r,s.s.HIDef]
flags=[s.sampleflag,s.sampleflag,s.sampleflag,(s.sampleflag & s.gim2dflag),(s.sampleflag & s.HIflag)]
for i in range(len(labels)):
flagLM=flags[i] & (s.logstellarmass < 10.41)
flag2=flags[i] & (s.s.CLUSTER != 'Coma')
flag2LM=flags[i] & (s.s.CLUSTER != 'Coma') & (s.logstellarmass < 10.41)
a,b = spearman(s.s.SIZE_RATIO[flags[i]],params[i][flags[i]])
aLM,bLM = spearman(s.s.SIZE_RATIO[flagLM],params[i][flagLM])
c,d=spearman(s.s.SIZE_RATIO[flag2],params[i][flag2])
cLM,dLM=spearman(s.s.SIZE_RATIO[flag2LM],params[i][flag2LM])
tableline='%s & %5.2f & %5.3f & %5.2f & %5.3f & %5.2f & %5.3f & %5.2f & %5.3f \\\\ \n' %(labels[i],a,b,aLM,bLM,c,d,cLM,dLM)
outfile.write(tableline)
outfile.write('\enddata \n')
outfile.write('\end{deluxetable*} \n')
outfile.close()
def paperTable1(sbcutobs=20,masscut=0):
#clustersigma={'MKW11':361, 'MKW8':325., 'AWM4':500., 'A2063':660., 'A2052':562., 'NGC6107':500., 'Coma':1000., 'A1367':745., 'Hercules':689.}
#clusterz={'MKW11':.022849,'MKW8':.027,'AWM4':.031755,'A2063':.034937,'A2052':.035491,'NGC6107':.030658,'Coma':.023,'A1367':.028,'Hercules':.037,'MKW10':.02054}
#clusterbiweightcenter={'MKW11':6897,'MKW8':8045,'AWM4':9636,'A2063':10426,'A2052':10354,'NGC6107':9397,'Coma':7015,'A1367':6507,'Hercules':10941}
#clusterbiweightcenter_errp={'MKW11':45,'MKW8':36,'AWM4':51,'A2063':63,'A2052':64,'NGC6107':48,'Coma':41,'A1367':48,'Hercules':48}
#clusterbiweightcenter_errm={'MK
outfile=open(homedir+'/Dropbox/Research/MyPapers/LCSsfrmass/Table1.tex','w')
outfile.write('\\begin{deluxetable*}{cccccc} \n')
outfile.write('\\tablecaption{Cluster Properties and Blue Galaxy Sample Sizes \label{finalsample}} \n')
#outfile.write('\\tablehead{\colhead{Cluster} &\colhead{Biweight Central Velocity} & \colhead{Lit.} & \colhead{Biweight Scale} & \colhead{Lit} & \colhead{N$_{spiral}$} & \colhead{N$_{spiral}$} } \n')# % \\\\ & \colhead{(km/s)} & \colhead{(km/s)} & \colhead{(km/s)} & \colhead{(km/s)} & \colhead{Member} & \colhead{Field}} \n')
outfile.write('\\tablehead{\colhead{Cluster} &\colhead{Biweight Central Velocity} & \colhead{Biweight Scale} & \colhead{N$_{gal}$} & \colhead{N$_{gal}$}& \colhead{N$_{gal}$} \\\\ & \colhead{(km/s)} & \colhead{(km/s)} & Member & Near-Field & Field } \n')
outfile.write('\startdata \n')
for cl in clusternamesbydistance:
nmemb_spiral = sum((s.s.CLUSTER == cl) & s.bluesampleflag & s.membflag)
nnearfield_spiral = sum((s.s.CLUSTER == cl) & s.bluesampleflag & ~s.membflag & s.dvflag)
nfield_spiral = sum((s.s.CLUSTER == cl) & s.bluesampleflag & ~s.membflag & ~s.dvflag)
#tableline='%s & %i$^{%+i}_{-%i}$ & %i & %i$^{+%i}_{-%i}$ & %i & %i & %i & %i \\\\ \n' %(cl, clusterbiweightcenter[cl],clusterbiweightcenter_errp[cl],clusterbiweightcenter_errm[cl],int(round(clusterz[cl]*3.e5)), clusterbiweightscale[cl],clusterbiweightscale_errp[cl],clusterbiweightscale_errm[cl],int(round(clustersigma[cl])),nmemb_spiral,nfield_spiral)
tableline='%s & %i$^{%+i}_{-%i}$ & %i$^{+%i}_{-%i}$ & %i & %i & %i \\\\ \n' %(cl, clusterbiweightcenter[cl],clusterbiweightcenter_errp[cl],clusterbiweightcenter_errm[cl], clusterbiweightscale[cl],clusterbiweightscale_errp[cl],clusterbiweightscale_errm[cl],nmemb_spiral,nnearfield_spiral,nfield_spiral)
outfile.write(tableline)
outfile.write('\enddata \n')
outfile.write('\end{deluxetable*} \n')
outfile.close()
def plotabellclustersposition():
figure()#figsize=(6,6))
eaflag=((e.s.CLUSTER == 'A2063') | (e.s.CLUSTER == 'A2052')) & (abs(e.s.DELTA_V) < 3)
hexbin(e.s.RA[eaflag],e.s.DEC[eaflag],cmap=cm.Greys,gridsize=40,vmin=0,vmax=10)
aflag=((s.s.CLUSTER == 'A2063') | (s.s.CLUSTER == 'A2052')) & (abs(s.s.DELTA_V) < 3)
aflag24=aflag & s.sampleflag
aflag=aflag & s.spiralflag
pflag=aflag24 & s.pointsource
print 'NSAIDs of point sources ', s.s.NSAID[pflag]
npflag=aflag24 & ~s.pointsource
plot(s.s.RA[aflag & ~aflag24],s.s.DEC[aflag & ~aflag24],'k.')
scatter(s.s.RA[aflag24],s.s.DEC[aflag24],s=s.s.SIZE_RATIO[aflag24]*60,c='red')
plot(s.s.RA[pflag],s.s.DEC[pflag],'k*',markersize=14)
axis('equal')
axis([228,232,5,11])
plot(clusterRA['A2052'],clusterDec['A2052'],'bx',markersize=16, lw=3)
plot(clusterRA['A2063'],clusterDec['A2063'],'bx',markersize=16, lw=3)
xlabel('$RA \ (deg)$',fontsize=20)
ylabel('$Dec \ (deg) $',fontsize=20)
cl='A2063'
r200=2.02*(clusterbiweightscale[cl])/1000./sqrt(OmegaL+OmegaM*(1.+clusterz[cl])**3)*H0/70. # in Mpc
r200deg=r200*1000./my.DA(clusterbiweightcenter[cl]/3.e5,h)/3600.
cir=Circle((clusterRA[cl],clusterDec[cl]),radius=1.3*r200deg,color='None',ec='k')
gca().add_patch(cir)
cl='A2052'
r200=2.02*(clusterbiweightscale[cl])/1000./sqrt(OmegaL+OmegaM*(1.+(clusterbiweightcenter[cl]/3.e5))**3)*H0/70. # in Mpc
r200deg=r200*1000./my.DA(clusterbiweightcenter[cl]/3.e5,h)/3600.
cir=Circle((clusterRA[cl],clusterDec[cl]),radius=1.3*r200deg,color='None',ec='k')
gca().add_patch(cir)
def plotpositionson24(plotsingle=0,plotcolorbar=1,plotnofit=0,useirsb=0,blueflag=True):
pl.figure(figsize=(10,8))
pl.subplots_adjust(hspace=.02,wspace=.02,left=.12,bottom=.12,right=.85)
i=1
allax=[]
for cl in clusternamesbylx:
pl.subplot(3,3,i)
infile=homedir+'research/LocalClusters/NSAmastertables/'+cl+'_NSAmastertable.fits'
d=fits.getdata(infile)
#print cl, i
ra=s.s.RA-clusterRA[cl]
dec=s.s.DEC-clusterDec[cl]
r200=2.02*(clusterbiweightscale[cl])/1000./sqrt(OmegaL+OmegaM*(1.+clusterz[cl])**3)*H0/70. # in Mpc
r200deg=r200*1000./my.DA(clusterbiweightcenter[cl]/3.e5,h)/3600.
cir=Circle((0,0),radius=r200deg,color='None',ec='k')
gca().add_patch(cir)
flag=(s.s.CLUSTER == cl) & s.dvflag
hexbin(d.RA-clusterRA[cl],d.DEC-clusterDec[cl],cmap=cm.Greys,gridsize=40,vmin=0,vmax=10)
if plotnofit:
flag=s.sfsampleflag & ~s.sampleflag & s.dvflag & (s.s.CLUSTER == cl)
plot(ra[flag],dec[flag],'rv',mec='r',mfc='None')
if blueflag:
flag=s.bluesampleflag & s.dvflag & (s.s.CLUSTER == cl)
else:
flag=s.sampleflag & s.dvflag & (s.s.CLUSTER == cl)
#print cl, len(ra[flag]),len(dec[flag]),len(s.s.SIZE_RATIO[flag])
if useirsb:
color=log10(s.sigma_ir)
v1=7.6
v2=10.5
colormap=cm.jet
else:
color=s.s.SIZE_RATIO
v1=.1
v2=1
colormap=cm.jet_r
try:
scatter(ra[flag],dec[flag],s=30,c=color[flag],cmap=colormap,vmin=v1,vmax=v2)
except ValueError:
scatter(ra[flag],dec[flag],s=30,c='k',cmap=cm.jet_r,vmin=.1,vmax=1)
ax=pl.gca()
fsize=14
t=cluster24Box[cl]
drawbox([t[0]-clusterRA[cl],t[1]-clusterDec[cl],t[2],t[3],t[4]],'g-')
ax=gca()
ax.invert_xaxis()
if plotsingle:
xlabel('$ \Delta RA \ (deg) $',fontsize=22)
ylabel('$ \Delta DEC \ (deg) $',fontsize=22)
legend(numpoints=1,scatterpoints=1)
cname='$'+cl+'$'
text(.1,.8,cname,fontsize=18,transform=ax.transAxes,horizontalalignment='left')
pl.axis([1.8,-1.8,-1.8,1.8])
pl.xticks(arange(-1,2,1))
pl.yticks(arange(-1,2,1))
allax.append(ax)
multiplotaxes(i)
i+=1
if plotcolorbar:
c=colorbar(ax=allax,fraction=0.05)
c.ax.text(2.2,.5,'$R_e(24)/R_e(r)$',rotation=-90,verticalalignment='center',fontsize=20)
pl.text(-.5,-.28,'$\Delta RA \ (deg) $',fontsize=26,horizontalalignment='center',transform=ax.transAxes)
pl.text(-2.4,1.5,'$\Delta Dec \ $',fontsize=26,verticalalignment='center',rotation=90,transform=ax.transAxes,family='serif')
pl.savefig(homedir+'/research/LocalClusters/SamplePlots/positionson24.eps')
pl.savefig(homedir+'/research/LocalClusters/SamplePlots/positionson24.png')
def plotabellclusters():
# plot density of ellipticals
# plot color mag
# plot color-mass
print '************* u-r vs M*'
color=s.nsamag[:,2]-s.nsamag[:,4]
#plotabellxy(s.logstellarmass,color,xlab='$log_{10}(M_*)$',ylab='$u - r$',axlim=[8.5,12,0.5,3.5])
color=s.gi_corr
print '************* NUV-r vs M*'
color=s.nsamag[:,1]-s.nsamag[:,4]
plotabellxy(s.logstellarmass,color,xlab='$log_{10}(M_*)$',ylab='$NUV - r$',axlim=[8.5,12,0,6.5])
print '************* u-i vs M*'
color=s.nsamag[:,2]-s.nsamag[:,5]
plotabellxy(s.logstellarmass,color,xlab='$log_{10}(M_*)$',ylab='$u - i$',axlim=[8.5,12,0,4])
print '************* u-24 vs M*'
color=s.NUV24color
plotabellxy(s.logstellarmass,color,xlab='$log_{10}(M_*)$',ylab='$NUV-24$')#,axlim=[8.5,12,0,4])
print '************* size vs M*'
plotabellxy(s.logstellarmass,s.s.SIZE_RATIO,xlab='$log_{10}(M_*)$',ylab='$R_e(24)/R_e(r)$',axlim=[8.5,12,-0.1,2],detectonly=1)
print '************* size vs Sigma_10'
plotabellxy(s.s.SIGMA_10,s.s.SIZE_RATIO,xlab='$ \Sigma_5$',ylab='$R_e(24)/R_e(r)$',axlim=[0.1,100,-.1,2])
gca().set_xscale('log')
print '************* dv vs dr'
plotabellxy(s.s.DR_R200,s.s.DELTA_V,xlab='$ \Delta R/R_{200}$',ylab='$\Delta v$',axlim=[0.,3,-3,3])
def plotabellxy(x,y,xlab=None,ylab=None,axlim=None,detectonly=None,newfigure=True):
if newfigure:
figure(figsize=(6,4))
subplots_adjust(bottom=.2,left=.15)
aflag=((s.s.CLUSTER == 'A2063') | (s.s.CLUSTER == 'A2052')) & (abs(s.s.DELTA_V) < 3)
aflag24=aflag & s.sampleflag
aflag=aflag & s.spiralflag
pflag=aflag24 & s.pointsource
npflag=aflag24 & ~s.pointsource
if detectonly: # plot spirals that don't make the galfit analysis cut
print 'not plotting spirals that dont make galfit cut'
else:
plot(x[aflag & ~aflag24],y[aflag & ~aflag24],'k.')
scatter(x[aflag24],y[aflag24],s=s.s.SIZE_RATIO[aflag24]*60,c='red')
plot(x[pflag],y[pflag],'k*',markersize=14)
if xlab:
xlabel(xlab,fontsize=20)
if ylab:
ylabel(ylab,fontsize=20)
if axlim:
axis(axlim)
print 'comparing x values'
ks(x[npflag],x[pflag])
print 'comparing y values'
ks(y[npflag],y[pflag])
def calc_starburst_fraction():
fcompactstarburst=[]
avesizeratio=[]
for i in range(len(clusternamesbylx)):
cl=clusternames[i]
flag = (s.s.CLUSTER == cl) & s.sampleflag & s.membflag & ~s.agnflag & (s.logstellarmass < 10.4)#& ~s.blueflag
print 'number in ',cl,' = ',sum(flag)
y=np.mean(s.s.SIZE_RATIO[flag])
n=sum(s.compact_starburst & flag)
d=sum(flag)
a,b,c=my.ratioerror(n,d)
print '%s: %5.2f + %5.2f - %5.2f (%i/%i) (N_failed fits = %5.2f)'%(cl,a,b,c,n,d,1.*sum(s.sampleflag & (s.s.CLUSTER == cl))/sum(s.sfsampleflag & (s.s.CLUSTER == cl)))
fcompactstarburst.append(a)
avesizeratio.append(y)
for i in range(len(clusternamesbylx)):
print clusternames[i],fcompactstarburst[i],avesizeratio[i]
spearman(np.array(fcompactstarburst),np.array(avesizeratio))
pl.figure()
pl.subplots_adjust(left=.15,bottom=.15)
plot(np.array(fcompactstarburst),np.array(avesizeratio),'bo')
pl.xlabel('$Frac \ Compact \ Starburst \ Galaxies$')
pl.ylabel('$ave(Re(24)/Re(r))$')
pl.axis([-.01,.4,.2,.8])
def compareSEGalfitradii():
pl.figure()
pl.subplots_adjust(left=.15,bottom=.15)
pl.plot(s.s.fcre1[s.sampleflag],s.s.FLUX_RADIUS2[s.sampleflag],'bo',label='SE R90')
pl.plot(s.s.fcre1[s.sampleflag],s.s.FLUX_RADIUS1[s.sampleflag],'co',label='SE R50')
pl.legend(numpoints=1,loc='lower right')
xl=np.arange(0,8.1)
pl.plot(xl,xl,'k-')
pl.axis([0,10,0,10])
pl.ylabel('$SE \ Flux \ Radius$')
pl.xlabel('$GALFIT \ R50$')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/SEvGalfitRadii.eps')
pl.savefig(homedir+'research/LocalClusters/SamplePlots/SEvGalfitRadii.png')
###############################################################
##################### MAIN PROGRAM #####################
###############################################################
if __name__ == '__main__':
nsa_columns=['ZDIST','SERSIC_TH50','SERSIC_N','D4000','HAEW','VDISP','HAFLUX','N2FLUX','HBFLUX','O3FLUX','AHDEW','CLUMPY','ASYMMETRY','AV','FA','SERSIC_BA']
n_columns=['HIMASS']
galfit24_columns=['cmag1','cnsersic1','cre1','cre1err','caxisratio1','cnumerical_error_flag24']
gim2d_columns=['B_T_r','S2g_1']
zoo_columns=['p_elliptical','p_spiral','p_el','p_cs','p_uncertain','p_mg','p_edge','p_dk']
ce_columns=['LIR_ZDIST','SFR_ZDIST']
ld_columns=['SIGMA_NN','SIGMA_5','SIGMA_10','RHOMASS']
my_columns=['SIZE_RATIO','STELLARMASS','SNR_SE','RMAG', 'DELTA_V','DR_R200','CLUSTER_PHI','HIDef','NUVr_color','CLUSTER_SIGMA','CLUSTER_REDSHIFT','CLUSTER_LX']
infile=homedir+'research/LocalClusters/NSAmastertables/LCS_Spirals_all_size.fits'
infile=homedir+'research/LocalClusters/NSAmastertables/LCS_all_size.fits'
s=spirals(infile,prefix='all')
#e=ellipticals()
#infile=homedir+'research/LocalClusters/NSAmastertables/LCS_Spirals_all_size.fits'
nc=spirals(infile,usecoma=False,prefix='no_coma')
nch=spirals(infile,usecoma=False,useherc=False,prefix='no_comaherc')
#infile=homedir+'research/LocalClusters/NSAmastertables/LCS_Spirals_all.fits'
#c=spirals(infile,onlycoma=True,prefix='only_coma')
|
rfinn/LCS
|
paper1code/LCSanalyzespirals.py
|
Python
|
gpl-3.0
| 337,778
|
[
"Galaxy"
] |
235bd8bca8cedcb26f56f0bea675f4498329fbbc4940315039e287e7ebf1ec5d
|
#!/usr/bin/env python
"""Example of generating a substitution matrix from an alignment.
"""
# standard library
from __future__ import print_function
import sys
# Biopython
from Bio import SubsMat
from Bio import AlignIO
from Bio.Alphabet import IUPAC, Gapped
from Bio.Align import AlignInfo
# get an alignment object from a Clustalw alignment output
c_align = AlignIO.read('protein.aln', 'clustal',
alphabet=Gapped(IUPAC.protein))
summary_align = AlignInfo.SummaryInfo(c_align)
# get a replacement dictionary and accepted replacement matrix
# exclude all amino acids that aren't charged polar
replace_info = summary_align.replacement_dictionary(["G", "A", "V", "L", "I",
"M", "P", "F", "W", "S",
"T", "N", "Q", "Y", "C"])
my_arm = SubsMat.SeqMat(replace_info)
print(replace_info)
my_lom = SubsMat.make_log_odds_matrix(my_arm)
print('log_odds_mat: %s' % my_lom)
my_lom.print_mat()
|
updownlife/multipleK
|
dependencies/biopython-1.65/Doc/examples/make_subsmat.py
|
Python
|
gpl-2.0
| 1,018
|
[
"Biopython"
] |
1a5fb3707f06dfbda8e30f97a8f6a71b884787c0f830249fa56f686c8d49093a
|
# encoding: utf-8
"""A dict subclass that supports attribute style access.
Authors:
* Fernando Perez (original)
* Brian Granger (refactoring to a dict subclass)
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
__all__ = ['Struct']
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
class Struct(dict):
"""A dict subclass with attribute style access.
This dict subclass has a a few extra features:
* Attribute style access.
* Protection of class members (like keys, items) when using attribute
style access.
* The ability to restrict assignment to only existing keys.
* Intelligent merging.
* Overloaded operators.
"""
_allownew = True
def __init__(self, *args, **kw):
"""Initialize with a dictionary, another Struct, or data.
Parameters
----------
args : dict, Struct
Initialize with one dict or Struct
kw : dict
Initialize with key, value pairs.
Examples
--------
>>> s = Struct(a=10,b=30)
>>> s.a
10
>>> s.b
30
>>> s2 = Struct(s,c=30)
>>> sorted(s2.keys())
['a', 'b', 'c']
"""
object.__setattr__(self, '_allownew', True)
dict.__init__(self, *args, **kw)
def __setitem__(self, key, value):
"""Set an item with check for allownew.
Examples
--------
>>> s = Struct()
>>> s['a'] = 10
>>> s.allow_new_attr(False)
>>> s['a'] = 10
>>> s['a']
10
>>> try:
... s['b'] = 20
... except KeyError:
... print('this is not allowed')
...
this is not allowed
"""
if not self._allownew and key not in self:
raise KeyError(
"can't create new attribute %s when allow_new_attr(False)" % key)
dict.__setitem__(self, key, value)
def __setattr__(self, key, value):
"""Set an attr with protection of class members.
This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to
:exc:`AttributeError`.
Examples
--------
>>> s = Struct()
>>> s.a = 10
>>> s.a
10
>>> try:
... s.get = 10
... except AttributeError:
... print("you can't set a class member")
...
you can't set a class member
"""
# If key is an str it might be a class member or instance var
if isinstance(key, str):
# I can't simply call hasattr here because it calls getattr, which
# calls self.__getattr__, which returns True for keys in
# self._data. But I only want keys in the class and in
# self.__dict__
if key in self.__dict__ or hasattr(Struct, key):
raise AttributeError(
'attr %s is a protected member of class Struct.' % key
)
try:
self.__setitem__(key, value)
except KeyError as e:
raise AttributeError(e)
def __getattr__(self, key):
"""Get an attr by calling :meth:`dict.__getitem__`.
Like :meth:`__setattr__`, this method converts :exc:`KeyError` to
:exc:`AttributeError`.
Examples
--------
>>> s = Struct(a=10)
>>> s.a
10
>>> type(s.get)
<... 'builtin_function_or_method'>
>>> try:
... s.b
... except AttributeError:
... print("I don't have that key")
...
I don't have that key
"""
try:
result = self[key]
except KeyError:
raise AttributeError(key)
else:
return result
def __iadd__(self, other):
"""s += s2 is a shorthand for s.merge(s2).
Examples
--------
>>> s = Struct(a=10,b=30)
>>> s2 = Struct(a=20,c=40)
>>> s += s2
>>> sorted(s.keys())
['a', 'b', 'c']
"""
self.merge(other)
return self
def __add__(self, other):
"""s + s2 -> New Struct made from s.merge(s2).
Examples
--------
>>> s1 = Struct(a=10,b=30)
>>> s2 = Struct(a=20,c=40)
>>> s = s1 + s2
>>> sorted(s.keys())
['a', 'b', 'c']
"""
sout = self.copy()
sout.merge(other)
return sout
def __sub__(self, other):
"""s1 - s2 -> remove keys in s2 from s1.
Examples
--------
>>> s1 = Struct(a=10,b=30)
>>> s2 = Struct(a=40)
>>> s = s1 - s2
>>> s
{'b': 30}
"""
sout = self.copy()
sout -= other
return sout
def __isub__(self, other):
"""Inplace remove keys from self that are in other.
Examples
--------
>>> s1 = Struct(a=10,b=30)
>>> s2 = Struct(a=40)
>>> s1 -= s2
>>> s1
{'b': 30}
"""
for k in other.keys():
if k in self:
del self[k]
return self
def __dict_invert(self, data):
"""Helper function for merge.
Takes a dictionary whose values are lists and returns a dict with
the elements of each list as keys and the original keys as values.
"""
outdict = {}
for k, lst in data.items():
if isinstance(lst, str):
lst = lst.split()
for entry in lst:
outdict[entry] = k
return outdict
def dict(self):
return self
def copy(self):
"""Return a copy as a Struct.
Examples
--------
>>> s = Struct(a=10,b=30)
>>> s2 = s.copy()
>>> type(s2) is Struct
True
"""
return Struct(dict.copy(self))
def hasattr(self, key):
"""hasattr function available as a method.
Implemented like has_key.
Examples
--------
>>> s = Struct(a=10)
>>> s.hasattr('a')
True
>>> s.hasattr('b')
False
>>> s.hasattr('get')
False
"""
return key in self
def allow_new_attr(self, allow=True):
"""Set whether new attributes can be created in this Struct.
This can be used to catch typos by verifying that the attribute user
tries to change already exists in this Struct.
"""
object.__setattr__(self, '_allownew', allow)
def merge(self, __loc_data__=None, __conflict_solve=None, **kw):
"""Merge two Structs with customizable conflict resolution.
This is similar to :meth:`update`, but much more flexible. First, a
dict is made from data+key=value pairs. When merging this dict with
the Struct S, the optional dictionary 'conflict' is used to decide
what to do.
If conflict is not given, the default behavior is to preserve any keys
with their current value (the opposite of the :meth:`update` method's
behavior).
Parameters
----------
__loc_data : dict, Struct
The data to merge into self
__conflict_solve : dict
The conflict policy dict. The keys are binary functions used to
resolve the conflict and the values are lists of strings naming
the keys the conflict resolution function applies to. Instead of
a list of strings a space separated string can be used, like
'a b c'.
kw : dict
Additional key, value pairs to merge in
Notes
-----
The `__conflict_solve` dict is a dictionary of binary functions which will be used to
solve key conflicts. Here is an example::
__conflict_solve = dict(
func1=['a','b','c'],
func2=['d','e']
)
In this case, the function :func:`func1` will be used to resolve
keys 'a', 'b' and 'c' and the function :func:`func2` will be used for
keys 'd' and 'e'. This could also be written as::
__conflict_solve = dict(func1='a b c',func2='d e')
These functions will be called for each key they apply to with the
form::
func1(self['a'], other['a'])
The return value is used as the final merged value.
As a convenience, merge() provides five (the most commonly needed)
pre-defined policies: preserve, update, add, add_flip and add_s. The
easiest explanation is their implementation::
preserve = lambda old,new: old
update = lambda old,new: new
add = lambda old,new: old + new
add_flip = lambda old,new: new + old # note change of order!
add_s = lambda old,new: old + ' ' + new # only for str!
You can use those four words (as strings) as keys instead
of defining them as functions, and the merge method will substitute
the appropriate functions for you.
For more complicated conflict resolution policies, you still need to
construct your own functions.
Examples
--------
This show the default policy:
>>> s = Struct(a=10,b=30)
>>> s2 = Struct(a=20,c=40)
>>> s.merge(s2)
>>> sorted(s.items())
[('a', 10), ('b', 30), ('c', 40)]
Now, show how to specify a conflict dict:
>>> s = Struct(a=10,b=30)
>>> s2 = Struct(a=20,b=40)
>>> conflict = {'update':'a','add':'b'}
>>> s.merge(s2,conflict)
>>> sorted(s.items())
[('a', 20), ('b', 70)]
"""
data_dict = dict(__loc_data__, **kw)
# policies for conflict resolution: two argument functions which return
# the value that will go in the new struct
preserve = lambda old, new: old
update = lambda old, new: new
add = lambda old, new: old + new
add_flip = lambda old, new: new + old # note change of order!
add_s = lambda old, new: old + ' ' + new
# default policy is to keep current keys when there's a conflict
conflict_solve = dict.fromkeys(self, preserve)
# the conflict_solve dictionary is given by the user 'inverted': we
# need a name-function mapping, it comes as a function -> names
# dict. Make a local copy (b/c we'll make changes), replace user
# strings for the three builtin policies and invert it.
if __conflict_solve:
inv_conflict_solve_user = __conflict_solve.copy()
for name, func in [('preserve', preserve), ('update', update),
('add', add), ('add_flip', add_flip),
('add_s', add_s)]:
if name in inv_conflict_solve_user.keys():
inv_conflict_solve_user[
func] = inv_conflict_solve_user[name]
del inv_conflict_solve_user[name]
conflict_solve.update(self.__dict_invert(inv_conflict_solve_user))
for key in data_dict:
if key not in self:
self[key] = data_dict[key]
else:
self[key] = conflict_solve[key](self[key], data_dict[key])
|
mattvonrocketstein/smash
|
smashlib/ipy3x/utils/ipstruct.py
|
Python
|
mit
| 11,894
|
[
"Brian"
] |
1155dc780b53d5ecd2949e9385dadb625c05bf9500aff93cb0636916b04e5e3e
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import copy
import warnings
from Bio.Seq import Seq
from bioutils.accessions import primary_assembly_accessions
from bioutils.sequences import reverse_complement
import recordtype
import hgvs.exceptions
import hgvs.location
import hgvs.posedit
import hgvs.transcriptmapper
import hgvs.utils.altseq_to_hgvsp as altseq_to_hgvsp
import hgvs.utils.altseqbuilder as altseqbuilder
import hgvs.variant
from hgvs.decorators.deprecated import deprecated
from hgvs.decorators.lru_cache import lru_cache
UNSET = None
class VariantMapper(object):
"""
Maps HGVS variants to and from g., r., c., and p. representations.
All methods require and return objects of type :class:`hgvs.variant.SequenceVariant`.
"""
# TODO 0.4.0: cache_transcripts was deprecated in 0.3.x; remove in 0.4.0
def __init__(self,hdp,cache_transcripts=UNSET):
self.hdp = hdp
if cache_transcripts != UNSET:
import inspect
upframe = inspect.getframeinfo( inspect.currentframe().f_back )
warnings.warn_explicit(
'VariantMapper cache_transcripts parameter is deprecated and will be removed in a future version',
category=DeprecationWarning,
filename=upframe.filename,
lineno=upframe.lineno + 1)
def g_to_c(self, var_g, tx_ac, alt_aln_method='splign'):
"""Given a genomic (g.) parsed HGVS variant, return a transcript (c.) variant on the specified transcript using
the specified alignment method (default is 'splign' from NCBI).
:param hgvs.variant.SequenceVariant var_g: a variant object
:param str tx_ac: a transcript accession (e.g., NM_012345.6 or ENST012345678)
:param str alt_aln_method: the alignment method; valid values depend on data source
:returns: variant object (:class:`hgvs.variant.SequenceVariant`) using CDS coordinates
:raises hgvs.exceptions.HGVSInvalidVariantError: if var_g is not of type 'g'
"""
if not (var_g.type == 'g'):
raise hgvs.exceptions.HGVSInvalidVariantError('Expected a genomic (g.) variant; got '+ str(var_g))
tm = self._fetch_TranscriptMapper(tx_ac=tx_ac, alt_ac=var_g.ac, alt_aln_method=alt_aln_method)
pos_c = tm.g_to_c( var_g.posedit.pos )
edit_c = self._convert_edit_check_strand(tm.strand, var_g.posedit.edit)
var_c = hgvs.variant.SequenceVariant(ac=tx_ac,
type='c',
posedit=hgvs.posedit.PosEdit( pos_c, edit_c ) )
return var_c
def g_to_r(self, var_g, tx_ac, alt_aln_method='splign'):
"""Given a genomic (g.) parsed HGVS variant, return a transcript (r.) variant on the specified transcript using
the specified alignment method (default is 'splign' from NCBI).
:param hgvs.variant.SequenceVariant var_g: a variant object
:param str tx_ac: a transcript accession (e.g., NM_012345.6 or ENST012345678)
:param str alt_aln_method: the alignment method; valid values depend on data source
:returns: variant object (:class:`hgvs.variant.SequenceVariant`) using transcript (r.) coordinates
:raises hgvs.exceptions.HGVSInvalidVariantError: if var_g is not of type 'g'
"""
if not (var_g.type == 'g'):
raise hgvs.exceptions.HGVSInvalidVariantError('Expected a genomic (g.); got '+ str(var_g))
tm = self._fetch_TranscriptMapper(tx_ac=tx_ac, alt_ac=var_g.ac, alt_aln_method=alt_aln_method)
pos_r = tm.g_to_r( var_g.posedit.pos )
edit_r = self._convert_edit_check_strand(tm.strand, var_g.posedit.edit)
var_r = hgvs.variant.SequenceVariant(ac=tx_ac,
type='r',
posedit=hgvs.posedit.PosEdit( pos_r, edit_r ) )
return var_r
def r_to_g(self, var_r, alt_ac, alt_aln_method='splign'):
"""Given an RNA (r.) parsed HGVS variant, return a genomic (g.) variant on the specified transcript using
the specified alignment method (default is 'splign' from NCBI).
:param hgvs.variant.SequenceVariant var_r: a variant object
:param str alt_ac: a reference sequence accession (e.g., NC_000001.11)
:param str alt_aln_method: the alignment method; valid values depend on data source
:returns: variant object (:class:`hgvs.variant.SequenceVariant`)
:raises hgvs.exceptions.HGVSInvalidVariantError: if var_r is not of type 'r'
"""
if not (var_r.type == 'r'):
raise hgvs.exceptions.HGVSInvalidVariantError('Expected a RNA (r.); got '+ str(var_r))
tm = self._fetch_TranscriptMapper(tx_ac=var_r.ac, alt_ac=alt_ac, alt_aln_method=alt_aln_method)
pos_g = tm.r_to_g( var_r.posedit.pos )
edit_g = self._convert_edit_check_strand(tm.strand, var_r.posedit.edit)
var_g = hgvs.variant.SequenceVariant(ac=alt_ac,
type='g',
posedit=hgvs.posedit.PosEdit( pos_g, edit_g ) )
return var_g
def c_to_g(self, var_c, alt_ac, alt_aln_method='splign'):
"""Given a cDNA (c.) parsed HGVS variant, return a genomic (g.) variant on the specified transcript using
the specified alignment method (default is 'splign' from NCBI).
:param hgvs.variant.SequenceVariant var_c: a variant object
:param str alt_ac: a reference sequence accession (e.g., NC_000001.11)
:param str alt_aln_method: the alignment method; valid values depend on data source
:returns: variant object (:class:`hgvs.variant.SequenceVariant`)
:raises hgvs.exceptions.HGVSInvalidVariantError: if var_c is not of type 'c'
"""
if not (var_c.type == 'c'):
raise hgvs.exceptions.HGVSInvalidVariantError('Expected a cDNA (c.); got ' + str(var_c))
tm = self._fetch_TranscriptMapper(tx_ac=var_c.ac, alt_ac=alt_ac, alt_aln_method=alt_aln_method)
pos_g = tm.c_to_g(var_c.posedit.pos)
edit_g = self._convert_edit_check_strand(tm.strand, var_c.posedit.edit)
var_g = hgvs.variant.SequenceVariant(ac=alt_ac,
type='g',
posedit=hgvs.posedit.PosEdit(pos_g, edit_g))
return var_g
def c_to_r(self, var_c):
"""Given a cDNA (c.) parsed HGVS variant, return a RNA (r.) variant on the specified transcript using
the specified alignment method (default is 'transcript' indicating a self alignment).
:param hgvs.variant.SequenceVariant var_c: a variant object
:returns: variant object (:class:`hgvs.variant.SequenceVariant`)
:raises hgvs.exceptions.HGVSInvalidVariantError: if var_c is not of type 'c'
"""
if not (var_c.type == 'c'):
raise hgvs.exceptions.HGVSInvalidVariantError('Expected a cDNA (c.); got ' + str(var_c))
tm = self._fetch_TranscriptMapper(tx_ac=var_c.ac, alt_ac=var_c.ac, alt_aln_method='transcript')
pos_r = tm.c_to_r(var_c.posedit.pos)
# not necessary to check strand
if isinstance(var_c.posedit.edit, hgvs.edit.NARefAlt) or isinstance(var_c.posedit.edit, hgvs.edit.Dup):
edit_r = var_c.posedit.edit
else:
raise NotImplemented('Only NARefAlt/Dup types are currently implemented')
var_r = hgvs.variant.SequenceVariant(ac=var_c.ac,
type='r',
posedit=hgvs.posedit.PosEdit( pos_r, edit_r ) )
return var_r
def r_to_c(self, var_r):
"""Given an RNA (r.) parsed HGVS variant, return a cDNA (c.) variant on the specified transcript using
the specified alignment method (default is 'transcript' indicating a self alignment).
:param hgvs.variant.SequenceVariant var_r: a variant object
:returns: variant object (:class:`hgvs.variant.SequenceVariant`)
:raises hgvs.exceptions.HGVSInvalidVariantError: if var_r is not of type 'r'
"""
if not (var_r.type == 'r'):
raise hgvs.exceptions.HGVSInvalidVariantError('Expected RNA (r.); got ' + str(var_r))
tm = self._fetch_TranscriptMapper(tx_ac=var_r.ac, alt_ac=var_r.ac, alt_aln_method='transcript')
pos_c = tm.r_to_c(var_r.posedit.pos)
# not necessary to check strand
if isinstance(var_r.posedit.edit, hgvs.edit.NARefAlt) or isinstance(var_r.posedit.edit, hgvs.edit.Dup):
edit_c = var_r.posedit.edit
else:
raise NotImplemented('Only NARefAlt types are currently implemented')
var_c = hgvs.variant.SequenceVariant(ac=var_r.ac,
type='c',
posedit=hgvs.posedit.PosEdit( pos_c, edit_c ) )
return var_c
# TODO: c_to_p needs refactoring
# TODO: data prep belongs in the data interface
def c_to_p(self, var_c, pro_ac=None):
"""
Converts a c. SequenceVariant to a p. SequenceVariant on the specified protein accession
Author: Rudy Rico
:param SequenceVariant var_c: hgvsc tag
:param str pro_ac: protein accession
:rtype: hgvs.variant.SequenceVariant
"""
class RefTranscriptData(recordtype.recordtype('RefTranscriptData',
['transcript_sequence', 'aa_sequence',
'cds_start', 'cds_stop', 'protein_accession'])):
@classmethod
def setup_transcript_data(cls, hdp, tx_ac, pro_ac):
"""helper for generating RefTranscriptData from for c_to_p"""
tx_info = hdp.get_tx_identity_info(var_c.ac)
tx_seq = hdp.get_tx_seq(tx_ac)
if tx_info is None or tx_seq is None:
raise hgvs.exceptions.HGVSError("Missing transcript data for accession: {}".format(tx_ac))
# use 1-based hgvs coords
cds_start = tx_info['cds_start_i'] + 1
cds_stop = tx_info['cds_end_i']
# padding list so biopython won't complain during the conversion
tx_seq_to_translate = tx_seq[cds_start - 1:cds_stop]
if len(tx_seq_to_translate) % 3 != 0:
''.join(list(tx_seq_to_translate).extend(['N']*((3-len(tx_seq_to_translate) % 3) % 3)))
tx_seq_cds = Seq(tx_seq_to_translate)
protein_seq = str(tx_seq_cds.translate())
if pro_ac is None:
# get_acs... will always return at least the MD5_ accession
pro_ac = hdp.get_acs_for_protein_seq(protein_seq)[0]
transcript_data = RefTranscriptData(tx_seq, protein_seq, cds_start,
cds_stop, pro_ac)
return transcript_data
if not (var_c.type == 'c'):
raise hgvs.exceptions.HGVSInvalidVariantError('Expected a cDNA (c.); got ' + str(var_c))
reference_data = RefTranscriptData.setup_transcript_data(self.hdp, var_c.ac, pro_ac)
builder = altseqbuilder.AltSeqBuilder(var_c, reference_data)
# TODO - handle case where you get 2+ alt sequences back; currently get list of 1 element
# loop structure implemented to handle this, but doesn't really do anything currently.
all_alt_data = builder.build_altseq()
var_ps = []
for alt_data in all_alt_data:
builder = altseq_to_hgvsp.AltSeqToHgvsp(reference_data, alt_data)
var_p = builder.build_hgvsp()
var_ps.append(var_p)
var_p = var_ps[0]
return var_p
############################################################################
## DEPRECATED METHODS
@deprecated(use_instead='g_to_c(...)')
def hgvsg_to_hgvsc(self,*args,**kwargs):
return self.g_to_c(*args,**kwargs)
@deprecated(use_instead='g_to_r(...)')
def hgvsg_to_hgvsr(self,*args,**kwargs):
return self.g_to_r(*args,**kwargs)
@deprecated(use_instead='r_to_g(...)')
def hgvsr_to_hgvsg(self,*args,**kwargs):
return self.r_to_g(*args,**kwargs)
@deprecated(use_instead='c_to_g(...)')
def hgvsc_to_hgvsg(self,*args,**kwargs):
return self.c_to_g(*args,**kwargs)
@deprecated(use_instead='c_to_r(...)')
def hgvsc_to_hgvsr(self,*args,**kwargs):
return self.c_to_r(*args,**kwargs)
@deprecated(use_instead='r_to_c(...)')
def hgvsr_to_hgvsc(self,*args,**kwargs):
return self.r_to_c(*args,**kwargs)
@deprecated(use_instead='c_to_p(...)')
def hgvsc_to_hgvsp(self,*args,**kwargs):
return self.c_to_p(*args,**kwargs)
############################################################################
## Internal methods
@lru_cache(maxsize=128)
def _fetch_TranscriptMapper(self, tx_ac, alt_ac, alt_aln_method):
"""
Get a new TranscriptMapper for the given transcript accession (ac),
possibly caching the result.
"""
return hgvs.transcriptmapper.TranscriptMapper(self.hdp, tx_ac=tx_ac, alt_ac=alt_ac,
alt_aln_method=alt_aln_method)
@staticmethod
def _convert_edit_check_strand(strand, edit_in):
"""
Convert an edit from one type to another, based on the stand and type
"""
if isinstance(edit_in, hgvs.edit.NARefAlt):
if strand == 1:
edit_out = copy.deepcopy(edit_in)
else:
try:
# if smells like an int, do nothing
# TODO: should use ref_n, right?
int(edit_in.ref)
ref = edit_in.ref
except (ValueError, TypeError):
ref = reverse_complement(edit_in.ref)
edit_out = hgvs.edit.NARefAlt(
ref = ref,
alt = reverse_complement(edit_in.alt),
)
elif isinstance(edit_in, hgvs.edit.Dup):
if strand == 1:
edit_out = copy.deepcopy(edit_in)
else:
edit_out = hgvs.edit.Dup(
seq = reverse_complement(edit_in.seq)
)
else:
raise NotImplemented('Only NARefAlt/Dup types are currently implemented')
return edit_out
class EasyVariantMapper(VariantMapper):
"""Provides simplified variant mapping for a single assembly and
transcript-reference alignment method.
EasyVariantMapper is instantiated with a primary_assembly and
alt_aln_method. These enable the following conveniences over
VariantMapper:
* The primary assembly and alignment method are used to
automatically select an appropriate chromosomal reference
sequence when mapping from a transcript to a genome (i.e.,
c_to_g(...) and r_to_g(...)).
* A new method, relevant_trancripts(g_variant), returns a list of
transcript accessions available for the specified variant. These
accessions are candidates mapping from genomic to trancript
coordinates (i.e., g_to_c(...) and g_to_r(...)).
[tests occur in module doc (rather than in method doc) to use a
single db connection]
IMPORTANT: Callers should be prepared to catch HGVSError
exceptions. These will be thrown whenever a transcript maps
ambiguously to a chromosome, such as for pseudoautosomal region
transcripts.
"""
# TODO 0.4.0: cache_transcripts was deprecated in 0.3.x; remove in 0.4.0
def __init__(self,hdp,primary_assembly='GRCh37',alt_aln_method='splign',cache_transcripts=UNSET):
super(EasyVariantMapper,self).__init__(hdp=hdp)
self.primary_assembly = primary_assembly
self.alt_aln_method = alt_aln_method
self.primary_assembly_accessions = set(primary_assembly_accessions[primary_assembly])
if cache_transcripts != UNSET:
import inspect
upframe = inspect.getframeinfo( inspect.currentframe().f_back )
warnings.warn_explicit(
'VariantMapper cache_transcripts parameter is deprecated and will be removed in a future version',
category=DeprecationWarning,
filename=upframe.filename,
lineno=upframe.lineno + 1)
def g_to_c(self, var_g, tx_ac):
return super(EasyVariantMapper,self).g_to_c(var_g, tx_ac, alt_aln_method=self.alt_aln_method)
def g_to_r(self, var_g, tx_ac):
return super(EasyVariantMapper,self).g_to_r(var_g, tx_ac, alt_aln_method=self.alt_aln_method)
def c_to_g(self, var_c):
alt_ac = self._alt_ac_for_tx_ac(var_c.ac)
return super(EasyVariantMapper,self).c_to_g(var_c, alt_ac, alt_aln_method=self.alt_aln_method)
def r_to_g(self, var_r):
alt_ac = self._alt_ac_for_tx_ac(var_r.ac)
return super(EasyVariantMapper,self).r_to_g(var_r, alt_ac, alt_aln_method=self.alt_aln_method)
def c_to_r(self, var_c):
return super(EasyVariantMapper,self).c_to_r(var_c)
def r_to_c(self, var_r):
return super(EasyVariantMapper,self).r_to_c(var_r)
def c_to_p(self, var_c):
return super(EasyVariantMapper,self).c_to_p(var_c)
def relevant_transcripts(self,var_g):
"""return list of transcripts accessions (strings) for given variant,
selected by genomic overlap"""
tx = self.hdp.get_tx_for_region(var_g.ac,
self.alt_aln_method,
var_g.posedit.pos.start.base,
var_g.posedit.pos.end.base)
return [ e['tx_ac'] for e in tx ]
def _alt_ac_for_tx_ac(self,tx_ac):
"""return chromosomal accession for given transcript accession (and
the primary_assembly and aln_method setting used to
instantiate this EasyVariantMapper)
"""
alt_acs = [e['alt_ac']
for e in self.hdp.get_tx_mapping_options(tx_ac)
if e['alt_aln_method'] == self.alt_aln_method
and e['alt_ac'] in self.primary_assembly_accessions]
if len(alt_acs) > 1:
raise hgvs.exceptions.HGVSError("Multiple chromosomal alignments for {tx_ac} in {pa}"
"using {am} (likely paralog or pseudoautosomal region)".format(
tx_ac=tx_ac, pa=self.primary_assembly, am=self.alt_aln_method))
if len(alt_acs) == 0:
raise hgvs.exceptions.HGVSError("No alignments for {tx_ac} in {pa} using {am}".format(
tx_ac=tx_ac, pa=self.primary_assembly, am=self.alt_aln_method))
return alt_acs[0] # exactly one remains
## <LICENSE>
## Copyright 2014 HGVS Contributors (https://bitbucket.org/hgvs/hgvs)
##
## 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.
## </LICENSE>
|
jmuhlich/hgvs
|
hgvs/variantmapper.py
|
Python
|
apache-2.0
| 19,777
|
[
"Biopython"
] |
09dde400fa844fa2f908c3d011f86812367f4fda4a3cb2d3aadc2671c9a46df4
|
import numpy as np
from ase.asec.command import Command
class ResultsCommand(Command):
@classmethod
def add_parser(cls, subparser):
parser = subparser.add_parser('results', help='results ...')
def __init__(self, logfile, args):
Command.__init__(self, logfile, args)
self.data = self.read()
def finalize(self):
for name in self.args.names:
if name in self.data:
e = self.data[name].get('energy', 42)
else:
e = 117
print '%2s %10.3f' % (name, e)
|
alexei-matveev/ase-local
|
ase/asec/results.py
|
Python
|
gpl-2.0
| 565
|
[
"ASE"
] |
853b962c1ce4d8989d27d3295cf289052d596d5acbdc24bd395b34f90a4a16c1
|
# -*- coding: utf-8 -*-
import codecs
import warnings
import re
from contextlib import contextmanager
from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule
from parso.python.tree import search_ancestor
_BLOCK_STMTS = ('if_stmt', 'while_stmt', 'for_stmt', 'try_stmt', 'with_stmt')
_STAR_EXPR_PARENTS = ('testlist_star_expr', 'testlist_comp', 'exprlist')
# This is the maximal block size given by python.
_MAX_BLOCK_SIZE = 20
_MAX_INDENT_COUNT = 100
ALLOWED_FUTURES = (
'all_feature_names', 'nested_scopes', 'generators', 'division',
'absolute_import', 'with_statement', 'print_function', 'unicode_literals',
)
_COMP_FOR_TYPES = ('comp_for', 'sync_comp_for')
def _iter_stmts(scope):
"""
Iterates over all statements and splits up simple_stmt.
"""
for child in scope.children:
if child.type == 'simple_stmt':
for child2 in child.children:
if child2.type == 'newline' or child2 == ';':
continue
yield child2
else:
yield child
def _get_comprehension_type(atom):
first, second = atom.children[:2]
if second.type == 'testlist_comp' and second.children[1].type in _COMP_FOR_TYPES:
if first == '[':
return 'list comprehension'
else:
return 'generator expression'
elif second.type == 'dictorsetmaker' and second.children[-1].type in _COMP_FOR_TYPES:
if second.children[1] == ':':
return 'dict comprehension'
else:
return 'set comprehension'
return None
def _is_future_import(import_from):
# It looks like a __future__ import that is relative is still a future
# import. That feels kind of odd, but whatever.
# if import_from.level != 0:
# return False
from_names = import_from.get_from_names()
return [n.value for n in from_names] == ['__future__']
def _remove_parens(atom):
"""
Returns the inner part of an expression like `(foo)`. Also removes nested
parens.
"""
try:
children = atom.children
except AttributeError:
pass
else:
if len(children) == 3 and children[0] == '(':
return _remove_parens(atom.children[1])
return atom
def _iter_params(parent_node):
return (n for n in parent_node.children if n.type == 'param')
def _is_future_import_first(import_from):
"""
Checks if the import is the first statement of a file.
"""
found_docstring = False
for stmt in _iter_stmts(import_from.get_root_node()):
if stmt.type == 'string' and not found_docstring:
continue
found_docstring = True
if stmt == import_from:
return True
if stmt.type == 'import_from' and _is_future_import(stmt):
continue
return False
def _iter_definition_exprs_from_lists(exprlist):
def check_expr(child):
if child.type == 'atom':
if child.children[0] == '(':
testlist_comp = child.children[1]
if testlist_comp.type == 'testlist_comp':
for expr in _iter_definition_exprs_from_lists(testlist_comp):
yield expr
return
else:
# It's a paren that doesn't do anything, like 1 + (1)
for c in check_expr(testlist_comp):
yield c
return
elif child.children[0] == '[':
yield testlist_comp
return
yield child
if exprlist.type in _STAR_EXPR_PARENTS:
for child in exprlist.children[::2]:
for c in check_expr(child): # Python 2 sucks
yield c
else:
for c in check_expr(exprlist): # Python 2 sucks
yield c
def _get_expr_stmt_definition_exprs(expr_stmt):
exprs = []
for list_ in expr_stmt.children[:-2:2]:
if list_.type in ('testlist_star_expr', 'testlist'):
exprs += _iter_definition_exprs_from_lists(list_)
else:
exprs.append(list_)
return exprs
def _get_for_stmt_definition_exprs(for_stmt):
exprlist = for_stmt.children[1]
return list(_iter_definition_exprs_from_lists(exprlist))
class _Context(object):
def __init__(self, node, add_syntax_error, parent_context=None):
self.node = node
self.blocks = []
self.parent_context = parent_context
self._used_name_dict = {}
self._global_names = []
self._nonlocal_names = []
self._nonlocal_names_in_subscopes = []
self._add_syntax_error = add_syntax_error
def is_async_funcdef(self):
# Stupidly enough async funcdefs can have two different forms,
# depending if a decorator is used or not.
return self.is_function() \
and self.node.parent.type in ('async_funcdef', 'async_stmt')
def is_function(self):
return self.node.type == 'funcdef'
def add_name(self, name):
parent_type = name.parent.type
if parent_type == 'trailer':
# We are only interested in first level names.
return
if parent_type == 'global_stmt':
self._global_names.append(name)
elif parent_type == 'nonlocal_stmt':
self._nonlocal_names.append(name)
else:
self._used_name_dict.setdefault(name.value, []).append(name)
def finalize(self):
"""
Returns a list of nonlocal names that need to be part of that scope.
"""
self._analyze_names(self._global_names, 'global')
self._analyze_names(self._nonlocal_names, 'nonlocal')
global_name_strs = {n.value: n for n in self._global_names}
for nonlocal_name in self._nonlocal_names:
try:
global_name = global_name_strs[nonlocal_name.value]
except KeyError:
continue
message = "name '%s' is nonlocal and global" % global_name.value
if global_name.start_pos < nonlocal_name.start_pos:
error_name = global_name
else:
error_name = nonlocal_name
self._add_syntax_error(error_name, message)
nonlocals_not_handled = []
for nonlocal_name in self._nonlocal_names_in_subscopes:
search = nonlocal_name.value
if search in global_name_strs or self.parent_context is None:
message = "no binding for nonlocal '%s' found" % nonlocal_name.value
self._add_syntax_error(nonlocal_name, message)
elif not self.is_function() or \
nonlocal_name.value not in self._used_name_dict:
nonlocals_not_handled.append(nonlocal_name)
return self._nonlocal_names + nonlocals_not_handled
def _analyze_names(self, globals_or_nonlocals, type_):
def raise_(message):
self._add_syntax_error(base_name, message % (base_name.value, type_))
params = []
if self.node.type == 'funcdef':
params = self.node.get_params()
for base_name in globals_or_nonlocals:
found_global_or_nonlocal = False
# Somehow Python does it the reversed way.
for name in reversed(self._used_name_dict.get(base_name.value, [])):
if name.start_pos > base_name.start_pos:
# All following names don't have to be checked.
found_global_or_nonlocal = True
parent = name.parent
if parent.type == 'param' and parent.name == name:
# Skip those here, these definitions belong to the next
# scope.
continue
if name.is_definition():
if parent.type == 'expr_stmt' \
and parent.children[1].type == 'annassign':
if found_global_or_nonlocal:
# If it's after the global the error seems to be
# placed there.
base_name = name
raise_("annotated name '%s' can't be %s")
break
else:
message = "name '%s' is assigned to before %s declaration"
else:
message = "name '%s' is used prior to %s declaration"
if not found_global_or_nonlocal:
raise_(message)
# Only add an error for the first occurence.
break
for param in params:
if param.name.value == base_name.value:
raise_("name '%s' is parameter and %s"),
@contextmanager
def add_block(self, node):
self.blocks.append(node)
yield
self.blocks.pop()
def add_context(self, node):
return _Context(node, self._add_syntax_error, parent_context=self)
def close_child_context(self, child_context):
self._nonlocal_names_in_subscopes += child_context.finalize()
class ErrorFinder(Normalizer):
"""
Searches for errors in the syntax tree.
"""
def __init__(self, *args, **kwargs):
super(ErrorFinder, self).__init__(*args, **kwargs)
self._error_dict = {}
self.version = self.grammar.version_info
def initialize(self, node):
def create_context(node):
if node is None:
return None
parent_context = create_context(node.parent)
if node.type in ('classdef', 'funcdef', 'file_input'):
return _Context(node, self._add_syntax_error, parent_context)
return parent_context
self.context = create_context(node) or _Context(node, self._add_syntax_error)
self._indentation_count = 0
def visit(self, node):
if node.type == 'error_node':
with self.visit_node(node):
# Don't need to investigate the inners of an error node. We
# might find errors in there that should be ignored, because
# the error node itself already shows that there's an issue.
return ''
return super(ErrorFinder, self).visit(node)
@contextmanager
def visit_node(self, node):
self._check_type_rules(node)
if node.type in _BLOCK_STMTS:
with self.context.add_block(node):
if len(self.context.blocks) == _MAX_BLOCK_SIZE:
self._add_syntax_error(node, "too many statically nested blocks")
yield
return
elif node.type == 'suite':
self._indentation_count += 1
if self._indentation_count == _MAX_INDENT_COUNT:
self._add_indentation_error(node.children[1], "too many levels of indentation")
yield
if node.type == 'suite':
self._indentation_count -= 1
elif node.type in ('classdef', 'funcdef'):
context = self.context
self.context = context.parent_context
self.context.close_child_context(context)
def visit_leaf(self, leaf):
if leaf.type == 'error_leaf':
if leaf.token_type in ('INDENT', 'ERROR_DEDENT'):
# Indents/Dedents itself never have a prefix. They are just
# "pseudo" tokens that get removed by the syntax tree later.
# Therefore in case of an error we also have to check for this.
spacing = list(leaf.get_next_leaf()._split_prefix())[-1]
if leaf.token_type == 'INDENT':
message = 'unexpected indent'
else:
message = 'unindent does not match any outer indentation level'
self._add_indentation_error(spacing, message)
else:
if leaf.value.startswith('\\'):
message = 'unexpected character after line continuation character'
else:
match = re.match('\\w{,2}("{1,3}|\'{1,3})', leaf.value)
if match is None:
message = 'invalid syntax'
else:
if len(match.group(1)) == 1:
message = 'EOL while scanning string literal'
else:
message = 'EOF while scanning triple-quoted string literal'
self._add_syntax_error(leaf, message)
return ''
elif leaf.value == ':':
parent = leaf.parent
if parent.type in ('classdef', 'funcdef'):
self.context = self.context.add_context(parent)
# The rest is rule based.
return super(ErrorFinder, self).visit_leaf(leaf)
def _add_indentation_error(self, spacing, message):
self.add_issue(spacing, 903, "IndentationError: " + message)
def _add_syntax_error(self, node, message):
self.add_issue(node, 901, "SyntaxError: " + message)
def add_issue(self, node, code, message):
# Overwrite the default behavior.
# Check if the issues are on the same line.
line = node.start_pos[0]
args = (code, message, node)
self._error_dict.setdefault(line, args)
def finalize(self):
self.context.finalize()
for code, message, node in self._error_dict.values():
self.issues.append(Issue(node, code, message))
class IndentationRule(Rule):
code = 903
def _get_message(self, message):
message = super(IndentationRule, self)._get_message(message)
return "IndentationError: " + message
@ErrorFinder.register_rule(type='error_node')
class _ExpectIndentedBlock(IndentationRule):
message = 'expected an indented block'
def get_node(self, node):
leaf = node.get_next_leaf()
return list(leaf._split_prefix())[-1]
def is_issue(self, node):
# This is the beginning of a suite that is not indented.
return node.children[-1].type == 'newline'
class ErrorFinderConfig(NormalizerConfig):
normalizer_class = ErrorFinder
class SyntaxRule(Rule):
code = 901
def _get_message(self, message):
message = super(SyntaxRule, self)._get_message(message)
return "SyntaxError: " + message
@ErrorFinder.register_rule(type='error_node')
class _InvalidSyntaxRule(SyntaxRule):
message = "invalid syntax"
def get_node(self, node):
return node.get_next_leaf()
def is_issue(self, node):
# Error leafs will be added later as an error.
return node.get_next_leaf().type != 'error_leaf'
@ErrorFinder.register_rule(value='await')
class _AwaitOutsideAsync(SyntaxRule):
message = "'await' outside async function"
def is_issue(self, leaf):
return not self._normalizer.context.is_async_funcdef()
def get_error_node(self, node):
# Return the whole await statement.
return node.parent
@ErrorFinder.register_rule(value='break')
class _BreakOutsideLoop(SyntaxRule):
message = "'break' outside loop"
def is_issue(self, leaf):
in_loop = False
for block in self._normalizer.context.blocks:
if block.type in ('for_stmt', 'while_stmt'):
in_loop = True
return not in_loop
@ErrorFinder.register_rule(value='continue')
class _ContinueChecks(SyntaxRule):
message = "'continue' not properly in loop"
message_in_finally = "'continue' not supported inside 'finally' clause"
def is_issue(self, leaf):
in_loop = False
for block in self._normalizer.context.blocks:
if block.type in ('for_stmt', 'while_stmt'):
in_loop = True
if block.type == 'try_stmt':
last_block = block.children[-3]
if last_block == 'finally' and leaf.start_pos > last_block.start_pos:
self.add_issue(leaf, message=self.message_in_finally)
return False # Error already added
if not in_loop:
return True
@ErrorFinder.register_rule(value='from')
class _YieldFromCheck(SyntaxRule):
message = "'yield from' inside async function"
def get_node(self, leaf):
return leaf.parent.parent # This is the actual yield statement.
def is_issue(self, leaf):
return leaf.parent.type == 'yield_arg' \
and self._normalizer.context.is_async_funcdef()
@ErrorFinder.register_rule(type='name')
class _NameChecks(SyntaxRule):
message = 'cannot assign to __debug__'
message_none = 'cannot assign to None'
def is_issue(self, leaf):
self._normalizer.context.add_name(leaf)
if leaf.value == '__debug__' and leaf.is_definition():
return True
if leaf.value == 'None' and self._normalizer.version < (3, 0) \
and leaf.is_definition():
self.add_issue(leaf, message=self.message_none)
@ErrorFinder.register_rule(type='string')
class _StringChecks(SyntaxRule):
message = "bytes can only contain ASCII literal characters."
def is_issue(self, leaf):
string_prefix = leaf.string_prefix.lower()
if 'b' in string_prefix \
and self._normalizer.version >= (3, 0) \
and any(c for c in leaf.value if ord(c) > 127):
# b'ä'
return True
if 'r' not in string_prefix:
# Raw strings don't need to be checked if they have proper
# escaping.
is_bytes = self._normalizer.version < (3, 0)
if 'b' in string_prefix:
is_bytes = True
if 'u' in string_prefix:
is_bytes = False
payload = leaf._get_payload()
if is_bytes:
payload = payload.encode('utf-8')
func = codecs.escape_decode
else:
func = codecs.unicode_escape_decode
try:
with warnings.catch_warnings():
# The warnings from parsing strings are not relevant.
warnings.filterwarnings('ignore')
func(payload)
except UnicodeDecodeError as e:
self.add_issue(leaf, message='(unicode error) ' + str(e))
except ValueError as e:
self.add_issue(leaf, message='(value error) ' + str(e))
@ErrorFinder.register_rule(value='*')
class _StarCheck(SyntaxRule):
message = "named arguments must follow bare *"
def is_issue(self, leaf):
params = leaf.parent
if params.type == 'parameters' and params:
after = params.children[params.children.index(leaf) + 1:]
after = [child for child in after
if child not in (',', ')') and not child.star_count]
return len(after) == 0
@ErrorFinder.register_rule(value='**')
class _StarStarCheck(SyntaxRule):
# e.g. {**{} for a in [1]}
# TODO this should probably get a better end_pos including
# the next sibling of leaf.
message = "dict unpacking cannot be used in dict comprehension"
def is_issue(self, leaf):
if leaf.parent.type == 'dictorsetmaker':
comp_for = leaf.get_next_sibling().get_next_sibling()
return comp_for is not None and comp_for.type in _COMP_FOR_TYPES
@ErrorFinder.register_rule(value='yield')
@ErrorFinder.register_rule(value='return')
class _ReturnAndYieldChecks(SyntaxRule):
message = "'return' with value in async generator"
message_async_yield = "'yield' inside async function"
def get_node(self, leaf):
return leaf.parent
def is_issue(self, leaf):
if self._normalizer.context.node.type != 'funcdef':
self.add_issue(self.get_node(leaf), message="'%s' outside function" % leaf.value)
elif self._normalizer.context.is_async_funcdef() \
and any(self._normalizer.context.node.iter_yield_exprs()):
if leaf.value == 'return' and leaf.parent.type == 'return_stmt':
return True
elif leaf.value == 'yield' \
and leaf.get_next_leaf() != 'from' \
and self._normalizer.version == (3, 5):
self.add_issue(self.get_node(leaf), message=self.message_async_yield)
@ErrorFinder.register_rule(type='strings')
class _BytesAndStringMix(SyntaxRule):
# e.g. 's' b''
message = "cannot mix bytes and nonbytes literals"
def _is_bytes_literal(self, string):
if string.type == 'fstring':
return False
return 'b' in string.string_prefix.lower()
def is_issue(self, node):
first = node.children[0]
# In Python 2 it's allowed to mix bytes and unicode.
if self._normalizer.version >= (3, 0):
first_is_bytes = self._is_bytes_literal(first)
for string in node.children[1:]:
if first_is_bytes != self._is_bytes_literal(string):
return True
@ErrorFinder.register_rule(type='import_as_names')
class _TrailingImportComma(SyntaxRule):
# e.g. from foo import a,
message = "trailing comma not allowed without surrounding parentheses"
def is_issue(self, node):
if node.children[-1] == ',' and node.parent.children[-1] != ')':
return True
@ErrorFinder.register_rule(type='import_from')
class _ImportStarInFunction(SyntaxRule):
message = "import * only allowed at module level"
def is_issue(self, node):
return node.is_star_import() and self._normalizer.context.parent_context is not None
@ErrorFinder.register_rule(type='import_from')
class _FutureImportRule(SyntaxRule):
message = "from __future__ imports must occur at the beginning of the file"
def is_issue(self, node):
if _is_future_import(node):
if not _is_future_import_first(node):
return True
for from_name, future_name in node.get_paths():
name = future_name.value
allowed_futures = list(ALLOWED_FUTURES)
if self._normalizer.version >= (3, 5):
allowed_futures.append('generator_stop')
if name == 'braces':
self.add_issue(node, message="not a chance")
elif name == 'barry_as_FLUFL':
m = "Seriously I'm not implementing this :) ~ Dave"
self.add_issue(node, message=m)
elif name not in ALLOWED_FUTURES:
message = "future feature %s is not defined" % name
self.add_issue(node, message=message)
@ErrorFinder.register_rule(type='star_expr')
class _StarExprRule(SyntaxRule):
message = "starred assignment target must be in a list or tuple"
message_iterable_unpacking = "iterable unpacking cannot be used in comprehension"
message_assignment = "can use starred expression only as assignment target"
def is_issue(self, node):
if node.parent.type not in _STAR_EXPR_PARENTS:
return True
if node.parent.type == 'testlist_comp':
# [*[] for a in [1]]
if node.parent.children[1].type in _COMP_FOR_TYPES:
self.add_issue(node, message=self.message_iterable_unpacking)
if self._normalizer.version <= (3, 4):
n = search_ancestor(node, 'for_stmt', 'expr_stmt')
found_definition = False
if n is not None:
if n.type == 'expr_stmt':
exprs = _get_expr_stmt_definition_exprs(n)
else:
exprs = _get_for_stmt_definition_exprs(n)
if node in exprs:
found_definition = True
if not found_definition:
self.add_issue(node, message=self.message_assignment)
@ErrorFinder.register_rule(types=_STAR_EXPR_PARENTS)
class _StarExprParentRule(SyntaxRule):
def is_issue(self, node):
if node.parent.type == 'del_stmt':
self.add_issue(node.parent, message="can't use starred expression here")
else:
def is_definition(node, ancestor):
if ancestor is None:
return False
type_ = ancestor.type
if type_ == 'trailer':
return False
if type_ == 'expr_stmt':
return node.start_pos < ancestor.children[-1].start_pos
return is_definition(node, ancestor.parent)
if is_definition(node, node.parent):
args = [c for c in node.children if c != ',']
starred = [c for c in args if c.type == 'star_expr']
if len(starred) > 1:
message = "two starred expressions in assignment"
self.add_issue(starred[1], message=message)
elif starred:
count = args.index(starred[0])
if count >= 256:
message = "too many expressions in star-unpacking assignment"
self.add_issue(starred[0], message=message)
@ErrorFinder.register_rule(type='annassign')
class _AnnotatorRule(SyntaxRule):
# True: int
# {}: float
message = "illegal target for annotation"
def get_node(self, node):
return node.parent
def is_issue(self, node):
type_ = None
lhs = node.parent.children[0]
lhs = _remove_parens(lhs)
try:
children = lhs.children
except AttributeError:
pass
else:
if ',' in children or lhs.type == 'atom' and children[0] == '(':
type_ = 'tuple'
elif lhs.type == 'atom' and children[0] == '[':
type_ = 'list'
trailer = children[-1]
if type_ is None:
if not (lhs.type == 'name'
# subscript/attributes are allowed
or lhs.type in ('atom_expr', 'power')
and trailer.type == 'trailer'
and trailer.children[0] != '('):
return True
else:
# x, y: str
message = "only single target (not %s) can be annotated"
self.add_issue(lhs.parent, message=message % type_)
@ErrorFinder.register_rule(type='argument')
class _ArgumentRule(SyntaxRule):
def is_issue(self, node):
first = node.children[0]
if node.children[1] == '=' and first.type != 'name':
if first.type == 'lambdef':
# f(lambda: 1=1)
if self._normalizer.version < (3, 8):
message = "lambda cannot contain assignment"
else:
message = 'expression cannot contain assignment, perhaps you meant "=="?'
else:
# f(+x=1)
if self._normalizer.version < (3, 8):
message = "keyword can't be an expression"
else:
message = 'expression cannot contain assignment, perhaps you meant "=="?'
self.add_issue(first, message=message)
@ErrorFinder.register_rule(type='nonlocal_stmt')
class _NonlocalModuleLevelRule(SyntaxRule):
message = "nonlocal declaration not allowed at module level"
def is_issue(self, node):
return self._normalizer.context.parent_context is None
@ErrorFinder.register_rule(type='arglist')
class _ArglistRule(SyntaxRule):
@property
def message(self):
if self._normalizer.version < (3, 7):
return "Generator expression must be parenthesized if not sole argument"
else:
return "Generator expression must be parenthesized"
def is_issue(self, node):
first_arg = node.children[0]
if first_arg.type == 'argument' \
and first_arg.children[1].type in _COMP_FOR_TYPES:
# e.g. foo(x for x in [], b)
return len(node.children) >= 2
else:
arg_set = set()
kw_only = False
kw_unpacking_only = False
is_old_starred = False
# In python 3 this would be a bit easier (stars are part of
# argument), but we have to understand both.
for argument in node.children:
if argument == ',':
continue
if argument in ('*', '**'):
# Python < 3.5 has the order engraved in the grammar
# file. No need to do anything here.
is_old_starred = True
continue
if is_old_starred:
is_old_starred = False
continue
if argument.type == 'argument':
first = argument.children[0]
if first in ('*', '**'):
if first == '*':
if kw_unpacking_only:
# foo(**kwargs, *args)
message = "iterable argument unpacking " \
"follows keyword argument unpacking"
self.add_issue(argument, message=message)
else:
kw_unpacking_only = True
else: # Is a keyword argument.
kw_only = True
if first.type == 'name':
if first.value in arg_set:
# f(x=1, x=2)
self.add_issue(first, message="keyword argument repeated")
else:
arg_set.add(first.value)
else:
if kw_unpacking_only:
# f(**x, y)
message = "positional argument follows keyword argument unpacking"
self.add_issue(argument, message=message)
elif kw_only:
# f(x=2, y)
message = "positional argument follows keyword argument"
self.add_issue(argument, message=message)
@ErrorFinder.register_rule(type='parameters')
@ErrorFinder.register_rule(type='lambdef')
class _ParameterRule(SyntaxRule):
# def f(x=3, y): pass
message = "non-default argument follows default argument"
def is_issue(self, node):
param_names = set()
default_only = False
for p in _iter_params(node):
if p.name.value in param_names:
message = "duplicate argument '%s' in function definition"
self.add_issue(p.name, message=message % p.name.value)
param_names.add(p.name.value)
if p.default is None and not p.star_count:
if default_only:
return True
else:
default_only = True
@ErrorFinder.register_rule(type='try_stmt')
class _TryStmtRule(SyntaxRule):
message = "default 'except:' must be last"
def is_issue(self, try_stmt):
default_except = None
for except_clause in try_stmt.children[3::3]:
if except_clause in ('else', 'finally'):
break
if except_clause == 'except':
default_except = except_clause
elif default_except is not None:
self.add_issue(default_except, message=self.message)
@ErrorFinder.register_rule(type='fstring')
class _FStringRule(SyntaxRule):
_fstring_grammar = None
message_expr = "f-string expression part cannot include a backslash"
message_nested = "f-string: expressions nested too deeply"
message_conversion = "f-string: invalid conversion character: expected 's', 'r', or 'a'"
def _check_format_spec(self, format_spec, depth):
self._check_fstring_contents(format_spec.children[1:], depth)
def _check_fstring_expr(self, fstring_expr, depth):
if depth >= 2:
self.add_issue(fstring_expr, message=self.message_nested)
expr = fstring_expr.children[1]
if '\\' in expr.get_code():
self.add_issue(expr, message=self.message_expr)
conversion = fstring_expr.children[2]
if conversion.type == 'fstring_conversion':
name = conversion.children[1]
if name.value not in ('s', 'r', 'a'):
self.add_issue(name, message=self.message_conversion)
format_spec = fstring_expr.children[-2]
if format_spec.type == 'fstring_format_spec':
self._check_format_spec(format_spec, depth + 1)
def is_issue(self, fstring):
self._check_fstring_contents(fstring.children[1:-1])
def _check_fstring_contents(self, children, depth=0):
for fstring_content in children:
if fstring_content.type == 'fstring_expr':
self._check_fstring_expr(fstring_content, depth)
class _CheckAssignmentRule(SyntaxRule):
def _check_assignment(self, node, is_deletion=False, is_namedexpr=False):
error = None
type_ = node.type
if type_ == 'lambdef':
error = 'lambda'
elif type_ == 'atom':
first, second = node.children[:2]
error = _get_comprehension_type(node)
if error is None:
if second.type == 'dictorsetmaker':
if self._normalizer.version < (3, 8):
error = 'literal'
else:
if second.children[1] == ':':
error = 'dict display'
else:
error = 'set display'
elif first in ('(', '['):
if second.type == 'yield_expr':
error = 'yield expression'
elif second.type == 'testlist_comp':
# ([a, b] := [1, 2])
# ((a, b) := [1, 2])
if is_namedexpr:
if first == '(':
error = 'tuple'
elif first == '[':
error = 'list'
# This is not a comprehension, they were handled
# further above.
for child in second.children[::2]:
self._check_assignment(child, is_deletion, is_namedexpr)
else: # Everything handled, must be useless brackets.
self._check_assignment(second, is_deletion, is_namedexpr)
elif type_ == 'keyword':
if self._normalizer.version < (3, 8):
error = 'keyword'
else:
error = str(node.value)
elif type_ == 'operator':
if node.value == '...':
error = 'Ellipsis'
elif type_ == 'comparison':
error = 'comparison'
elif type_ in ('string', 'number', 'strings'):
error = 'literal'
elif type_ == 'yield_expr':
# This one seems to be a slightly different warning in Python.
message = 'assignment to yield expression not possible'
self.add_issue(node, message=message)
elif type_ == 'test':
error = 'conditional expression'
elif type_ in ('atom_expr', 'power'):
if node.children[0] == 'await':
error = 'await expression'
elif node.children[-2] == '**':
error = 'operator'
else:
# Has a trailer
trailer = node.children[-1]
assert trailer.type == 'trailer'
if trailer.children[0] == '(':
error = 'function call'
elif is_namedexpr and trailer.children[0] == '[':
error = 'subscript'
elif is_namedexpr and trailer.children[0] == '.':
error = 'attribute'
elif type_ in ('testlist_star_expr', 'exprlist', 'testlist'):
for child in node.children[::2]:
self._check_assignment(child, is_deletion, is_namedexpr)
elif ('expr' in type_ and type_ != 'star_expr' # is a substring
or '_test' in type_
or type_ in ('term', 'factor')):
error = 'operator'
if error is not None:
if is_namedexpr:
message = 'cannot use assignment expressions with %s' % error
else:
cannot = "can't" if self._normalizer.version < (3, 8) else "cannot"
message = ' '.join([cannot, "delete" if is_deletion else "assign to", error])
self.add_issue(node, message=message)
@ErrorFinder.register_rule(type='sync_comp_for')
class _CompForRule(_CheckAssignmentRule):
message = "asynchronous comprehension outside of an asynchronous function"
def is_issue(self, node):
expr_list = node.children[1]
if expr_list.type != 'expr_list': # Already handled.
self._check_assignment(expr_list)
return node.parent.children[0] == 'async' \
and not self._normalizer.context.is_async_funcdef()
@ErrorFinder.register_rule(type='expr_stmt')
class _ExprStmtRule(_CheckAssignmentRule):
message = "illegal expression for augmented assignment"
def is_issue(self, node):
for before_equal in node.children[:-2:2]:
self._check_assignment(before_equal)
augassign = node.children[1]
if augassign != '=' and augassign.type != 'annassign': # Is augassign.
return node.children[0].type in ('testlist_star_expr', 'atom', 'testlist')
@ErrorFinder.register_rule(type='with_item')
class _WithItemRule(_CheckAssignmentRule):
def is_issue(self, with_item):
self._check_assignment(with_item.children[2])
@ErrorFinder.register_rule(type='del_stmt')
class _DelStmtRule(_CheckAssignmentRule):
def is_issue(self, del_stmt):
child = del_stmt.children[1]
if child.type != 'expr_list': # Already handled.
self._check_assignment(child, is_deletion=True)
@ErrorFinder.register_rule(type='expr_list')
class _ExprListRule(_CheckAssignmentRule):
def is_issue(self, expr_list):
for expr in expr_list.children[::2]:
self._check_assignment(expr)
@ErrorFinder.register_rule(type='for_stmt')
class _ForStmtRule(_CheckAssignmentRule):
def is_issue(self, for_stmt):
# Some of the nodes here are already used, so no else if
expr_list = for_stmt.children[1]
if expr_list.type != 'expr_list': # Already handled.
self._check_assignment(expr_list)
@ErrorFinder.register_rule(type='namedexpr_test')
class _NamedExprRule(_CheckAssignmentRule):
# namedexpr_test: test [':=' test]
def is_issue(self, namedexpr_test):
# assigned name
first = namedexpr_test.children[0]
def search_namedexpr_in_comp_for(node):
while True:
parent = node.parent
if parent is None:
return parent
if parent.type == 'sync_comp_for' and parent.children[3] == node:
return parent
node = parent
if search_namedexpr_in_comp_for(namedexpr_test):
# [i+1 for i in (i := range(5))]
# [i+1 for i in (j := range(5))]
# [i+1 for i in (lambda: (j := range(5)))()]
message = 'assignment expression cannot be used in a comprehension iterable expression'
self.add_issue(namedexpr_test, message=message)
# defined names
exprlist = list()
def process_comp_for(comp_for):
if comp_for.type == 'sync_comp_for':
comp = comp_for
elif comp_for.type == 'comp_for':
comp = comp_for.children[1]
exprlist.extend(_get_for_stmt_definition_exprs(comp))
def search_all_comp_ancestors(node):
has_ancestors = False
while True:
node = search_ancestor(node, 'testlist_comp', 'dictorsetmaker')
if node is None:
break
for child in node.children:
if child.type in _COMP_FOR_TYPES:
process_comp_for(child)
has_ancestors = True
break
return has_ancestors
# check assignment expressions in comprehensions
search_all = search_all_comp_ancestors(namedexpr_test)
if search_all:
if self._normalizer.context.node.type == 'classdef':
message = 'assignment expression within a comprehension ' \
'cannot be used in a class body'
self.add_issue(namedexpr_test, message=message)
namelist = [expr.value for expr in exprlist if expr.type == 'name']
if first.type == 'name' and first.value in namelist:
# [i := 0 for i, j in range(5)]
# [[(i := i) for j in range(5)] for i in range(5)]
# [i for i, j in range(5) if True or (i := 1)]
# [False and (i := 0) for i, j in range(5)]
message = 'assignment expression cannot rebind ' \
'comprehension iteration variable %r' % first.value
self.add_issue(namedexpr_test, message=message)
self._check_assignment(first, is_namedexpr=True)
|
srusskih/SublimeJEDI
|
dependencies/parso/python/errors.py
|
Python
|
mit
| 41,625
|
[
"VisIt"
] |
46d934cbc00867f48fc3fccdc1d5f4011d47747915766a4362537cbcccd8d4e8
|
"""
Some simple modules for doing runtime visualization
.. todo::
Added support for image cache and some global data structure that provides a map into the image cache
Clean up Viewers.py
.. inheritance-diagram:: proteus.Viewers
:parts: 1
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from builtins import range
from builtins import object
from past.utils import old_div
import subprocess
import numpy
cmdFile=None
datFile=None
datFilename=None
viewerPipe=None
viewerType=None
plotNumber=None
windowNumber=None
meshDataStructuresWritten=None
def gnuplotOn(problemName):
global viewerPipe,cmdFile,datFilename,datFile,viewerType,plotNumber,windowNumber
viewerPipe=subprocess.Popen('gnuplot',shell=True,bufsize=1,stdin=subprocess.PIPE).stdin
cmdFile=open(problemName+'_gnuplot.cmd','w',1)
datFilename = problemName+'_gnuplot.dat'
datFile=open(datFilename,'w',1)
viewerType='gnuplot'
plotNumber=0
windowNumber=0
def matlabOn(problemName,silent=True):
global viewerPipe,cmdFile,datFilename,datFile,viewerType,plotNumber,windowNumber
#mwf add for handling mesh data structures
#mwf debug
if silent == True:
viewerPipe=open('/dev/null','w',1)
else:
# viewerPipe=subprocess.Popen('matlab -nosplash -nodesktop -nojvm',shell=True,bufsize=1,
# stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE).stdin
dummyFile = open('/dev/null','w')
viewerPipe=subprocess.Popen('matlab -nosplash -nodesktop -nojvm',shell=True,bufsize=1,
stdin=subprocess.PIPE,stdout=dummyFile,stderr=dummyFile).stdin
cmdFile=open(problemName+'.m','w',1)
viewerType='matlab'
plotNumber=0
windowNumber=0
meshDataStructuresWritten = False
def vtkOn(problemName,silent=True):
global viewerPipe,cmdFile,datFilename,datFile,viewerType,plotNumber,windowNumber
#viewerPipe=subprocess.Popen('gnuplot',shell=True,bufsize=1,stdin=subprocess.PIPE).stdin
viewerPipe=open('/dev/null','w',1)
cmdFile=open(problemName+'_vtk_dummy.cmd','w',1)
datFilename = problemName+'_vtk_dummy.dat'
datFile=open(datFilename,'w',1)
import os
from proteusGraphical import vtkViewers
#vtkViewers.g.ImageFolderPath = os.path.abspath('.')+"/results/"
vtkViewers.g.ImageFolderPath = os.path.abspath('.')+"/tmp/"+problemName+"/"
if not os.path.exists(vtkViewers.g.ImageFolderPath):
os.makedirs(vtkViewers.g.ImageFolderPath)
viewerType='vtk'
plotNumber=0
windowNumber=0
return vtkViewers
def viewerOn(problemName,viewer):
if viewer == 'gnuplot':
return gnuplotOn(problemName)
if viewer == 'matlab':
return matlabOn(problemName)
if viewer == 'vtk':
return vtkOn(problemName)
def newPlot():
global plotNumber
#print "plot number",plotNumber
plotNumber +=1
def newWindow():
global windowNumber
#print "window",windowNumber
windowNumber +=1
class V_base(object):
def __init__(self,
p=None,
n=None,
s=None):
if p is None:
from . import default_p as p
if n is None:
from . import default_n as n
if s is None:
from . import default_s as s
global cmdFile,datFile,datFilename,viewerPipe,viewerType,plotNumber,windowNumber,meshDataStructuresWritten
self.cmdFile=cmdFile
self.datFile=datFile
self.datFilename = datFilename
self.viewerPipe=viewerPipe
self.viewerType=viewerType
self.meshDataStructuresWritten=meshDataStructuresWritten
#check s for correctness somewhere
self.p=p
self.n=n
self.s=s
if n.nnx is not None:
self.dgridx = (n.nnx-1)*(2**n.nLevels)
else:
self.dgridx = 1.0
if n.nny is not None:
self.dgridy = (n.nny-1)*(2**n.nLevels)
else:
self.dgridy = 1.0
if n.nnz is not None:
self.dgridz = (n.nnz-1)*(2**n.nLevels)
else:
self.dgridz = 1.0
self.plotOffSet = None
self.stepPlotCalled = {}
self.stepPlotCalled['exact']=False; self.stepPlotCalled['elementQuantities']=False
self.plotWindowStart= {}
if self.s.viewComponents == 'All':
self.s.viewComponents = list(range(self.p.coefficients.nc))
def windowNumber(self):
global windowNumber
return windowNumber
def plotNumber(self):
global plotNumber
return plotNumber
def preprocess(self,mlvt,tsim):
if (('Init' in self.s.viewTimes or
'All' in self.s.viewTimes or
tsim in self.s.viewTimes)
and
'u' in self.s.viewQuantities):
if self.plotOffSet is None:
self.plotOffSet = self.windowNumber()
self.windowNumberTmp= mlvt.levelModelList[-1].viewSolution(plotOffSet=self.plotOffSet,
titleModifier='',
dgridnx=self.dgridx,
dgridny=self.dgridy,
pause=self.s.viewerPause)
#should create new windows if plotted here
self.stepPlotExact(mlvt,tsim)
self.stepPlotElementQuantities(mlvt,tsim)
def processTimeLevel(self,mlvt,tsim=None,plotOffSet=None):
if ('All' in self.s.viewTimes or
tsim in self.s.viewTimes):
self.stepProcessPlot(mlvt,tsim)
def postprocess(self,mlvt,tsim):
if ('All' in self.s.viewTimes or
'Last' in self.s.viewTimes or
tsim in self.s.viewTimes):
self.stepProcessPlot(mlvt,tsim)
def stepProcessPlot(self,mlvt,tsim):
"""plot desired quantities for a single step
Parameters
----------
mlvt : multilevel vector transport that holds the quantities to measure
tsim : simulation time
assumes this is the correct time to plot
"""
import pdb
nplots = 0
if 'u' in self.s.viewQuantities:
self.windowNumberSave = self.windowNumber()
mlvt.levelModelList[-1].viewSolution(plotOffSet=self.plotOffSet,titleModifier='',
dgridnx=self.dgridx,dgridny=self.dgridy,pause=self.s.viewerPause)
if self.plotOffSet is None:
self.plotOffSet = self.windowNumberSave
#end if
self.stepPlotExact(mlvt,tsim)
self.stepPlotElementQuantities(mlvt,tsim)
def stepPlotExact(self,mlvt,tsim):
"""plot 'exact' value of desired quantities for a single step
Parameters
----------
mlvt : multilevel vector transport that holds the quantities to measure
tsim : simulation time
assumes this is the correct time to plot
and plotOffSet is set correctly
"""
# TO DO: Fix scaling for exact vector components to match Transport
#mwf taking a lot of time on jade
if ('u_exact' not in self.s.viewQuantities) and ('velocity_exact' not in self.s.viewQuantities):
return
global windowNumber
try:
from proteusGraphical import vtkViewers
except:
return
vt = mlvt.levelModelList[-1]
self.windowNumberSave = self.windowNumber()
#try not to orphan exact plots
if self.stepPlotCalled['exact'] == True:
windowNumber = self.plotWindowStart['exact']
matlabNodalPointsWritten = False #keep track of data structures written for matlab
for ci in range(self.p.coefficients.nc):
if (ci in self.s.viewComponents):
plotExact= 'u_exact' in self.s.viewQuantities and \
self.p.analyticalSolution is not None and \
ci in self.p.analyticalSolution and \
self.p.analyticalSolution[ci] is not None
if plotExact:
#copy the code from VectorTransport.viewSolution as much as possibe
if self.viewerType == 'gnuplot':
title=vt.coefficients.variableNames[ci]+'_exact: t=%12.5e' % tsim
if vt.nSpace_global == 1:
xandu = [(vt.mesh.nodeArray[nN,0],self.p.analyticalSolution[ci].uOfXT(vt.mesh.nodeArray[nN],tsim))
for nN in range(vt.mesh.nNodes_global)]
xandu.sort()
for xu in xandu:
self.datFile.write("%12.5e %12.5e \n" % (xu[0],xu[1]))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with linespoints title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#end if 1d
elif vt.nSpace_global == 2:
for x in vt.mesh.nodeArray[:,:]:
uex = self.p.analyticalSolution[ci].uOfXT(x,tsim)
self.datFile.write("%12.5e %12.5e %12.5e \n" % (x[0],x[1],uex))
self.datFile.write("\n \n")
cmd = "set dgrid3d %d,%d,16; set contour base; set term x11 %i; splot \'%s\' index %i with lines title \"%s\" \n" % (self.dgridx,
self.dgridy,
self.windowNumber(),
self.datFilename,
self.plotNumber(),
title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#end 2d
elif vt.nSpace_global == 3:
(slice_x,slice_y,slice_z) = vt.mesh.nodeArray[old_div(vt.mesh.nodeArray.shape[0],2),:]
for x in vt.mesh.nodeArray[:,:]:
uex = self.p.analyticalSolution[ci].uOfXT(x,tsim)
if x[0] == slice_x:
self.datFile.write("%12.5e %12.5e %12.5e\n" % (x[1],x[2],uex))
self.datFile.write("\n \n")
cmd = "set dgrid3d; set contour base; set term x11 %i; splot \'%s\' index %i with lines title \"%s-x-slice\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
for x in vt.mesh.nodeArray[:,:]:
uex = self.p.analyticalSolution[ci].uOfXT(x,tsim)
if x[1] == slice_y:
self.datFile.write("%12.5e %12.5e %12.5e\n" % (x[0],x[2],uex))
self.datFile.write("\n \n")
cmd = "set dgrid3d; set contour base; set term x11 %i; splot \'%s\' index %i with lines title \"%s-y-slice\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
for x in vt.mesh.nodeArray[:,:]:
uex = self.p.analyticalSolution[ci].uOfXT(x,tsim)
if x[2] == slice_z:
self.datFile.write("%12.5e %12.5e %12.5e\n" % (x[0],x[1],uex))
self.datFile.write("\n \n")
cmd = "set dgrid3d; set contour base; set term x11 %i; splot \'%s\' index %i with lines title \"%s-z-slice\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#end 3d
#end gnuplot
elif self.viewerType == 'matlab':
#assume matlab data structures will be written elsewhere
title=vt.coefficients.variableNames[ci]+'-exact: t=%12.5e' % tsim
name =vt.coefficients.variableNames[ci]
writer = MatlabWriter(nxgrid=50,nygrid=50,nzgrid=50)
nplotted = writer.viewScalarAnalyticalFunction(self.cmdFile,vt.nSpace_global,
self.p.analyticalSolution[ci].uOfXT,tsim,
vt.mesh.nodeArray,vt.mesh.elementNodesArray,
name=name,storeMeshData=not self.meshDataStructuresWritten,
figureNumber =self.windowNumber()+1,title=title)
windowNumber += nplotted
elif self.viewerType == 'vtk':
title=vt.coefficients.variableNames[ci]+'_exact'
if vt.nSpace_global == 1:
xvals = []; yvals = []
for x in vt.mesh.nodeArray:
uex = self.p.analyticalSolution[ci].uOfXT(x,tsim)
xvals.append(x[0]); yvals.append(uex)
#
vtkViewers.viewScalar_1D(xvals,yvals,"x",vt.coefficients.variableNames[ci]+'_exact',title,
self.windowNumber(),
Pause=self.viewerPause,sortPoints=True)
newPlot()
newWindow()
#1d
#vtk
#end plotExact
plotExactVel = ('velocity_exact' in self.s.viewQuantities and
'p.analyticalSolutionVelocity' in dir(p) and
self.p.p.analyticalSolutionVelocity is not None and
('velocity',ci) in vt.q)
if plotExactVel:
import math
if self.viewerType == 'gnuplot':
title=vt.coefficients.variableNames[ci]+'velocity_exact: t=%12.5e' % tsim
#to scale need exact solution values everywhere first
v = numpy.zeros(vt.q[('velocity',ci)].shape,'d')
if vt.nSpace_global == 1:
max_u = 0.0;
for eN in range(vt.mesh.nElements_global):
for k in range(vt.nQuadraturePoints_element):
xtmp = vt.q['x'][eN,k,:];
v[eN,k,:] = self.p.p.analyticalSolutionVelocity[ci].uOfXT(xtmp,tsim)
max_u=max(abs(v[eN,k,0]),max_u)
scale = 10.*max_u
if abs(scale) < 1.0e-12:
scale = 1.0
for eN in range(vt.mesh.nElements_global):
for k in range(vt.nQuadraturePoints_element):
xtmp = vt.q['x'][eN,k,:];
vtmp = v[eN,k,:]
self.datFile.write("%12.5e %12.5e \n" % (xtmp[0],old_div(vtmp[0],scale)))
cmd = "set term x11 %i; plot \'%s\' index %i with linespoints title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
elif vt.nSpace_global == 2:
max_u = 0.0; max_v =0.0;
for eN in range(vt.mesh.nElements_global):
for k in range(vt.nQuadraturePoints_element):
xtmp = vt.q['x'][eN,k,:];
v[eN,k,:] = self.p.p.analyticalSolutionVelocity[ci].uOfXT(xtmp,tsim)
max_u=max(max_u,abs(v[eN,k,0]))
max_v=max(max_u,abs(v[eN,k,1]))
scale = 10.0*math.sqrt(max_u**2 + max_v**2)
if abs(scale) < 1.e-12:
scale = 1.0
for eN in range(vt.mesh.nElements_global):
for k in range(vt.nQuadraturePoints_element):
xtmp = vt.q['x'][eN,k,:];
vtmp = v[eN,k,:]
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[0],xtmp[1],
old_div(vtmp[0],scale),old_div(vtmp[1],scale)))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
elif vt.nSpace_global == 3:
max_u = 0.0; max_v =0.0; max_w = 0.0;
(slice_x,slice_y,slice_z) = vt.mesh.nodeArray[old_div(vt.mesh.nodeArray.shape[0],2),:]
for eN in range(vt.mesh.nElements_global):
for k in range(vt.nQuadraturePoints_element):
xtmp = vt.q['x'][eN,k,:];
v[eN,k,:] = self.p.p.analyticalSolutionVelocity[ci].uOfXT(xtmp,tsim)
max_u=max(max_u,abs(v[eN,k,0]))
max_v=max(max_u,abs(v[eN,k,1]))
max_w=max(max_w,abs(v[eN,k,2]))
scale = 10.0*math.sqrt(max_u**2 + max_v**2 + max_w**2)
if abs(scale) < 1.e-12:
scale = 1.0
for eN in range(vt.mesh.nElements_global):
for k in range(vt.nQuadraturePoints_element):
xtmp = vt.q['x'][eN,k,:];
vtmp = v[eN,k,:]
if abs(xtmp[0]- slice_x) < vt.mesh.h:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[1],xtmp[2],
old_div(vtmp[1],scale),old_div(vtmp[2],scale)))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title+' x-slice')
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#yslice
for eN in range(vt.mesh.nElements_global):
for k in range(vt.nQuadraturePoints_element):
xtmp = vt.q['x'][eN,k,:];
vtmp = v[eN,k,:]
if abs(xtmp[1]- slice_y) < vt.mesh.h:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[0],xtmp[2],
old_div(vtmp[0],scale),old_div(vtmp[2],scale)))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title+' y-slice')
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#zslice
for eN in range(vt.mesh.nElements_global):
for k in range(vt.nQuadraturePoints_element):
xtmp = vt.q['x'][eN,k,:];
vtmp = v[eN,k,:]
if abs(xtmp[2]- slice_z) < vt.mesh.h:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[0],xtmp[1],
old_div(vtmp[0],scale),old_div(vtmp[1],scale)))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title+' z-slice')
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#end 3d
#gnuplot
elif self.viewerType == 'matlab':
title=vt.coefficients.variableNames[ci]+'velocity-exact: t=%12.5e' % tsim
name =vt.coefficients.variableNames[ci]+'velocity'
writer = MatlabWriter(nxgrid=50,nygrid=50,nzgrid=50)
nplotted = writer.viewVectorAnalyticalFunction(self.cmdFile,vt.nSpace_global,
self.p.p.analyticalSolutionVelocity[ci].uOfXT,tsim,
vt.mesh.nodeArray,vt.mesh.elementNodesArray,
name=name,storeMeshData=not self.meshDataStructuresWritten,
figureNumber =self.windowNumber()+1,title=title)
windowNumber += nplotted
#need vtk option
#end components
#end ci
#vector components
if vt.coefficients.vectorComponents is not None:
title = 'velocity_exact : t=%12.5e' % tsim
if vt.nSpace_global == 2:
uci = vt.coefficients.vectorComponents[0]; vci = vt.coefficients.vectorComponents[1]
plotVector = (uci in self.s.viewComponents and vci in self.s.viewComponents and
self.p.analyticalSolution is not None and
uci in self.p.analyticalSolution and vci in self.p.analyticalSolution and
self.p.analyticalSolution[uci] is not None and self.p.analyticalSolution[vci] is not None)
if plotVector and self.viewerType == 'gnuplot':
for x in vt.mesh.nodeArray[:,:]:
uex = self.p.analyticalSolution[uci].uOfXT(x,tsim)
vex = self.p.analyticalSolution[vci].uOfXT(x,tsim)
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (x[0],x[1],uex,vex))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
elif vt.nSpace_global == 3:
(slice_x,slice_y,slice_z) = vt.mesh.nodeArray[old_div(vt.mesh.nodeArray.shape[0],2),:]
uci = vt.coefficients.vectorComponents[0]; vci = vt.coefficients.vectorComponents[1]
wci = vt.coefficients.vectorComponents[2]
plotVector = (uci in self.s.viewComponents and vci in self.s.viewComponents and
wci in self.s.viewComponents and self.p.analyticalSolution is not None and
self.p.analyticalSolution is not None and
uci in self.p.analyticalSolution and vci in self.p.analyticalSolution and
wci in self.p.analyticalSolution and
self.p.analyticalSolution[uci] is not None and self.p.analyticalSolution[vci] is not None and
self.p.analyticalSolution[wci] is not None)
if plotVector and self.viewerType == 'gnuplot':
for x in vt.mesh.nodeArray[:,:]:
uex = self.p.analyticalSolution[uci].uOfXT(x,tsim)
vex = self.p.analyticalSolution[vci].uOfXT(x,tsim)
wex = self.p.analyticalSolution[wci].uOfXT(x,tsim)
if x[0] == slice_x:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (x[1],x[2],vex,wex))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title+' x-slice')
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
for x in vt.mesh.nodeArray[:,:]:
uex = self.p.analyticalSolution[uci].uOfXT(x,tsim)
vex = self.p.analyticalSolution[vci].uOfXT(x,tsim)
wex = self.p.analyticalSolution[wci].uOfXT(x,tsim)
if x[1] == slice_y:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (x[0],x[2],uex,wex))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title+' y-slice')
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
for x in vt.mesh.nodeArray[:,:]:
uex = self.p.analyticalSolution[uci].uOfXT(x,tsim)
vex = self.p.analyticalSolution[vci].uOfXT(x,tsim)
wex = self.p.analyticalSolution[wci].uOfXT(x,tsim)
if x[2] == slice_z:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (x[0],x[1],uex,vex))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title+' z-slice')
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#end plot vector
#end 3d
#end vector components
if self.stepPlotCalled['exact'] == False:
self.plotWindowStart['exact'] = self.windowNumberSave
self.stepPlotCalled['exact'] = True
#end def
def stepPlotElementQuantities(self,mlvt,tsim):
"""
sort through desired quantities in quadrature dictionaries like m, dm, to plot
p --- problem definition
n --- numerics definition
mlvt --- multilevel vector transport that holds the quantities to measure
tsim --- simulation time
assumes this is the correct time to plot
and plotOffSet is set correctly
"""
global windowNumber
self.windowNumberSave = self.windowNumber()
plottedSomething = False
if self.stepPlotCalled['elementQuantities'] == True:
windowNumber = self.plotWindowStart['elementQuantities']
for quant in self.s.viewQuantities:
recType = quant.split(':')
if len(recType) > 1 and recType[0] == 'q': #found element quadrature quantity
stval = eval(recType[1])
if (stval in mlvt.levelModelList[-1].q and
len(mlvt.levelModelList[-1].q[stval].shape) == 2): #found quantity and it's a scalar
self.plotScalarElementQuantity(stval,mlvt,tsim)
plottedSomething = True
elif (stval in mlvt.levelModelList[-1].q and
len(mlvt.levelModelList[-1].q[stval].shape) == 3): #found quantity and it's a vector
self.plotVectorElementQuantity(stval,mlvt,tsim)
plottedSomething = True
elif len(recType) > 1 and recType[0] == 'ebq_global': #found global element boundary quantity
stval = eval(recType[1])
if stval in mlvt.levelModelList[-1].ebq_global:
if len(mlvt.levelModelList[-1].ebq_global[stval].shape) == 3: #found quantity and its a vector
self.plotVectorGlobalElementBoundaryQuantity(stval,mlvt,tsim)
plottedSomething = True
if self.stepPlotCalled['elementQuantities'] == False:
self.plotWindowStart['elementQuantities'] = self.windowNumberSave
if plottedSomething:
self.stepPlotCalled['elementQuantities'] = True
#
def plotScalarElementQuantity(self,ckey,mlvt,tsim):
"""plotting routine to look at scalar quantity stored in element quad dictionary q
Parameters
-----------
ckey : what should be plotted
mlvt : multilevel vector transport that holds the quantities to measure
tsim : simulation time
assumes this is the correct time to plot
and plotOffSet is set correctly
"""
p = self.p; n = self.n
from proteusGraphical import vtkViewers
vt = mlvt.levelModelList[-1]
title = """q[%s]""" % (ckey,)
assert ckey in vt.q
if self.viewerType == 'gnuplot':
if vt.nSpace_global == 1:
npoints = vt.q['x'].shape[0]*vt.q['x'].shape[1]
xandu = [(vt.q['x'].flat[i*3+0],vt.q[ckey].flat[i]) for i in range(npoints)]
xandu.sort()
for xu in xandu:
self.datFile.write("%12.5e %12.5e \n" % (xu[0],xu[1]))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with linespoints title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
elif vt.nSpace_global == 2:
for eN in range(vt.q['x'].shape[0]):
for k in range(vt.q['x'].shape[1]):
self.datFile.write("%12.5e %12.5e %12.5e \n" % (vt.q['x'][eN,k,0],vt.q['x'][eN,k,1],vt.q[ckey][eN,k]))
self.datFile.write("\n \n")
ggrid = 50;
cmd = "set dgrid3d %d,%d,16; set contour base; set term x11 %i; splot \'%s\' index %i with lines title \"%s\" \n" % (self.dgridx,
self.dgridy,
self.windowNumber(),
self.datFilename,
self.plotNumber(),
title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#end 2d
elif vt.nSpace_global == 3:
(slice_x,slice_y,slice_z) = vt.mesh.nodeArray[old_div(vt.mesh.nodeArray.shape[0],2),:]
for eN in range(vt.q['x'].shape[0]):
for k in range(vt.q['x'].shape[1]):
if vt.q['x'][eN,k,0] == slice_x:
self.datFile.write("%12.5e %12.5e %12.5e \n" % (vt.q['x'][eN,k,1],
vt.q['x'][eN,k,2],vt.q[ckey][eN,k]))
self.datFile.write("\n \n")
cmd = "set dgrid3d; set contour base; set term x11 %i; splot \'%s\' index %i with lines title \"%s-x-slice\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#
for eN in range(vt.q['x'].shape[0]):
for k in range(vt.q['x'].shape[1]):
if vt.q['x'][eN,k,1] == slice_y:
self.datFile.write("%12.5e %12.5e %12.5e \n" % (vt.q['x'][eN,k,0],
vt.q['x'][eN,k,2],vt.q[ckey][eN,k]))
self.datFile.write("\n \n")
cmd = "set dgrid3d; set contour base; set term x11 %i; splot \'%s\' index %i with lines title \"%s-y-slice\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#
for eN in range(vt.q['x'].shape[0]):
for k in range(vt.q['x'].shape[1]):
if vt.q['x'][eN,k,2] == slice_z:
self.datFile.write("%12.5e %12.5e %12.5e \n" % (vt.q['x'][eN,k,0],
vt.q['x'][eN,k,1],vt.q[ckey][eN,k]))
self.datFile.write("\n \n")
cmd = "set dgrid3d; set contour base; set term x11 %i; splot \'%s\' index %i with lines title \"%s-z-slice\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#3d
#gnuplot
elif self.viewerType == 'matlab':
name = ckey[0];
for i in range(len(ckey)-1):
name += "_%s" % ckey[1+i]
title = "%s t = %g " % (name,tsim)
#does not handle window number counting internally
writer = MatlabWriter(nxgrid=50,nygrid=50,nzgrid=50)
nplotted = writer.viewScalarPointData(self.cmdFile,vt.nSpace_global,vt.q,ckey,name=name,
storeMeshData=not self.meshDataStructuresWritten,
useLocal = True,
figureNumber =self.windowNumber()+1,title=title)
windowNumber += nplotted
elif self.viewerType == 'vtk':
title = """q[%s]""" % (ckey,)
if vt.nSpace_global == 1:
npoints = vt.q['x'].shape[0]*vt.q['x'].shape[1]
xvals = numpy.array([vt.q['x'].flat[i*3+0] for i in range(npoints)])
yvals = numpy.array([vt.q[ckey].flat[i] for i in range(npoints)])
# yvals = [vt.q[ckey].flat[:]
vtkViewers.viewScalar_1D(xvals,yvals,"x",ckey[0],title,self.windowNumber(),
Pause=self.s.viewerPause,sortPoints=True)
newPlot()
newWindow()
elif vt.nSpace_global == 2:
vtkViewers.viewScalar_pointSet_2D(vt.q['x'], vt.q[ckey], title, self.windowNumber(), True, self.s.viewerPause, False)
newPlot()
newWindow()
elif vt.nSpace_global == 3:
vtkViewers.viewScalar_pointSet_3D(vt.q['x'], vt.q[ckey], title, self.windowNumber(), self.s.viewerPause, False)
newPlot()
newWindow()
#def
def plotVectorGlobalElementBoundaryQuantity(self,ckey,mlvt,tsim):
"""plotting routine to look at vector quantity stored in global elementBoundary quad dictionary ebq_global
Parameters
-----------
ckey : what should be plotted
mlvt : multilevel vector transport that holds the quantities to measure
tsim : simulation time
assumes this is the correct time to plot
and plotOffSet is set correctly
"""
from proteusGraphical import vtkViewers
p = self.p; n = self.n
vt = mlvt.levelModelList[-1]
title = """ebq_global[%s] t= %s""" % (ckey,tsim)
assert ckey in vt.ebq_global
if self.viewerType == 'gnuplot':
if vt.nSpace_global == 1:
max_u=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[0],2).flat))
L = max(vt.mesh.nodeArray[:,0])
scale = 10.*max_u/L
if abs(scale) < 1.0e-12:
scale = 1.0
npoints = vt.ebq_global['x'].shape[0]*vt.ebq_global['x'].shape[1]
xandu = [(vt.ebq_global['x'].flat[i*3+0],vt.ebq_global[ckey].flat[i]) for i in range(npoints)]
xandu.sort()
for xu in xandu:
self.datFile.write("%12.5e %12.5e \n" % (xu[0],old_div(xu[1],scale)))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with linespoints title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title+" max= "+repr(max_u))
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
elif vt.nSpace_global == 2:
max_u=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[0],2).flat))
max_v=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[1],2).flat))
L = min((max(vt.mesh.nodeArray[:,0]),max(vt.mesh.nodeArray[:,1])))
scale =10.0*max((max_u,max_v,1.0e-16))/L
if abs(scale) < 1.e-12:
scale = 1.0
for ebN in range(vt.ebq_global[ckey].shape[0]):
for k in range(vt.ebq_global[ckey].shape[1]):
xtmp =vt.ebq_global['x'][ebN,k,:]; vtmp = vt.ebq_global[ckey][ebN,k,:]
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[0],xtmp[1],
old_div(vtmp[0],scale),old_div(vtmp[1],scale)))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title+" max=(%s,%s) " % (max_u,max_v))
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#mwf debug
#raw_input('simTools coef press return to continue\n')
#end 2d
elif vt.nSpace_global == 3:
(slice_x,slice_y,slice_z) = vt.mesh.nodeArray[old_div(vt.mesh.nodeArray.shape[0],2),:]
max_u=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[0],2).flat))
max_v=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[1],2).flat))
max_w=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[2],2).flat))
L = min((max(vt.mesh.nodeArray[:,0]),max(vt.mesh.nodeArray[:,1]),
max(vt.mesh.nodeArray[:,1])))
scale = 10.0*max((max_u,max_v,max_w,1.e-16))/L
if abs(scale) < 1.e-12:
scale = 1.0
#x slice
for ebN in range(vt.ebq_global[ckey].shape[0]):
for k in range(vt.ebq_global[ckey].shape[1]):
xtmp = vt.ebq_global['x'][ebN,k,:]; vtmp = vt.ebq_global[ckey][ebN,k,:]
if abs(xtmp[0]-slice_x) < vt.mesh.h:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[1],xtmp[2],
old_div(vtmp[1],scale),old_div(vtmp[2],scale)))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title+" max=(%s,%s,%s) " % (max_u,max_v,max_w)+" : x-slice")
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#y slice
for ebN in range(vt.ebq_global[ckey].shape[0]):
for k in range(vt.ebq_global[ckey].shape[1]):
xtmp = vt.ebq_global['x'][ebN,k,:]; vtmp = vt.ebq_global[ckey][ebN,k,:]
if abs(xtmp[0]-slice_y) < vt.mesh.h:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[1],xtmp[2],
old_div(vtmp[1],scale),old_div(vtmp[2],scale)))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title+" max=(%s,%s,%s) " % (max_u,max_v,max_w)+" : y-slice")
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#z slice
for ebN in range(vt.ebq_global[ckey].shape[0]):
for k in range(vt.ebq_global[ckey].shape[1]):
xtmp = vt.ebq_global['x'][ebN,k,:]; vtmp = vt.ebq_global[ckey][ebN,k,:]
if abs(xtmp[0]-slice_z) < vt.mesh.h:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[1],xtmp[2],
old_div(vtmp[1],scale),old_div(vtmp[2],scale)))
self.datFile.write("\n \n")
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
title+" max=(%s,%s,%s) " % (max_u,max_v,max_w)+" : z-slice")
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#3d
#gnuplot
elif self.viewerType == 'vtk':
title = """ebq_global[%s]""" % (ckey,)
if vt.nSpace_global == 1:
max_u=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[0],2).flat))
L = max(vt.mesh.nodeArray[:,0])
scale = 10.*max_u/L
if abs(scale) < 1.0e-12:
scale = 1.0
npoints = vt.ebq_global['x'].shape[0]*vt.ebq_global['x'].shape[1]
xvals = [vt.ebq_global['x'].flat[i*3+0] for i in range(npoints)]
yvals = [old_div(vt.ebq_global[ckey].flat[i],scale) for i in range(npoints)]
vtkViewers.viewScalar_1D(xvals,yvals,"x",ckey[0],title,self.windowNumber(),
Pause=self.s.viewerPause,sortPoints=True)
newPlot()
newWindow()
elif vt.nSpace_global == 2:
max_u=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[0],2).flat))
max_v=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[1],2).flat))
L = min((max(vt.mesh.nodeArray[:,0]),max(vt.mesh.nodeArray[:,1])))
scale =10.0*max((max_u,max_v,1.0e-16))/L
if abs(scale) < 1.e-12:
scale = 1.0
npoints = vt.ebq_global['x'].shape[0]*vt.ebq_global['x'].shape[1]
# x = [vt.ebq_global['x'].flat[i*3+0] for i in range(npoints)]
# y = [vt.ebq_global['x'].flat[i*3+1] for i in range(npoints)]
# z = [vt.ebq_global['x'].flat[i*3+2] for i in range(npoints)]
xvals= [old_div(vt.ebq_global[ckey].flat[i*2+0],scale) for i in range(npoints)]
yvals= [old_div(vt.ebq_global[ckey].flat[i*2+1],scale) for i in range(npoints)]
nodes = vt.ebq_global['x'].flat[:]
vtkViewers.viewVector_pointSet_2D(nodes,xvals,yvals,None,title,self.windowNumber(),
arrows=True,streamlines=False,
Pause=self.s.viewerPause)
# vtkDisplay2DVectorMeshGeneric(x,y,z,xvals,yvals,None,title,self.windowNumber(),
# arrows=True,streamlines=False,
# Pause=self.flags['plotOptions']['vtk']['pause'])
newPlot()
newWindow()
elif vt.nSpace_global == 3:
max_u=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[0],2).flat))
max_v=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[1],2).flat))
max_w=max(numpy.absolute(numpy.take(vt.ebq_global[ckey],[2],2).flat))
L = min((max(vt.mesh.nodeArray[:,0]),max(vt.mesh.nodeArray[:,1]),max(vt.mesh.nodeArray[:,2])))
scale =10.0*max((max_u,max_v,max_w,1.0e-16))/L
if abs(scale) < 1.e-12:
scale = 1.0
npoints = vt.ebq_global['x'].shape[0]*vt.ebq_global['x'].shape[1]
# x = [vt.ebq_global['x'].flat[i*3+0] for i in range(npoints)]
# y = [vt.ebq_global['x'].flat[i*3+1] for i in range(npoints)]
# z = [vt.ebq_global['x'].flat[i*3+2] for i in range(npoints)]
nodes = vt.ebq_global['x'].flat[:]
xvals= [old_div(vt.ebq_global[ckey].flat[i*3+0],scale) for i in range(npoints)]
yvals= [old_div(vt.ebq_global[ckey].flat[i*3+1],scale) for i in range(npoints)]
zvals= [old_div(vt.ebq_global[ckey].flat[i*3+2],scale) for i in range(npoints)]
vtkViewers.viewVector_pointSet_3D(nodes,xvals,yvals,zvals,title,self.windowNumber(),
arrows=True,streamlines=False,
Pause=self.s.viewerPause)
# vtkDisplay3DVectorMeshGeneric(x,y,z,xvals,yvals,zvals,title,self.windowNumber(),
# arrows=True,streamlines=False,
# Pause=self.flags['plotOptions']['vtk']['pause'])
newPlot()
newWindow()
#def
def plotVectorElementQuantity(self,ckey,mlvt,tsim,nVectorPlotPointsPerElement=1):
"""
plotting routine to look at vector quantity stored in global element quad dictionary q
input :
ckey --- what should be plotted
p --- problem definition
n --- numerics definition
mlvt --- multilevel vector transport that holds the quantities to measure
tsim --- simulation time
assumes this is the correct time to plot
and plotOffSet is set correctly
"""
from proteusGraphical import vtkViewers
p = self.p; n = self.n
vt = mlvt.levelModelList[-1]
title = """q[%s] t= %s""" % (ckey,tsim)
assert ckey in vt.q
if self.viewerType == 'gnuplot':
if vt.nSpace_global == 1:
max_u=max(numpy.absolute(numpy.take(vt.q[ckey],[0],2).flat))
L = max(vt.mesh.nodeArray[:,0])
scale = 10.*max_u/L
if abs(scale) < 1.0e-12:
scale = 1.0
npoints = vt.q['x'].shape[0]*vt.q['x'].shape[1]
xandu = [(vt.q['x'].flat[i*3+0],vt.q[ckey].flat[i]) for i in range(npoints)]
xandu.sort()
for xu in xandu:
self.datFile.write("%12.5e %12.5e \n" % (xu[0],old_div(xu[1],scale)))
self.datFile.write("\n \n")
ptitle = title+" max= %g" % max_u
cmd = "set term x11 %i; plot \'%s\' index %i with linespoints title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
ptitle)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
elif vt.nSpace_global == 2:
max_u=max(numpy.absolute(numpy.take(vt.q[ckey],[0],2).flat))
max_v=max(numpy.absolute(numpy.take(vt.q[ckey],[1],2).flat))
L = min((max(vt.mesh.nodeArray[:,0]),max(vt.mesh.nodeArray[:,1])))
scale =10.0*max((max_u,max_v,1.0e-16))/L
if abs(scale) < 1.e-12:
scale = 1.0
for eN in range(vt.mesh.nElements_global):
#mwf what about just 1 point per element for k in range(vt.nQuadraturePoints_element):
for k in range(min(nVectorPlotPointsPerElement,vt.nQuadraturePoints_element)):
xtmp = vt.q['x'][eN,k,:]; vtmp = vt.q[ckey][eN,k,:]
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[0],xtmp[1],
old_div(vtmp[0],scale),old_div(vtmp[1],scale)))
self.datFile.write("\n \n")
ptitle = title + "max=(%s,%s)" % (max_u,max_v)
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
ptitle)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
elif vt.nSpace_global == 3:
(slice_x,slice_y,slice_z) = vt.mesh.nodeArray[old_div(vt.mesh.nodeArray.shape[0],2),:]
max_u=max(numpy.absolute(numpy.take(vt.q[ckey],[0],2).flat))
max_v=max(numpy.absolute(numpy.take(vt.q[ckey],[1],2).flat))
max_w=max(numpy.absolute(numpy.take(vt.q[ckey],[2],2).flat))
L = min((max(vt.mesh.nodeArray[:,0]),max(vt.mesh.nodeArray[:,1]),
max(vt.mesh.nodeArray[:,1])))
scale = 10.0*max((max_u,max_v,max_w,1.e-16))/L
if abs(scale) < 1.e-12:
scale = 1.0
for eN in range(vt.mesh.nElements_global):
#mwf now try one point per element for k in range(vt.nQuadraturePoints_element):
for k in range(min(nVectorPlotPointsPerElement,vt.nQuadraturePoints_element)):
xtmp = vt.q['x'][eN,k,:]; vtmp = vt.q[ckey][eN,k,:]
if abs(xtmp[0]-slice_x) < vt.mesh.h:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[1],xtmp[2],
old_div(vtmp[1],scale),old_div(vtmp[2],scale)))
self.datFile.write("\n \n")
ptitle = title + " max=(%s,%s,%s) " % (max_u,max_v,max_w)+" : x-slice"
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
ptitle)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#y slice
for eN in range(vt.mesh.nElements_global):
#mwf now try one point per element for k in range(vt.nQuadraturePoints_element):
for k in range(min(nVectorPlotPointsPerElement,vt.nQuadraturePoints_element)):
xtmp = vt.q['x'][eN,k,:]; vtmp = vt.q[ckey][eN,k,:]
if abs(xtmp[1]-slice_y) < vt.mesh.h:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[0],xtmp[2],
old_div(vtmp[0],scale),old_div(vtmp[2],scale)))
self.datFile.write("\n \n")
ptitle = title + " max=(%s,%s,%s) " % (max_u,max_v,max_w)+" : y-slice"
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
ptitle)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#z slice
for eN in range(vt.mesh.nElements_global):
#mwf now try one point per element for k in range(vt.nQuadraturePoints_element):
for k in range(min(nVectorPlotPointsPerElement,vt.nQuadraturePoints_element)):
xtmp = vt.q['x'][eN,k,:]; vtmp = vt.q[ckey][eN,k,:]
if abs(xtmp[2]-slice_z) < vt.mesh.h:
self.datFile.write("%12.5e %12.5e %12.5e %12.5e \n" % (xtmp[0],xtmp[1],
old_div(vtmp[0],scale),old_div(vtmp[1],scale)))
self.datFile.write("\n \n")
ptitle = title + " max=(%s,%s,%s) " % (max_u,max_v,max_w)+" : z-slice"
cmd = "set term x11 %i; plot \'%s\' index %i with vectors title \"%s\" \n" % (self.windowNumber(),
self.datFilename,
self.plotNumber(),
ptitle)
self.cmdFile.write(cmd)
self.viewerPipe.write(cmd)
newPlot()
newWindow()
#end 3d
#gnuplot
elif self.viewerType == 'matlab':
name = ckey[0];
for i in range(len(ckey)-1):
name += "_%s" % ckey[1+i]
title = "%s t = %g " % (name,tsim)
#does not handle window number counting internally
writer = MatlabWriter(nxgrid=50,nygrid=50,nzgrid=50)
nplotted = writer.viewVectorPointData(self.cmdFile,vt.nSpace_global,vt.q,ckey,name=name,
storeMeshData=not self.meshDataStructuresWritten,
useLocal=False,#not implemented yed
figureNumber =self.windowNumber()+1,title=title)
windowNumber += nplotted
elif self.viewerType == 'vtk':
title = """q[%s]""" % (ckey,)
if vt.nSpace_global == 1:
max_u=max(numpy.absolute(numpy.take(vt.q[ckey],[0],2).flat))
L = max(vt.mesh.nodeArray[:,0])
scale = 1.0
if abs(scale) < 1.0e-12:
scale = 1.0
npoints = vt.q['x'].shape[0]*vt.q['x'].shape[1]
xvals = [vt.q['x'].flat[i*3+0] for i in range(npoints)]
yvals = [old_div(vt.q[ckey].flat[i],scale) for i in range(npoints)]
vtkViewers.viewVector_1D(xvals,yvals,"x",ckey[0],title,self.windowNumber(),
Pause=self.s.viewerPause)
newPlot()
newWindow()
#1d
elif vt.nSpace_global == 2:
vtkViewers.viewVector_pointSet_2D(vt.q['x'],vt.q[ckey],title)
newPlot()
newWindow()
elif vt.nSpace_global == 3:
vtkViewers.viewVector_pointSet_3D(vt.q['x'],vt.q[ckey],title,self.windowNumber(),
Pause=self.s.viewerPause)
newPlot()
newWindow()
#def
class MatlabWriter(object):
"""
collect functionality for generating visualation data and commands in matlab
TODO:
C0P2 in 3d
DG monomials
"""
def __init__(self,nxgrid=50,nygrid=50,nzgrid=10,verbose=0):
self.verbose = 0
self.ngrid=[nxgrid,nygrid,nzgrid] #default grid size if converting to regular mesh
def storePointMeshData(self,cmdFile,x,name):
"""
write out spatial locations for generic point data
"""
cmdFile.write("%s_x_q = [ ... \n" % name)
for eN in range(x.shape[0]):
for k in range(x.shape[1]):
cmdFile.write("%g %g %g \n" % (x[eN,k,0],x[eN,k,1],x[eN,k,2]))
cmdFile.write("];")
#
def viewScalarPointData(self,cmdFile,nSpace,q,ckey,name=None,
storeMeshData=True,useLocal=True,
figureNumber=1,title=None):
"""
wrapper for visualling element quadrature points, can try to use a local representation
or build a global one depending on useLocal.
If useLocal and nPoints_elemnet < nSpace+1 calls global routine
"""
if not useLocal:
return self.viewGlobalScalarPointData(cmdFile,nSpace,q,ckey,name=name,
storeMeshData=storeMeshData,
figureNumber=figureNumber,title=title)
nPoints_element = q['x'].shape[1]
if nPoints_element <= nSpace:
print("""
Warning! viewScalarPointData nPoints_element=%s < %s too small for useLocal, using global interp""" % (nPoints_element,
nSpace+1))
return self.viewGlobalScalarPointData(cmdFile,nSpace,q,ckey,name=name,
storeMeshData=storeMeshData,
figureNumber=figureNumber,title=title)
return self.viewLocalScalarPointData(cmdFile,nSpace,q,ckey,name=name,
storeMeshData=storeMeshData,
figureNumber=figureNumber,title=title)
def viewVectorPointData(self,cmdFile,nSpace,q,ckey,name=None,
storeMeshData=True,useLocal=True,
figureNumber=1,title=None):
"""
wrapper for visualling element quadrature points, can try to use a local representation
or build a global one depending on useLocal.
TODO: implement local view for vectors
If useLocal and nPoints_elemnet < nSpace+1 calls global routine
"""
if not useLocal:
return self.viewGlobalVectorPointData(cmdFile,nSpace,q,ckey,name=name,
storeMeshData=storeMeshData,
figureNumber=figureNumber,title=title)
else:
print("viewLocalVectorPointData not implemented, using global!")
return self.viewGlobalVectorPointData(cmdFile,nSpace,q,ckey,name=name,
storeMeshData=storeMeshData,
figureNumber=figureNumber,title=title)
# nPoints_element = q['x'].shape[1]
# if nPoints_element <= nSpace:
# print """
# Warning! viewScalarPointData nPoints_element=%s < %s too small for useLocal, using global interp""" % (nPoints_element,
# nSpace+1)
# return self.viewGlobalScalarPointData(cmdFile,nSpace,q,ckey,name=name,
# storeMeshData=storeMeshData,
# figureNumber=figureNumber,title=title)
# return self.viewLocalScalarPointData(cmdFile,nSpace,q,ckey,name=name,
# storeMeshData=storeMeshData,
# figureNumber=figureNumber,title=title)
def viewGlobalScalarPointData(self,cmdFile,nSpace,q,ckey,name=None,
storeMeshData=True,figureNumber=1,title=None):
"""
input scalar variable and coordinates stored in dictionary
q['x'], q[ckey]
respectively, generate global continuous interpolant
should work for q, ebq_global, and ebqe quadrature dictionaries
uses delaunay triangulation in 2d and 3d
scalar data is stored in
name_q
if storeMeshData = True, writes out
name_x_q -- point data
tri_name_q -- Delaunay representation (2d,3d)
returns number of figures actually plotted
"""
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
[x_tmp,i_tmp] = sort(%s_x_q(:,1)); %s_x_q = %s_x_q(i_tmp); %s_q = %s_q(i_tmp);
"""
cmd1dView = """
figure(%i) ; plot(%s_x_q(:,1),%s_q) ; title('%s');
"""
#2d
cmd2dData = """
tri_%s_q = delaunay(%s_x_q(:,1),%s_x_q(:,2));
"""
cmd2dView = """
figure(%i) ; trimesh(tri_%s_q,%s_x_q(:,1),%s_x_q(:,2),%s_q); title('%s');
%%also could be used
%%trisurf(tri_name_q,name_x_q(:,1),name_x_q(:,2),name_q);
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x_q(:,1)) max(%s_x_q(:,1)) ; min(%s_x_q(:,2)) max(%s_x_q(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_qxg,%s_qyg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%s_qg = griddata(%s_x_q(:,1),%s_x_q(:,2),%s_q,%s_qxg,%s_qyg);
"""
#3d
cmd3dData = """
tri_%s_q = delaunay3(%s_x_q(:,1),%s_x_q(:,2),%s_x_q(:,3));
"""
cmd3dView = """
%%Warning not very good right now
%%figure(%i) ; tetramesh(tri_%s_q,%s_x_q); title('%s');
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x_q(:,1)) max(%s_x_q(:,1)) ; min(%s_x_q(:,2)) max(%s_x_q(:,2)) ; min(%s_x_q(:,3)) max(%s_x_q(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_qxg,%s_qyg,%s_qzg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%s_qg = griddata3(%s_x_q(:,1),%s_x_q(:,2),%s_x_q(:,3),%s_q,%s_qxg,%s_qyg,%s_qzg);
"""
###
if name is None:
name = ckey[0];
for i in range(len(ckey)-1):
name += "_%s" % ckey[1+i]
if title is None:
title = name
assert ckey in q, " ckey = %s missing from q " % ckey
assert len(q[ckey].shape) == 2, " q[%s].shape= %s should be ( , ) " % (ckey,q[ckey].shape)
if storeMeshData:
self.storePointMeshData(cmdFile,q['x'],name)
#cmdFile.write("%s_x_q = [ ... \n" % name)
#for eN in range(q['x'].shape[0]):
# for k in range(q['x'].shape[1]):
# cmdFile.write("%g %g %g \n" % (q['x'][eN,k,0],q['x'][eN,k,1],q['x'][eN,k,2]))
#cmdFile.write("];")
#
cmdFile.write("%s_q = [ ... \n" % name)
for eN in range(q[ckey].shape[0]): #ebq_global or ebqe would work
for k in range(q[ckey].shape[1]):
cmdFile.write("%g \n" % q[ckey][eN,k])
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
cmd = cmd2dData % (name,name,name)
cmdFile.write(cmd)
cmd = cmd2dView % (figureNumber,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
cmd = cmd3dData % (name,name,name,name)
cmdFile.write(cmd)
cmd = cmd3dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 0 #tetramesh no good right now
#
return nplotted
def viewGlobalVectorPointData(self,cmdFile,nSpace,q,ckey,name=None,
storeMeshData=True,figureNumber=1,title=None):
"""
input vector variable and coordinates stored in dictionary
q['x'], q[ckey]
respectively, generate global continuous interpolant
should work for q, ebq_global, and ebqe quadrature dictionaries
uses delaunay triangulation in 2d and 3d
vector data is stored in
name_q
if storeMeshData = True, writes out
name_x_q -- point data
tri_name_q -- Delaunay representation (2d,3d)
returns number of figures actually generated
"""
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
[x_tmp,i_tmp] = sort(%s_x_q(:,1)); %s_x_q = %s_x_q(i_tmp); %s_q = %s_q(i_tmp);
"""
cmd1dView = """
figure(%i) ; plot(%s_x_q(:,1),%s_q) ; title('%s');
"""
#2d
cmd2dData = """
tri_%s_q = delaunay(%s_x_q(:,1),%s_x_q(:,2));
"""
cmd2dView = """
%s_q_mag = (%s_q(:,1).^2 + %s_q(:,2).^2).^(0.5);
figure(%i) ; quiver(%s_x_q(:,1),%s_x_q(:,2),%s_q(:,1),%s_q(:,2));title('%s');
%%could also use
%% trimesh(tri_name_q,name_x_q(:,1),name_x_q(:,2),name_q_mag);
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x_q(:,1)) max(%s_x_q(:,1)) ; min(%s_x_q(:,2)) max(%s_x_q(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_qxg,%s_qyg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%s_qg_x = griddata(%s_x_q(:,1),%s_x_q(:,2),%s_q(:,1),%s_qxg,%s_qyg);
%s_qg_y = griddata(%s_x_q(:,1),%s_x_q(:,2),%s_q(:,2),%s_qxg,%s_qyg);
"""
#3d
cmd3dData = """
tri_%s_q = delaunay3(%s_x_q(:,1),%s_x_q(:,2),%s_x_q(:,3));
"""
cmd3dView = """
%s_q_mag = (%s_q(:,1).^2 + %s_q(:,2).^2 + %s_q(:,3).^2).^(0.5);
figure(%i) ; quiver3(%s_x_q(:,1),%s_x_q(:,2),%s_x_q(:,3),%s_q(:,1),%s_q(:,2),%s_q(:,3));title('%s');
%%Warning not very good right now
%% tetramesh(tri_name_q,name_x_q);
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x_q(:,1)) max(%s_x_q(:,1)) ; min(%s_x_q(:,2)) max(%s_x_q(:,2)) ; min(%s_x_q(:,3)) max(%s_x_q(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_qxg,%s_qyg,%s_qzg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%s_qg_x = griddata3(%s_x_q(:,1),%s_x_q(:,2),%s_x_q(:,3),%s_q(:,1),%s_qxg,%s_qyg,%s_qzg);
%s_qg_y = griddata3(%s_x_q(:,1),%s_x_q(:,2),%s_x_q(:,3),%s_q(:,2),%s_qxg,%s_qyg,%s_qzg);
%s_qg_z = griddata3(%s_x_q(:,1),%s_x_q(:,2),%s_x_q(:,3),%s_q(:,3),%s_qxg,%s_qyg,%s_qzg);
"""
###
if name is None:
name = ckey[0];
for i in range(len(ckey)-1):
name += "_%s" % ckey[1+i]
if title is None:
title = name
assert ckey in q, " ckey = %s missing from q " % ckey
assert len(q[ckey].shape) == 3, " q[%s].shape= %s should be ( , , ) " % (ckey,q[ckey].shape)
if storeMeshData:
self.storePointMeshData(cmdFile,q['x'],name)
#
cmdFile.write("%s_q = [ ... \n" % name)
for eN in range(q[ckey].shape[0]): #ebq_global or ebqe would work
for k in range(q[ckey].shape[1]):
for I in range(q[ckey].shape[2]):
cmdFile.write(" %g " % q[ckey][eN,k,I])
cmdFile.write(" ; \n ")
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
cmd = cmd2dData % (name,name,name)
cmdFile.write(cmd)
cmd = cmd2dView % (name,name,name,
figureNumber,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
cmd = cmd3dData % (name,name,name,name)
cmdFile.write(cmd)
cmd = cmd3dView % (name,name,name,name,
figureNumber,name,name,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name,
name,name,name,name,name,name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
#
return nplotted
def viewLocalScalarPointData(self,cmdFile,nSpace,q,ckey,name=None,
storeMeshData=True,figureNumber=1,title=None):
"""
input scalar variable and coordinates stored in dictionary
q['x'], q[ckey]
respectively, generate local interpolant that is element-wise continuous
should work for q, ebq_global, and ebqe quadrature dictionaries
uses delaunay triangulation in 2d and 3d on each element (stored in cell array)
scalar data is stored in
name_q
if storeMeshData = True, writes out
name_x_q -- point data
tri_name_q -- Delaunay representation (2d,3d)
returns number of figures actually plotted
"""
#1d
cmd1dData = """
nElements_global = %i; nPoints_element = %i;
tri_%s_q = [];
for eN = 1:nElements_global
[x_tmp,i_tmp] = sort(%s_x_q(nPoints_element*(eN-1)+1:nPoints_element*eN,1));
tmp = [];
for j = 1:nPoints_element-1
tmp = [tmp ; i_tmp(j) i_tmp(j+1)];
end
tri_%s_q = [tri_%s_q ; nPoints_element*(eN-1) + tmp];
end
%s_q_loc = %s_x_q; %s_q_loc(:,2) = %s_q;
"""
cmd1dView = """
figure(%i) ; patch('vertices',%s_q_loc,'faces',tri_%s_q,'FaceColor','none','EdgeColor','black'); title('%s');
"""
#2d
cmd2dData = """
nElements_global = %i; nPoints_element = %i;
tri_%s_q = [];
for eN = 1:nElements_global
tmp = delaunay(%s_x_q(nPoints_element*(eN-1)+1:nPoints_element*eN,1),...
%s_x_q(nPoints_element*(eN-1)+1:nPoints_element*eN,2));
tri_%s_q = [tri_%s_q ; nPoints_element*(eN-1)+tmp];
end
%s_q_loc = %s_x_q; %s_q_loc(:,3) = %s_q;
"""
cmd2dView = """
figure(%i) ; patch('vertices',%s_q_loc,'faces',tri_%s_q,'FaceVertexCData',%s_q,'FaceColor','interp','EdgeColor','none'); title('%s');
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x_q(:,1)) max(%s_x_q(:,1)) ; min(%s_x_q(:,2)) max(%s_x_q(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_qxg,%s_qyg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%s_qg = griddata(%s_x_q(:,1),%s_x_q(:,2),%s_q,%s_qxg,%s_qyg);
"""
#3d
cmd3dData = """
nElements_global = %i; nPoints_element = %i;
tri_%s_q = [];
for eN = 1:nElements_global
tmp = delaunay3(%s_x_q(nPoints_element*(eN-1)+1:nPoints_element*eN,1),...
%s_x_q(nPoints_element*(eN-1)+1:nPoints_element*eN,2),...
%s_x_q(nPoints_element*(eN-1)+1:nPoints_element*eN,3));
tri_%s_q = [tri_%s_q ; nPoints_element*(eN-1)+tmp];
end
%s_q_loc = %s_x_q; %s_q_loc(:,3) = %s_q;
"""
cmd3dView = """
%%good luck
figure(%i); patch('vertices',%s_x_q,'faces',tri_%s_q,'FaceVertexCData',%s_q,'FaceColor','none','EdgeColor','interp'); title('%s')
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x_q(:,1)) max(%s_x_q(:,1)) ; min(%s_x_q(:,2)) max(%s_x_q(:,2)) ; min(%s_x_q(:,3)) max(%s_x_q(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_qxg,%s_qyg,%s_qzg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%s_qg = griddata3(%s_x_q(:,1),%s_x_q(:,2),%s_x_q(:,3),%s_q,%s_qxg,%s_qyg,%s_qzg);
"""
nplotted = 0
if name is None:
name = ckey[0];
for i in range(len(ckey)-1):
name += "_%s" % ckey[1+i]
if title is None:
title = name
assert ckey in q, " ckey = %s missing from q " % ckey
assert len(q[ckey].shape) == 2, " q[%s].shape= %s should be ( , ) " % (ckey,q[ckey].shape)
nElements_global = q['x'].shape[0]; nPoints_element = q['x'].shape[1];
if storeMeshData:
self.storePointMeshData(cmdFile,q['x'],name)
cmdFile.write("%s_q = [ ... \n" % name)
for eN in range(q[ckey].shape[0]): #ebq_global or ebqe would work
for k in range(q[ckey].shape[1]):
cmdFile.write("%g \n" % q[ckey][eN,k])
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (nElements_global,nPoints_element,
name,
name,
name,name,
name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
cmd = cmd2dData % (nElements_global,nPoints_element,
name,
name,name,
name,name,
name,name,name,name)
cmdFile.write(cmd)
cmd = cmd2dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
cmd = cmd3dData % (nElements_global,nPoints_element,
name,
name,name,name,
name,name,
name,name,name,name)
cmdFile.write(cmd)
cmd = cmd3dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
return nplotted
#
def viewScalarAnalyticalFunction(self,cmdFile,nSpace,f,t,x,elementNodesConnectivity=None,
name='exact',storeMeshData=True,figureNumber=1,title=None):
"""
input scalar analytical function f(x,t) and array of points
respectively, generate global continuous interpolant
uses delaunay triangulation in 2d and 3d if element - node triangulation not already defined
scalar data is stored in
name_ex
if storeMeshData = True, writes out
name_x_ex -- point data
tri_name_ex -- element-node representation (2d,3d)
returns number of figures actually plotted
"""
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
[x_tmp,i_tmp] = sort(%s_x_ex(:,1)); %s_x_ex = %s_x_ex(i_tmp); %s_ex = %s_ex(i_tmp);
"""
cmd1dView = """
figure(%i) ; plot(%s_x_ex(:,1),%s_ex) ; title('%s');
"""
#2d
#if does not have element-node connectivity already
cmd2dData = """
tri_%s_ex = delaunay(%s_x_ex(:,1),%s_x_ex(:,2));
"""
cmd2dView = """
figure(%i) ; trimesh(tri_%s_ex,%s_x_ex(:,1),%s_x_ex(:,2),%s_ex); title('%s');
%%also could be used
%%trisurf(tri_name_ex,name_x_ex(:,1),name_x_ex(:,2),name_ex);
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x_ex(:,1)) max(%s_x_ex(:,1)) ; min(%s_x_ex(:,2)) max(%s_x_ex(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_qxg,%s_qyg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%s_qg = griddata(%s_x_ex(:,1),%s_x_ex(:,2),%s_ex,%s_qxg,%s_qyg);
"""
#3d
#if does not have element-node connectivity already
cmd3dData = """
tri_%s_ex = delaunay3(%s_x_ex(:,1),%s_x_ex(:,2),%s_x_ex(:,3));
"""
cmd3dView = """
%%Warning not very good right now
%%figure(%i) ; tetramesh(tri_%s_ex,%s_x_ex); title('%s');
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x_ex(:,1)) max(%s_x_ex(:,1)) ; min(%s_x_ex(:,2)) max(%s_x_ex(:,2)) ; min(%s_x_ex(:,3)) max(%s_x_ex(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_qxg,%s_qyg,%s_qzg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%s_qg = griddata3(%s_x_ex(:,1),%s_x_ex(:,2),%s_x_ex(:,3),%s_ex,%s_qxg,%s_qyg,%s_qzg);
"""
###
if title is None:
title = name
nPoints = 1
for i in range(len(x.shape)-1):
nPoints *= x.shape[i]
if storeMeshData:
cmdFile.write("%s_x_ex = [ ... \n" % name)
for i in range(nPoints):
cmdFile.write("%g %g %g \n" % (x.flat[3*i+0],x.flat[3*i+1],x.flat[3*i+2]))
#
cmdFile.write("];")
#
if elementNodesConnectivity is not None:
assert len(elementNodesConnectivity.shape) == 2
cmdFile.write("tri_%s_ex = [ ... \n" % name)
for eN in range(elementNodesConnectivity.shape[0]):
for nN in range(elementNodesConnectivity.shape[1]):
cmdFile.write(" %i " % (elementNodesConnectivity[eN,nN]+1))
cmdFile.write("; \n ")
#
cmdFile.write("];")
#
cmdFile.write("%s_ex = [ ... \n" % name)
for i in range(nPoints):
uex = f(x.flat[3*i:3*(i+1)],t)
cmdFile.write("%g \n" % uex)
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
if elementNodesConnectivity is None:
cmd = cmd2dData % (name,name,name)
cmdFile.write(cmd)
cmd = cmd2dView % (figureNumber,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
if elementNodesConnectivity is None:
cmd = cmd3dData % (name,name,name,name)
cmdFile.write(cmd)
cmd = cmd3dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 0 #tetramesh no good right now
#
return nplotted
def viewVectorAnalyticalFunction(self,cmdFile,nSpace,f,t,x,elementNodesConnectivity=None,
name='exact',storeMeshData=True,figureNumber=1,title=None):
"""
input vector analytical function f(x,t) and array of points
respectively, generate global continuous interpolant
uses delaunay triangulation in 2d and 3d if element - node triangulation not already defined
vector data is stored in
name_ex
if storeMeshData = True, writes out
name_x_ex -- point data
tri_name_ex -- element-node representation (2d,3d)
returns number of figures actually plotted
"""
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
[x_tmp,i_tmp] = sort(%s_x_ex(:,1)); %s_x_ex = %s_x_ex(i_tmp); %s_ex = %s_ex(i_tmp);
"""
cmd1dView = """
figure(%i) ; plot(%s_x_ex(:,1),%s_ex) ; title('%s');
"""
#2d
#if does not have element-node connectivity already
cmd2dData = """
tri_%s_ex = delaunay(%s_x_ex(:,1),%s_x_ex(:,2));
"""
cmd2dView = """
%s_ex_mag = (%s_ex(:,1).^2 + %s_ex(:,2).^2).^(0.5);
figure(%i) ; quiver(%s_x_ex(:,1),%s_x_ex(:,2),%s_ex(:,1),%s_ex(:,2));title('%s');
%%could also use
%% trimesh(tri_name_ex,name_x_ex(:,1),name_x_ex(:,2),name_ex_mag);
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x_ex(:,1)) max(%s_x_ex(:,1)) ; min(%s_x_ex(:,2)) max(%s_x_ex(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_qxg,%s_qyg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%s_qg_x = griddata(%s_x_ex(:,1),%s_x_ex(:,2),%s_ex(:,1),%s_qxg,%s_qyg);
%s_qg_y = griddata(%s_x_ex(:,1),%s_x_ex(:,2),%s_ex(:,2),%s_qxg,%s_qyg);
"""
#3d
#if does not have element-node connectivity already
cmd3dData = """
tri_%s_ex = delaunay3(%s_x_ex(:,1),%s_x_ex(:,2),%s_x_ex(:,3));
"""
cmd3dView = """
%s_ex_mag = (%s_ex(:,1).^2 + %s_ex(:,2).^2 + %s_ex(:,3).^2).^(0.5);
figure(%i) ; quiver3(%s_x_ex(:,1),%s_x_ex(:,2),%s_x_ex(:,3),%s_ex(:,1),%s_ex(:,2),%s_ex(:,3));title('%s');
%%Warning not very good right now
%% tetramesh(tri_name_ex,name_x_ex);
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x_ex(:,1)) max(%s_x_ex(:,1)) ; min(%s_x_ex(:,2)) max(%s_x_ex(:,2)) ; min(%s_x_ex(:,3)) max(%s_x_ex(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_qxg,%s_qyg,%s_qzg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%s_qg_x = griddata3(%s_x_ex(:,1),%s_x_ex(:,2),%s_x_ex(:,3),%s_ex(:,1),%s_qxg,%s_qyg,%s_qzg);
%s_qg_y = griddata3(%s_x_ex(:,1),%s_x_ex(:,2),%s_x_ex(:,3),%s_ex(:,2),%s_qxg,%s_qyg,%s_qzg);
%s_qg_z = griddata3(%s_x_ex(:,1),%s_x_ex(:,2),%s_x_ex(:,3),%s_ex(:,3),%s_qxg,%s_qyg,%s_qzg);
"""
###
if title is None:
title = name
nPoints = 1
for i in range(len(x.shape)-1):
nPoints *= x.shape[i]
if storeMeshData:
cmdFile.write("%s_x_ex = [ ... \n" % name)
for i in range(nPoints):
cmdFile.write("%g %g %g \n" % (x.flat[3*i+0],x.flat[3*i+1],x.flat[3*i+2]))
#
cmdFile.write("];")
#
if elementNodesConnectivity is not None:
assert len(elementNodesConnectivity.shape) == 2
cmdFile.write("tri_%s_ex = [ ... \n" % name)
for eN in range(elementNodesConnectivity.shape[0]):
for nN in range(elementNodesConnectivity.shape[1]):
cmdFile.write(" %i " % (elementNodesConnectivity[eN,nN]+1))
cmdFile.write("; \n ")
#
cmdFile.write("];")
#
cmdFile.write("%s_ex = [ ... \n" % name)
for i in range(nPoints):
uex = f(x.flat[3*i:3*(i+1)],t)
for I in range(nSpace):
cmdFile.write(" %g " % uex[I])
cmdFile.write("; \n")
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
if elementNodesConnectivity is None:
cmd = cmd2dData % (name,name,name)
cmdFile.write(cmd)
cmd = cmd2dView % (name,name,name,
figureNumber,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
if elementNodesConnectivity is None:
cmd = cmd3dData % (name,name,name,name)
cmdFile.write(cmd)
cmd = cmd3dView % (name,name,name,name,
figureNumber,name,name,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name,
name,name,name,name,name,name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1 #
#
return nplotted
def viewScalar_LagrangeC0P1(self,cmdFile,nSpace,nodeArray,elementNodesArray,u_dof,
name="u",storeMeshData=True,figureNumber=1,title=None):
# """given C0 P1 function with nodal Lagrange representation generate a
# matlab representation that is as faithful as possible to the
# actual finite element function structure
# C0-P1 output: mesh vertices and element connectivity degrees of freedom at vertices
# scalar data is stored in name
# if storeMeshData = True, writes out
# name_x -- mesh vertices
# tri_name_v -- element-node representation
# returns number of figures actually plotted
# """
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
[x_tmp,i_tmp] = sort(%s_x(:,1)); %s_x = %s_x(i_tmp); %s = %s(i_tmp);
"""
cmd1dView = """
figure(%i) ; plot(%s_x(:,1),%s) ; title('%s');
"""
#2d
cmd2dData = """ \n """
cmd2dView = """
figure(%i) ; trimesh(tri_%s,%s_x(:,1),%s_x(:,2),%s); title('%s');
%%also could be used
%%trisurf(tri_name,name_x(:,1),name_x(:,2),name);
%%tmp = name_x; tmp(:,3) = name;
%%patch('vertices',tmp,'faces',tri_name,'FaceVertexCData',name,'FaceColor','interp','EdgeColor','none')
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_xg,%s_yg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%s_g = griddata(%s_x(:,1),%s_x(:,2),%s,%s_xg,%s_yg);
"""
#3d
cmd3dData = """ \n """
cmd3dView = """
%%figure out reasonable default using tetramesh or patch
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2)) ; min(%s_x(:,3)) max(%s_x(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_xg,%s_yg,%s_zg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%s_g = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s,%s_xg,%s_yg,%s_zg);
"""
if title is None:
title = name
nNodes_global = nodeArray.shape[0]; nElements_global = elementNodesArray.shape[0]
nNodes_element= elementNodesArray.shape[1]
assert nNodes_element == nSpace+1, "affine simplicial geometry only"
if storeMeshData:
cmdFile.write("%s_x = [ ... \n" % name)
for nN in range(nNodes_global):
cmdFile.write("%g %g %g \n" % (nodeArray[nN,0],nodeArray[nN,1],nodeArray[nN,2]))
#
cmdFile.write("];")
#
cmdFile.write("tri_%s = [ ... \n" % name)
for eN in range(nElements_global):
for nN in range(nNodes_element):
cmdFile.write(" %i " % (elementNodesArray[eN,nN]+1))
cmdFile.write("; \n ")
#
cmdFile.write("];")
#
cmdFile.write("%s = [ ... \n" % name)
for i in range(u_dof.shape[0]):
cmdFile.write("%g \n" % u_dof[i])
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
#nothing to be done with mesh-data representation here
cmd = cmd2dView % (figureNumber,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
#nothing to be done with mesh-data representation here
#cmd = cmd3dView % (figureNumber,name,name,title)
#cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 0 #tetramesh no good right now
#
return nplotted
#
def viewVector_LagrangeC0P1(self,cmdFile,nSpace,nodeArray,elementNodesArray,
u_dof,v_dof=None,w_dof=None,
name="velocity",storeMeshData=True,figureNumber=1,title=None):
# """
# given a vector valued C0 P1 function with nodal Lagrange representation
# generate a matlab representation that is as faithful as possible to
# the actual finite element function structure
# Assumes 1 <= number of components <= nSpace
# C0-P1 output:
# mesh vertices and element connectivity
# degrees of freedom at vertices
# vector data is stored in
# name which is [nNodes,nCoord]
# if storeMeshData = True, writes out
# name_x -- mesh vertices
# tri_name_v -- element-node representation
# returns number of figures actually plotted
# """
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
[x_tmp,i_tmp] = sort(%s_x(:,1)); %s_x = %s_x(i_tmp); %s = %s(i_tmp);
"""
cmd1dView = """
figure(%i) ; plot(%s_x(:,1),%s) ; title('%s');
"""
#2d
cmd2dData = """ \n """
cmd2dView = """
%s_mag = (%s(:,1).^2 + %s(:,2).^2).^(0.5);
figure(%i) ; quiver(%s_x(:,1),%s_x(:,2),%s(:,1),%s(:,2));title('%s');
%%could also use
%% trimesh(tri_name,name_x(:,1),name_x(:,2),name_mag);
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_xg,%s_yg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%s_gxcoord = griddata(%s_x(:,1),%s_x(:,2),%s(:,1),%s_xg,%s_yg);
%s_gycoord = griddata(%s_x(:,1),%s_x(:,2),%s(:,2),%s_xg,%s_yg);
"""
#3d
cmd3dData = """ \n """
cmd3dView = """
%s_mag = (%s_x(:,1).^2 + %s_x(:,2).^2 + %s_x(:,3).^2).^(0.5);
figure(%i) ; quiver3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s(:,1),%s(:,2),%s(:,3));title('%s');
%%figure out reasonable default using tetramesh or patch
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2)) ; min(%s_x(:,3)) max(%s_x(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_xg,%s_yg,%s_zg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%s_gxcoord = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s(:,1),%s_xg,%s_yg,%s_zg);
%s_gycoord = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s(:,2),%s_xg,%s_yg,%s_zg);
%s_gzcoord = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s(:,3),%s_xg,%s_yg,%s_zg);
"""
if title is None:
title = name
#
nNodes_global = nodeArray.shape[0]; nElements_global = elementNodesArray.shape[0]
nNodes_element= elementNodesArray.shape[1]
assert nNodes_element == nSpace+1, "affine simplicial geometry only"
nCoords = 1
if v_dof is not None:
nCoords += 1
assert v_dof.shape == u_dof.shape
if w_dof is not None:
nCoords += 1
assert w_dof.shape == u_dof.shape
assert (1 <= nCoords and nCoords <= nSpace), "nCoords= %s nSpace= %s wrong " % (nCoords,nSpace)
if storeMeshData:
cmdFile.write("%s_x = [ ... \n" % name)
for nN in range(nNodes_global):
cmdFile.write("%g %g %g \n" % (nodeArray[nN,0],nodeArray[nN,1],nodeArray[nN,2]))
#
cmdFile.write("];")
#
cmdFile.write("tri_%s = [ ... \n" % name)
for eN in range(nElements_global):
for nN in range(nNodes_element):
cmdFile.write(" %i " % (elementNodesArray[eN,nN]+1))
cmdFile.write("; \n ")
#
cmdFile.write("];")
#
cmdFile.write("%s = [ ... \n" % name)
for i in range(u_dof.shape[0]):
cmdFile.write(" %g " % u_dof[i])
if nCoords > 1: cmdFile.write(" %g " % v_dof[i])
if nCoords > 2: cmdFile.write(" %g " % w_dof[i])
cmdFile.write(" \n ")
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
#nothing to be done with mesh-data representation here
cmd = cmd2dView % (name,name,name,
figureNumber,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
#nothing to be done with mesh-data representation here
cmd = cmd3dView % (name,name,name,name,
figureNumber,name,name,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name,
name,name,name,name,name,name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1 #
#
return nplotted
#
def viewScalar_LagrangeC0P2(self,cmdFile,nSpace,lagrangeNodesArray,elementNodesArray,
l2g,u_dof,
name="u",storeMeshData=True,figureNumber=1,title=None):
# """TODO 3D
# given C0 P2 function with nodal Lagrange representation
# generate a matlab representation that is as faithful as possible to
# the actual finite element function structure
# C0-P2 output: matlab mesh vertices stored according [geometric
# vertices, midNodesVertices] and element connectivity for
# refined mesh degrees of freedom at all vertices 'mid-edge'
# vertices stored in midNodesArray
# scalar data is stored in
# name
# if storeMeshData = True, writes out
# name_x -- matlab mesh vertices
# tri_name_v -- matlab element-node representation
# returns number of figures actually plotted
# """
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
[x_tmp,i_tmp] = sort(%s_x(:,1)); %s_x = %s_x(i_tmp); %s = %s(i_tmp);
"""
cmd1dView = """
figure(%i) ; plot(%s_x(:,1),%s) ; title('%s');
"""
#2d
cmd2dData = """ \n """
cmd2dView = """
figure(%i) ; trimesh(tri_%s,%s_x(:,1),%s_x(:,2),%s); title('%s');
%%also could be used
%%trisurf(tri_name,name_x(:,1),name_x(:,2),name);
%%tmp = name_x; tmp(:,3) = name;
%%patch('vertices',tmp,'faces',tri_name,'FaceVertexCData',name,'FaceColor','interp','EdgeColor','none')
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_xg,%s_yg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%s_g = griddata(%s_x(:,1),%s_x(:,2),%s,%s_xg,%s_yg);
"""
#3d
cmd3dData = """ \n """
cmd3dView = """
%%figure out reasonable default using tetramesh or patch
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2)) ; min(%s_x(:,3)) max(%s_x(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_xg,%s_yg,%s_zg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%s_g = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s,%s_xg,%s_yg,%s_zg);
"""
if title is None:
title = name
nLagrangeNodes_global = lagrangeNodesArray.shape[0]; nElements_global = elementNodesArray.shape[0]
nNodes_element= elementNodesArray.shape[1]
assert nNodes_element == nSpace+1, "affine simplicial geometry only"
assert u_dof.shape[0] == nLagrangeNodes_global, "u_dof len=%s but nLagrangeNodes_global=%s " % (u_dof.shape[0],
nLagrangeNodes_global)
nMidNodes_element = int((nSpace+2)*(nSpace+1)/2) - nNodes_element
#store geometric nodes first, then "quadratic" ones
if storeMeshData:
cmdFile.write("%s_x = [ ... \n" % name)
for nN in range(nLagrangeNodes_global):
cmdFile.write("%g %g %g \n" % (lagrangeNodesArray[nN,0],lagrangeNodesArray[nN,1],lagrangeNodesArray[nN,2]))
#
cmdFile.write("];")
#
if nSpace == 1:
cmdFile.write("tri_%s = [ ... \n" % name)
for eN in range(nElements_global):
#not necessary going to get positive jacobians
cmdFile.write(" %i " % (l2g[eN,0]+1))
cmdFile.write(" %i " % (l2g[eN,2]+1)) #use l2g?
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,2]+1))#use l2g?
cmdFile.write(" %i " % (l2g[eN,1]+1))
cmdFile.write(" \n ")
cmdFile.write("];")
elif nSpace == 2:
cmdFile.write("tri_%s = [ ... \n" % name)
for eN in range(nElements_global):
#four triangles per element, see FemTools Quadratic space for numbering convention
cmdFile.write(" %i " % (l2g[eN,0]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+0]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+2]+1))
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,nNodes_element+0]+1))
cmdFile.write(" %i " % (l2g[eN,1]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+1]+1))
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,nNodes_element+1]+1))
cmdFile.write(" %i " % (l2g[eN,2]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+2]+1))
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,nNodes_element+0]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+1]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+2]+1))
cmdFile.write(" \n ")
cmdFile.write("];")
else:
print("""3d LagrangeC0P2 not implemented yet""")
return 0
#
#assumes l2g layout consistent with matlab one
cmdFile.write("%s = [ ... \n" % name)
for i in range(u_dof.shape[0]):
cmdFile.write("%g \n" % u_dof[i])
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
#nothing to be done with mesh-data representation here
cmd = cmd2dView % (figureNumber,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
#nothing to be done with mesh-data representation here
#cmd = cmd3dView % (figureNumber,name,name,title)
#cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 0 #tetramesh no good right now
#
return nplotted
#
def viewVector_LagrangeC0P2(self,cmdFile,nSpace,lagrangeNodesArray,elementNodesArray,
l2g,u_dof,v_dof=None,w_dof=None,
name="velocity",storeMeshData=True,figureNumber=1,title=None):
# """
# TODO: 3D
# given a vector valued C0 P2 function with nodal Lagrange representation
# generate a matlab representation that is as faithful as possible to
# the actual finite element function structure
# Assumes 1 <= number of components <= nSpace
# C0-P2 output:
# matlab mesh vertices stored according [geometric vertices, midNodesVertices]
# and element connectivity for refined mesh
# degrees of freedom at all vertices
# 'mid-edge' vertices stored in midNodesArray
# vector data is stored in
# name which is [nNodes,nCoord]
# if storeMeshData = True, writes out
# name_x -- mesh vertices
# tri_name_v -- element-node representation
# returns number of figures actually plotted
# """
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
[x_tmp,i_tmp] = sort(%s_x(:,1)); %s_x = %s_x(i_tmp); %s = %s(i_tmp);
"""
cmd1dView = """
figure(%i) ; plot(%s_x(:,1),%s) ; title('%s');
"""
#2d
cmd2dData = """ \n """
cmd2dView = """
%s_mag = (%s(:,1).^2 + %s(:,2).^2).^(0.5);
figure(%i) ; quiver(%s_x(:,1),%s_x(:,2),%s(:,1),%s(:,2));title('%s');
%%could also use
%% trimesh(tri_name,name_x(:,1),name_x(:,2),name_mag);
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_xg,%s_yg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%s_gxcoord = griddata(%s_x(:,1),%s_x(:,2),%s(:,1),%s_xg,%s_yg);
%s_gycoord = griddata(%s_x(:,1),%s_x(:,2),%s(:,2),%s_xg,%s_yg);
"""
#3d
cmd3dData = """ \n """
cmd3dView = """
%s_mag = (%s_x(:,1).^2 + %s_x(:,2).^2 + %s_x(:,3).^2).^(0.5);
figure(%i) ; quiver3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s(:,1),%s(:,2),%s(:,3));title('%s');
%%figure out reasonable default using tetramesh or patch
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2)) ; min(%s_x(:,3)) max(%s_x(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_xg,%s_yg,%s_zg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%s_gxcoord = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s(:,1),%s_xg,%s_yg,%s_zg);
%s_gycoord = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s(:,2),%s_xg,%s_yg,%s_zg);
%s_gzcoord = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s(:,3),%s_xg,%s_yg,%s_zg);
"""
if title is None:
title = name
#
nLagrangeNodes_global = lagrangeNodesArray.shape[0]; nElements_global = elementNodesArray.shape[0]
nNodes_element= elementNodesArray.shape[1]
assert nNodes_element == nSpace+1, "affine simplicial geometry only"
assert u_dof.shape[0] == nLagrangeNodes_global, "u_dof len=%s but nLagrangeNodes_global=%s " % (u_dof.shape[0],
nLagrangeNodes_global)
nMidNodes_element = int((nSpace+2)*(nSpace+1)/2) - nNodes_element
nCoords = 1
if v_dof is not None:
nCoords += 1
assert v_dof.shape == u_dof.shape
if w_dof is not None:
nCoords += 1
assert w_dof.shape == u_dof.shape
assert (1 <= nCoords and nCoords <= nSpace), "nCoords= %s nSpace= %s wrong " % (nCoords,nSpace)
#store geometric nodes first, then "quadratic" ones
if storeMeshData:
cmdFile.write("%s_x = [ ... \n" % name)
for nN in range(nLagrangeNodes_global):
cmdFile.write("%g %g %g \n" % (lagrangeNodesArray[nN,0],lagrangeNodesArray[nN,1],lagrangeNodesArray[nN,2]))
#
cmdFile.write("];")
#
if nSpace == 1:
cmdFile.write("tri_%s = [ ... \n" % name)
for eN in range(nElements_global):
#not necessary going to get positive jacobians
cmdFile.write(" %i " % (l2g[eN,0]+1))
cmdFile.write(" %i " % (l2g[eN,2]+ 1)) #use l2g?
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,2] + 1))#use l2g?
cmdFile.write(" %i " % (l2g[eN,1]+1))
cmdFile.write(" \n ")
cmdFile.write("];")
elif nSpace == 2:
cmdFile.write("tri_%s = [ ... \n" % name)
for eN in range(nElements_global):
#four triangles per element, see FemTools Quadratic space for numbering convention
cmdFile.write(" %i " % (l2g[eN,0]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+0]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+2]+1))
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,nNodes_element+0]+1))
cmdFile.write(" %i " % (l2g[eN,1]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+1]+1))
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,nNodes_element+1]+1))
cmdFile.write(" %i " % (l2g[eN,2]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+2]+1))
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,nNodes_element+0]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+1]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+2]+1))
cmdFile.write(" \n ")
cmdFile.write("];")
else:
print("""3d LagrangeC0P2 not implemented yet""")
return 0
#
#assumes l2g layout consistent with matlab one
cmdFile.write("%s = [ ... \n" % name)
for i in range(u_dof.shape[0]):
cmdFile.write(" %g " % u_dof[i])
if nCoords > 1: cmdFile.write(" %g " % v_dof[i])
if nCoords > 2: cmdFile.write(" %g " % w_dof[i])
cmdFile.write(" \n ")
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
#nothing to be done with mesh-data representation here
cmd = cmd2dView % (name,name,name,
figureNumber,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
#nothing to be done with mesh-data representation here
cmd = cmd3dView % (name,name,name,name,
figureNumber,name,name,name,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name,
name,name,name,name,name,name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1 #
#
return nplotted
#
def viewScalar_DGP0(self,cmdFile,nSpace,nodeArray,elementNodesArray,l2g,u_dof,
name="u",storeMeshData=True,figureNumber=1,title=None):
# """
# given DG P0 function
# generate a matlab representation that is as faithful as possible to
# the actual finite element function structure
# Assumes local dof associated with local node numbering
# DG-P0 output:
# element-wise list of vertices and local elemntwise-connectivity matrices
# degrees of freedom at element vertices (as if a DG-P1 function)
# scalar data is stored in
# name
# if storeMeshData = True, writes out
# name_x -- mesh vertices
# tri_name -- element-node representation
# returns number of figures actually plotted
# """
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
%s_dg = %s_x; %s_dg(:,2) = %s;
nNodes = max(max(tri_%s_cg)); %s_cg = zeros(nNodes,1); nn_cg = zeros(nNodes,1);
nElements = size(tri_%s_cg,1); nDOF_element = size(tri_%s_cg,2);
for eN = 1:nElements
for i = 1:nDOF_element
I = tri_%s_cg(eN,i);
%s_cg(I) = %s_cg(I) + %s(tri_%s(eN,i));
nn_cg(I) = nn_cg(I) + 1.;
end
end
%s_cg = %s_cg ./ nn_cg;
"""
cmd1dView = """
figure(%i); patch('vertices',%s_dg(:,1:2),'faces',tri_%s); title('%s');
"""
#2d
cmd2dData = """
%s_dg = %s_x; %s_dg(:,3) = %s;
nNodes = max(max(tri_%s_cg)); %s_cg = zeros(nNodes,1); nn_cg = zeros(nNodes,1);
nElements = size(tri_%s_cg,1); nDOF_element = size(tri_%s_cg,2);
for eN = 1:nElements
for i = 1:nDOF_element
I = tri_%s_cg(eN,i);
%s_cg(I) = %s_cg(I) + %s(tri_%s(eN,i));
nn_cg(I) = nn_cg(I) + 1.;
end
end
%s_cg = %s_cg ./ nn_cg;
"""
cmd2dView = """
figure(%i); patch('vertices',%s_dg,'faces',tri_%s,'FaceVertexCData',%s_dg,'FaceColor','interp','EdgeColor','none'); title('%s');
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_xg,%s_yg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%%note, uses average of duplicate values
%s_g = griddata(%s_x(:,1),%s_x(:,2),%s,%s_xg,%s_yg);
"""
#3d
cmd3dData = """
nNodes = max(max(tri_%s_cg)); %s_cg = zeros(nNodes,1); nn_cg = zeros(nNodes,1);
nElements = size(tri_%s_cg,1); nDOF_element = size(tri_%s_cg,2);
for eN = 1:nElements
for i = 1:nDOF_element
I = tri_%s_cg(eN,i);
%s_cg(I) = %s_cg(I) + %s(tri_%s(eN,i));
nn_cg(I) = nn_cg(I) + 1.;
end
end
%s_cg = %s_cg ./ nn_cg;
"""
cmd3dView = """
figure(%i); patch('vertices',%s_x,'faces',tri_%s,'FaceVertexCData',%s,'FaceColor','interp','EdgeColor','none'); title('%s');
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2)) ; min(%s_x(:,3)) max(%s_x(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_xg,%s_yg,%s_zg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%%note, uses average of duplicate values
%s_g = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s,%s_xg,%s_yg,%s_zg);
"""
if title is None:
title = name
nNodes_global = nodeArray.shape[0]; nElements_global = l2g.shape[0]
nNodes_element= elementNodesArray.shape[1]
nDOF_element = l2g.shape[1]
if storeMeshData:
cmdFile.write("%s_x = [ ... \n" % name)
for eN in range(nElements_global):
for nN_local in range(nNodes_element):
nN = elementNodesArray[eN,nN_local]
cmdFile.write("%g %g %g \n" % (nodeArray[nN,0],nodeArray[nN,1],nodeArray[nN,2]))
#
cmdFile.write("];")
cmdFile.write("%s_x_cg = [ ... \n" % name)
for nN in range(nNodes_global):
cmdFile.write("%g %g %g \n" % (nodeArray[nN,0],nodeArray[nN,1],nodeArray[nN,2]))
#
cmdFile.write("];")
#
cmdFile.write("tri_%s = [ ... \n" % name)
for eN in range(nElements_global):
for nN in range(nNodes_element):#assumes laid out line element nodes
cmdFile.write(" %i " % (eN*nNodes_element+nN+1))
cmdFile.write("; \n ")
#
cmdFile.write("];")
#
#provide CG connectivity if wanted nodal averages for some reason
cmdFile.write("tri_%s_cg = [ ... \n" % name)
for eN in range(nElements_global):
for i in range(nDOF_element):#assumes laid out line element nodes
cmdFile.write(" %i " % (elementNodesArray[eN,i]+1))
cmdFile.write("; \n ")
#
cmdFile.write("];")
#
cmdFile.write("%s = [ ... \n" % name)
for eN in range(nElements_global):
for nN in range(nNodes_element):
cmdFile.write("%g \n" % u_dof[l2g[eN,0]])
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name,
name,name,
name,name,
name,
name,name,name,name,
name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
cmd = cmd2dData % (name,name,name,name,
name,name,
name,name,
name,
name,name,name,name,
name,name)
cmdFile.write(cmd)
cmd = cmd2dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
cmd = cmd3dData % (name,name,
name,name,
name,
name,name,name,name,
name,name)
cmdFile.write(cmd)
cmd = cmd3dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
#
return nplotted
#
def viewScalar_LagrangeDGP1(self,cmdFile,nSpace,nodeArray,elementNodesArray,l2g,u_dof,
name="u",storeMeshData=True,figureNumber=1,title=None):
# """
# given DG P1 function with nodal Lagrange representation
# generate a matlab representation that is as faithful as possible to
# the actual finite element function structure
# Assumes local dof associated with local node numbering
# DG-P1 output:
# element-wise list of vertices and local elemntwise-connectivity matrices
# degrees of freedom at vertices
# scalar data is stored in
# name
# if storeMeshData = True, writes out
# name_x -- mesh vertices
# tri_name -- element-node representation
# returns number of figures actually plotted
# """
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
%s_dg = %s_x; %s_dg(:,2) = %s;
nNodes = max(max(tri_%s_cg)); %s_cg = zeros(nNodes,1); nn_cg = zeros(nNodes,1);
nElements = size(tri_%s_cg,1); nDOF_element = size(tri_%s_cg,2);
for eN = 1:nElements
for i = 1:nDOF_element
I = tri_%s_cg(eN,i);
%s_cg(I) = %s_cg(I) + %s(tri_%s(eN,i));
nn_cg(I) = nn_cg(I) + 1.;
end
end
%s_cg = %s_cg ./ nn_cg;
"""
cmd1dView = """
figure(%i); patch('vertices',%s_dg(:,1:2),'faces',tri_%s); title('%s');
"""
#2d
cmd2dData = """
%s_dg = %s_x; %s_dg(:,3) = %s;
nNodes = max(max(tri_%s_cg)); %s_cg = zeros(nNodes,1); nn_cg = zeros(nNodes,1);
nElements = size(tri_%s_cg,1); nDOF_element = size(tri_%s_cg,2);
for eN = 1:nElements
for i = 1:nDOF_element
I = tri_%s_cg(eN,i);
%s_cg(I) = %s_cg(I) + %s(tri_%s(eN,i));
nn_cg(I) = nn_cg(I) + 1.;
end
end
%s_cg = %s_cg ./ nn_cg;
"""
cmd2dView = """
figure(%i); patch('vertices',%s_dg,'faces',tri_%s,'FaceVertexCData',%s_dg,'FaceColor','interp','EdgeColor','none'); title('%s');
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_xg,%s_yg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%%note, uses average of duplicate values
%s_g = griddata(%s_x(:,1),%s_x(:,2),%s,%s_xg,%s_yg);
"""
#3d
cmd3dData = """
nNodes = max(max(tri_%s_cg)); %s_cg = zeros(nNodes,1); nn_cg = zeros(nNodes,1);
nElements = size(tri_%s_cg,1); nDOF_element = size(tri_%s_cg,2);
for eN = 1:nElements
for i = 1:nDOF_element
I = tri_%s_cg(eN,i);
%s_cg(I) = %s_cg(I) + %s(tri_%s(eN,i));
nn_cg(I) = nn_cg(I) + 1.;
end
end
%s_cg = %s_cg ./ nn_cg;
"""
cmd3dView = """
figure(%i); patch('vertices',%s_x,'faces',tri_%s,'FaceVertexCData',%s,'FaceColor','interp','EdgeColor','none'); title('%s');
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2)) ; min(%s_x(:,3)) max(%s_x(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_xg,%s_yg,%s_zg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%%note, uses average of duplicate values
%s_g = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s,%s_xg,%s_yg,%s_zg);
"""
if title is None:
title = name
nNodes_global = nodeArray.shape[0]; nElements_global = l2g.shape[0]
nNodes_element= elementNodesArray.shape[1]
nDOF_element = l2g.shape[1]
if storeMeshData:
cmdFile.write("%s_x = [ ... \n" % name)
for eN in range(nElements_global):
for nN_local in range(nNodes_element):
nN = elementNodesArray[eN,nN_local]
cmdFile.write("%g %g %g \n" % (nodeArray[nN,0],nodeArray[nN,1],nodeArray[nN,2]))
#
cmdFile.write("];")
cmdFile.write("%s_x_cg = [ ... \n" % name)
for nN in range(nNodes_global):
cmdFile.write("%g %g %g \n" % (nodeArray[nN,0],nodeArray[nN,1],nodeArray[nN,2]))
#
cmdFile.write("];")
#
cmdFile.write("tri_%s = [ ... \n" % name)
for eN in range(nElements_global):
for i in range(nDOF_element):#assumes laid out line element nodes
cmdFile.write(" %i " % (l2g[eN,i]+1))
cmdFile.write("; \n ")
#
cmdFile.write("];")
#
#provide CG connectivity
cmdFile.write("tri_%s_cg = [ ... \n" % name)
for eN in range(nElements_global):
for i in range(nDOF_element):#assumes laid out line element nodes
cmdFile.write(" %i " % (elementNodesArray[eN,i]+1))
cmdFile.write("; \n ")
#
cmdFile.write("];")
#
cmdFile.write("%s = [ ... \n" % name)
for i in range(u_dof.shape[0]):
cmdFile.write("%g \n" % u_dof[i])
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name,
name,name,
name,name,
name,
name,name,name,name,
name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
cmd = cmd2dData % (name,name,name,name,
name,name,
name,name,
name,
name,name,name,name,
name,name)
cmdFile.write(cmd)
cmd = cmd2dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
cmd = cmd3dData % (name,name,
name,name,
name,
name,name,name,name,
name,name)
cmdFile.write(cmd)
cmd = cmd3dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
#
return nplotted
#
def viewScalar_LagrangeDGP2(self,cmdFile,nSpace,nodeArray,elementNodesArray,midNodesArray,
l2g,cg_l2g,u_dof,
name="u",storeMeshData=True,figureNumber=1,title=None):
# """
# TODO: 3d
# given DG P1 function with nodal Lagrange representation
# generate a matlab representation that is as faithful as possible to
# the actual finite element function structure
# Assumes local dof associated with local node numbering
# and then local edge numbering
# uses cg numbering for accessing mid-edge vertices
# DG-P2 output:
# element-wise list of vertices and mid-edge vertices along
# with local elemntwise-connectivity matrices
# degrees of freedom at vertices and mid-edge vertices
# scalar data is stored in
# name
# if storeMeshData = True, writes out
# name_x -- mesh vertices and mid-edge vertices
# tri_name -- element-node representation
# returns number of figures actually plotted
# """
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
%s_dg = %s_x; %s_dg(:,2) = %s;
"""
cmd1dView = """
figure(%i); patch('vertices',%s_dg(:,1:2),'faces',tri_%s); title('%s');
"""
#2d
cmd2dData = """
%s_dg = %s_x; %s_dg(:,3) = %s;
"""
cmd2dView = """
figure(%i); patch('vertices',%s_dg,'faces',tri_%s,'FaceVertexCData',%s_dg,'FaceColor','interp','EdgeColor','none'); title('%s');
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_xg,%s_yg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%%note, uses average of duplicate values
%s_g = griddata(%s_x(:,1),%s_x(:,2),%s,%s_xg,%s_yg);
"""
#3d
cmd3dData = """
"""
cmd3dView = """
figure(%i); patch('vertices',%s_dg,'faces',tri_%s,'FaceVertexCData',%s,'FaceColor','interp','EdgeColor','none'); title('%s');
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2)) ; min(%s_x(:,3)) max(%s_x(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_xg,%s_yg,%s_zg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%%note, uses average of duplicate values
%s_g = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s,%s_xg,%s_yg,%s_zg);
"""
if title is None:
title = name
nNodes_global = nodeArray.shape[0]; nElements_global = l2g.shape[0]
nNodes_element= elementNodesArray.shape[1]
assert nNodes_element == nSpace+1, "affine simplicial geometry only"
nMidNodes_global = midNodesArray.shape[0]
nMidNodes_element = int((nSpace+2)*(nSpace+1)/2) - nNodes_element
nDOF_element = l2g.shape[1]
assert nDOF_element == nMidNodes_element + nNodes_element
#assumes local ordering vertices then midedge nodes
if storeMeshData:
cmdFile.write("%s_x = [ ... \n" % name)
for eN in range(nElements_global):
for nN_local in range(nNodes_element):
nN = elementNodesArray[eN,nN_local]
cmdFile.write("%g %g %g \n" % (nodeArray[nN,0],nodeArray[nN,1],nodeArray[nN,2]))
for nM_local in range(nMidNodes_element):
nM = cg_l2g[eN,nNodes_element+nM_local] - nNodes_global
cmdFile.write("%g %g %g \n" % (midNodesArray[nM,0],midNodesArray[nM,1],midNodesArray[nM,2]))
#
cmdFile.write("];")
#
cmdFile.write("tri_%s = [ ... \n" % name)
if nSpace == 1:
for eN in range(nElements_global):
cmdFile.write(" %i " % (l2g[eN,0]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+0]+1))
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,nNodes_element+0]+1))
cmdFile.write(" %i \n" % (l2g[eN,1]+1))
cmdFile.write("; \n ")
elif nSpace == 2:
for eN in range(nElements_global):
#four triangles per element, see FemTools Quadratic space for numbering convention
cmdFile.write(" %i " % (l2g[eN,0]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+0]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+2]+1))
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,nNodes_element+0]+1))
cmdFile.write(" %i " % (l2g[eN,1]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+1]+1))
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,nNodes_element+1]+1))
cmdFile.write(" %i " % (l2g[eN,2]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+2]+1))
cmdFile.write(" \n ")
cmdFile.write(" %i " % (l2g[eN,nNodes_element+0]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+1]+1))
cmdFile.write(" %i " % (l2g[eN,nNodes_element+2]+1))
cmdFile.write(" \n ")
cmdFile.write("; \n ")
else:
print("""3d LagrangeDGP2 not implemented yet""")
return 0
#
cmdFile.write("];")
#
cmdFile.write("%s = [ ... \n" % name)
for i in range(u_dof.shape[0]):
cmdFile.write("%g \n" % u_dof[i])
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
cmd = cmd2dData % (name,name,name,name)
cmdFile.write(cmd)
cmd = cmd2dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
cmd = cmd3dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
#
return nplotted
#
def viewScalar_CrouzeixRaviartP1(self,cmdFile,nSpace,nodeArray,elementNodesArray,l2g,u_dof,
name="u",storeMeshData=True,figureNumber=1,title=None):
# """
# given FEM function with local Crouzeix-Raviart representation
# generate a matlab representation that is as faithful as possible to
# the actual finite element function structure
# Assumes local dof associated with local node numbering
# CR output:
# Just treat as a DGP1 function
# element-wise list of vertices and local elemntwise-connectivity matrices
# degrees of freedom at vertices instead of face barycenters
# scalar data is stored in
# name
# if storeMeshData = True, writes out
# name_x -- mesh vertices
# tri_name -- element-node representation
# returns number of figures actually plotted
# """
nplotted = 0
###simple visualization commands (%s --> name)
#1d
cmd1dData = """
%%actully just C0P1 in 1d
%s_cr = %s_x; %s_cr(:,2) = %s;
"""
cmd1dView = """
figure(%i); patch('vertices',%s_cr(:,1:2),'faces',tri_%s); title('%s');
"""
#2d
cmd2dData = """
%s_cr = %s_x; %s_cr(:,3) = %s;
nNodes = max(max(tri_%s_cg)); %s_cg = zeros(nNodes,1); nn_cg = zeros(nNodes,1);
nElements = size(tri_%s_cg,1); nDOF_element = size(tri_%s_cg,2);
for eN = 1:nElements
for i = 1:nDOF_element
I = tri_%s_cg(eN,i);
%s_cg(I) = %s_cg(I) + %s(tri_%s(eN,i));
nn_cg(I) = nn_cg(I) + 1.;
end
end
%s_cg = %s_cg ./ nn_cg;
"""
cmd2dView = """
figure(%i); patch('vertices',%s_cr,'faces',tri_%s,'FaceVertexCData',%s_cr,'FaceColor','interp','EdgeColor','none'); title('%s');
%%for average cg interpolant can also use
%%tmp = name_x_cg; tmp(:,3) = name_cg;
%%patch('vertices',tmp,'faces',tri_name_cg,'FaceVertexCData',name_cg,'FaceColor','interp','EdgeColor','none');
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_xg,%s_yg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%%note, uses average of duplicate values
%s_g = griddata(%s_x(:,1),%s_x(:,2),%s,%s_xg,%s_yg);
"""
#3d
cmd3dData = """
nNodes = max(max(tri_%s_cg)); %s_cg = zeros(nNodes,1); nn_cg = zeros(nNodes,1);
nElements = size(tri_%s_cg,1); nDOF_element = size(tri_%s_cg,2);
for eN = 1:nElements
for i = 1:nDOF_element
I = tri_%s_cg(eN,i);
%s_cg(I) = %s_cg(I) + %s(tri_%s(eN,i));
nn_cg(I) = nn_cg(I) + 1.;
end
end
%s_cg = %s_cg ./ nn_cg;
"""
cmd3dView = """
figure(%i); patch('vertices',%s_cr,'faces',tri_%s,'FaceVertexCData',%s,'FaceColor','interp','EdgeColor','none'); title('%s');
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2)) ; min(%s_x(:,3)) max(%s_x(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_xg,%s_yg,%s_zg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%%note, uses average of duplicate values
%s_g = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s,%s_xg,%s_yg,%s_zg);
"""
import numpy
if title is None:
title = name
nNodes_global = nodeArray.shape[0]; nElements_global = l2g.shape[0]
nNodes_element= elementNodesArray.shape[1]
nDOF_element = l2g.shape[1]
assert nDOF_element == nNodes_element
#treat like a dgp1 function with Lagrange basis
if storeMeshData:
cmdFile.write("%s_x = [ ... \n" % name)
for eN in range(nElements_global):
for nN_local in range(nNodes_element):
nN = elementNodesArray[eN,nN_local]
cmdFile.write("%g %g %g \n" % (nodeArray[nN,0],nodeArray[nN,1],nodeArray[nN,2]))
#
cmdFile.write("];")
cmdFile.write("%s_x_cg = [ ... \n" % name)
for nN in range(nNodes_global):
cmdFile.write("%g %g %g \n" % (nodeArray[nN,0],nodeArray[nN,1],nodeArray[nN,2]))
#
cmdFile.write("];")
#
cmdFile.write("tri_%s = [ ... \n" % name)
for eN in range(nElements_global):
for i in range(nDOF_element):#assumes laid out line element nodes
cmdFile.write(" %i " % (eN*nNodes_element+i+1))
cmdFile.write("; \n ")
#
cmdFile.write("];")
#
#provide CG connectivity
cmdFile.write("tri_%s_cg = [ ... \n" % name)
for eN in range(nElements_global):
for i in range(nDOF_element):#assumes laid out line element nodes
cmdFile.write(" %i " % (elementNodesArray[eN,i]+1))
cmdFile.write("; \n ")
#
cmdFile.write("];")
#
#dofs
cmdFile.write("%s = [ ... \n" % name)
#u(vertex_i) = u^i(1-nSpace) + \sum_{j \ne i} u^j where u^j is local dof j
if nSpace == 1:
for eN in range(nElements_global):
#dof associated with face id, so opposite usual C0P1 ordering here
cmdFile.write(" %g \n" % u_dof[l2g[eN,1]])
cmdFile.write(" %g \n" % u_dof[l2g[eN,0]])
#
elif nSpace == 2:
nodeVal = numpy.zeros(3,'d')
for eN in range(nElements_global):
nodeVal *= 0.0
#assume vertex associated with face across from it
nodeVal[0] = u_dof[l2g[eN,1]]
nodeVal[0]+= u_dof[l2g[eN,2]]
nodeVal[0]-= u_dof[l2g[eN,0]]
nodeVal[1] = u_dof[l2g[eN,0]]
nodeVal[1]+= u_dof[l2g[eN,2]]
nodeVal[1]-= u_dof[l2g[eN,1]]
nodeVal[2] = u_dof[l2g[eN,0]]
nodeVal[2]+= u_dof[l2g[eN,1]]
nodeVal[2]-= u_dof[l2g[eN,2]]
cmdFile.write(" %g \n %g \n %g \n " % (nodeVal[0],nodeVal[1],nodeVal[2]))
#
else:
for eN in range(nElements_global):
for i in range(nNodes_element):
nodalVal = u_dof[l2g[eN,i]]*(1.0-float(nSpace)) + sum([u_dof[l2g[eN,j]] for j in range(nDOF_element) if j != i])
cmdFile.write(" %g \n " % nodeVal)
#
#
#
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
cmd = cmd2dData % (name,name,name,name,
name,name,
name,name,
name,
name,name,name,name,
name,name)
cmdFile.write(cmd)
cmd = cmd2dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
cmd = cmd3dData % (name,name,
name,name,
name,
name,name,name,name,
name,name)
cmdFile.write(cmd)
cmd = cmd3dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
#
return nplotted
#
def viewScalar_MonomialDGPK(self,cmdFile,nSpace,nodeArray,elementNodesArray,
interpolationPoints,u_interpolationPoints,
name="u",storeMeshData=True,figureNumber=1,title=None):
# """
# given DG PK function with monomial basis
# generate a matlab representation that is as faithful as possible to
# the actual finite element function structure
# input is u values at interpolation points (not dof)
# Generates an array of triangulations of interpolation points on each element
# DG-PK output:
# element-wise list of interpolation points and local elementwise-connectivity matrices
# degrees of freedom at interpolation points
# scalar data is stored in
# name
# if storeMeshData = True, writes out
# name_x -- mesh vertices
# tri_name -- element-node representation
# returns number of figures actually plotted
# """
#1d
cmd1dData = """
nElements_global = %i; nPoints_element = %i;
tri_%s = [];
for eN = 1:nElements_global
[x_tmp,i_tmp] = sort(%s_x(nPoints_element*(eN-1)+1:nPoints_element*eN,1));
tmp = [];
for j = 1:nPoints_element-1
tmp = [tmp ; i_tmp(j) i_tmp(j+1)];
end
tri_%s = [tri_%s ; nPoints_element*(eN-1) + tmp];
end
%s_loc = %s_x; %s_loc(:,2) = %s;
"""
cmd1dView = """
figure(%i) ; patch('vertices',%s_loc,'faces',tri_%s,'FaceColor','none','EdgeColor','black'); title('%s');
"""
#2d
cmd2dData = """
nElements_global = %i; nPoints_element = %i;
tri_%s = [];
for eN = 1:nElements_global
tmp = delaunay(%s_x(nPoints_element*(eN-1)+1:nPoints_element*eN,1),...
%s_x(nPoints_element*(eN-1)+1:nPoints_element*eN,2));
tri_%s = [tri_%s ; nPoints_element*(eN-1)+tmp];
end
%s_loc = %s_x; %s_loc(:,3) = %s;
"""
cmd2dView = """
figure(%i) ; patch('vertices',%s_loc,'faces',tri_%s,'FaceVertexCData',%s,'FaceColor','interp','EdgeColor','none'); title('%s');
"""
cmd2dGrid = """
nx = %i; ny = %i;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny;
[%s_xg,%s_yg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2));
%s_g = griddata(%s_x(:,1),%s_x(:,2),%s,%s_xg,%s_yg);
"""
#3d
cmd3dData = """
nElements_global = %i; nPoints_element = %i;
tri_%s = [];
for eN = 1:nElements_global
tmp = delaunay3(%s_x(nPoints_element*(eN-1)+1:nPoints_element*eN,1),...
%s_x(nPoints_element*(eN-1)+1:nPoints_element*eN,2),...
%s_x(nPoints_element*(eN-1)+1:nPoints_element*eN,3));
tri_%s = [tri_%s ; nPoints_element*(eN-1)+tmp];
end
%s_loc = %s_x; %s_loc(:,3) = %s;
"""
cmd3dView = """
%%good luck
figure(%i); patch('vertices',%s_x,'faces',tri_%s,'FaceVertexCData',%s,'FaceColor','none','EdgeColor','interp'); title('%s')
"""
cmd3dGrid = """
nx = %i; ny = %i; nz = %i ;
XYZ = [min(%s_x(:,1)) max(%s_x(:,1)) ; min(%s_x(:,2)) max(%s_x(:,2)) ; min(%s_x(:,3)) max(%s_x(:,3))];
dx = (XYZ(1,2)-XYZ(1,1))/nx; dy = (XYZ(2,2)-XYZ(2,1))/ny; dz = (XYZ(3,2)-XYZ(3,1))/nz;
[%s_xg,%s_yg,%s_zg] = meshgrid(XYZ(1,1):dx:XYZ(1,2),XYZ(2,1):dy:XYZ(2,2),XYZ(3,1):dz:XYZ(3,2));
%s_g = griddata3(%s_x(:,1),%s_x(:,2),%s_x(:,3),%s,%s_xg,%s_yg,%s_zg);
"""
nplotted = 0
if title is None:
title = name
nElements_global = interpolationPoints.shape[0]; nPoints_element = interpolationPoints.shape[1];
#if constants use DGP0
if nPoints_element == 1:
return self.viewScalar_DGP0(cmdFile,nSpace,nodeArray,elementNodesArray,l2g,u_dof,
name=name,storeMeshData=storeMeshData,
figureNumber=figureNumber,title=title)
assert nPoints_element > nSpace
if storeMeshData:
cmdFile.write("%s_x = [ ... \n" % name)
for eN in range(nElements_global):
for k in range(nPoints_element):
cmdFile.write("%g %g %g \n" % (interpolationPoints[eN,k,0],
interpolationPoints[eN,k,1],
interpolationPoints[eN,k,2]))
cmdFile.write("];")
cmdFile.write("%s = [ ... \n" % name)
for eN in range(nElements_global):
for k in range(nPoints_element):
cmdFile.write("%g \n" % u_interpolationPoints[eN,k])
cmdFile.write("];");
if nSpace == 1:
cmd = cmd1dData % (nElements_global,nPoints_element,
name,
name,
name,name,
name,name,name,name)
cmdFile.write(cmd)
cmd = cmd1dView % (figureNumber,name,name,title)
cmdFile.write(cmd)
nplotted = 1
elif nSpace == 2:
cmd = cmd2dData % (nElements_global,nPoints_element,
name,
name,name,
name,name,
name,name,name,name)
cmdFile.write(cmd)
cmd = cmd2dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd2dGrid % (self.ngrid[0],self.ngrid[1],
name,name,name,name,
name,name,
name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
else:
cmd = cmd3dData % (nElements_global,nPoints_element,
name,
name,name,name,
name,name,
name,name,name,name)
cmdFile.write(cmd)
cmd = cmd3dView % (figureNumber,name,name,name,title)
cmdFile.write(cmd)
cmd = cmd3dGrid % (self.ngrid[0],self.ngrid[1],self.ngrid[2],
name,name,name,name,name,name,
name,name,name,
name,name,name,name,name,name,name,name)
cmdFile.write(cmd)
nplotted = 1
return nplotted
#
|
erdc/proteus
|
proteus/Viewers.py
|
Python
|
mit
| 156,763
|
[
"VTK"
] |
3209667b1c8c9bd8b2a9281c6f9c248b786df36805ee90650b7ab7323e5387d1
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
import visvis as vv
import numpy as np
def kde(data, bins=None, kernel=None, **kwargs):
""" kde(a, bins=None, range=None, **kwargs)
Make a kernerl density estimate plot of the data. This is like a
histogram, but produces a smoother result, thereby better represening
the probability density function.
See the vv.StatData for more statistics on data.
Parameters
----------
a : array_like
The data to calculate the historgam of.
bins : int (optional)
The number of bins. If not given, the best number of bins is
determined automatically using the Freedman-Diaconis rule.
kernel : float or sequence (optional)
The kernel to use for distributing the values. If a scalar is given,
a Gaussian kernel with a sigma equal to the given number is used.
If not given, the best kernel is chosen baded on the number of bins.
kwargs : keyword arguments
These are given to the plot function.
"""
# Get stats
from visvis.processing.statistics import StatData
stats = StatData(data)
# Get kde
xx, values = stats.kde(bins, kernel)
# Plot
return vv.plot(xx, values, **kwargs)
if __name__ == '__main__':
vv.clf()
data = np.random.normal(7,2,size=(100,100))
b = vv.kde(data, lc='r')
|
pbfy0/visvis
|
functions/kde.py
|
Python
|
bsd-3-clause
| 1,526
|
[
"Gaussian"
] |
3df7cafaece06c0a8d37ce4f4eef2b3c85c0ea8581a45c0265b2db008c7632ce
|
########################################################################
# $HeadURL$
# File : CPUNormalization.py
# Author : Ricardo Graciani
########################################################################
""" DIRAC Workload Management System Client module that encapsulates all the
methods necessary to handle CPU normalization
"""
__RCSID__ = "$Id$"
from DIRAC.Core.Utilities.SiteCEMapping import getQueueInfo
from DIRAC import S_OK, S_ERROR
import os, random
from DIRAC import gConfig, gLogger, S_OK, S_ERROR
from DIRAC.Core.Utilities.SiteCEMapping import getQueueInfo
# TODO: This should come from some place in the configuration
NORMALIZATIONCONSTANT = 60. / 250. # from minutes to seconds and from SI00 to HS06 (ie min * SI00 -> sec * HS06 )
UNITS = { 'HS06': 1. , 'SI00': 1. / 250. }
def queueNormalizedCPU( ceUniqueID ):
""" Report Normalized CPU length of queue
"""
result = getQueueInfo( ceUniqueID )
if not result['OK']:
return result
ceInfoDict = result['Value']
benchmarkSI00 = ceInfoDict['SI00']
maxCPUTime = ceInfoDict['maxCPUTime']
# For some sites there are crazy values in the CS
maxCPUTime = max( maxCPUTime, 0 )
maxCPUTime = min( maxCPUTime, 86400 * 12.5 )
if maxCPUTime and benchmarkSI00:
normCPUTime = NORMALIZATIONCONSTANT * maxCPUTime * benchmarkSI00
else:
if not benchmarkSI00:
subClusterUniqueID = ceInfoDict['SubClusterUniqueID']
return S_ERROR( 'benchmarkSI00 info not available for %s' % subClusterUniqueID )
if not maxCPUTime:
return S_ERROR( 'maxCPUTime info not available' )
return S_OK( normCPUTime )
def getQueueNormalization( ceUniqueID ):
""" Report Normalization Factor applied by Site to the given Queue
"""
result = getQueueInfo( ceUniqueID )
if not result['OK']:
return result
ceInfoDict = result['Value']
subClusterUniqueID = ceInfoDict['SubClusterUniqueID']
benchmarkSI00 = ceInfoDict['SI00']
if benchmarkSI00:
return S_OK( benchmarkSI00 )
else:
return S_ERROR( 'benchmarkSI00 info not available for %s' % subClusterUniqueID )
#errorList.append( ( subClusterUniqueID , 'benchmarkSI00 info not available' ) )
#exitCode = 3
def __getQueueNormalization( queueCSSection, siteCSSEction ):
""" Query the CS and return the Normalization
"""
benchmarkSI00Option = '%s/%s' % ( queueCSSection, 'SI00' )
benchmarkSI00 = gConfig.getValue( benchmarkSI00Option, 0.0 )
if not benchmarkSI00:
benchmarkSI00Option = '%s/%s' % ( siteCSSEction, 'SI00' )
benchmarkSI00 = gConfig.getValue( benchmarkSI00Option, 0.0 )
return benchmarkSI00
def __getMaxCPUTime( queueCSSection ):
""" Query the CS and return the maxCPUTime
"""
maxCPUTimeOption = '%s/%s' % ( queueCSSection, 'maxCPUTime' )
maxCPUTime = gConfig.getValue( maxCPUTimeOption, 0.0 )
# For some sites there are crazy values in the CS
maxCPUTime = max( maxCPUTime, 0 )
maxCPUTime = min( maxCPUTime, 86400 * 12.5 )
return maxCPUTime
def getCPUNormalization( reference = 'HS06', iterations = 1 ):
""" Get Normalized Power of the current CPU in [reference] units
"""
if reference not in UNITS:
return S_ERROR( 'Unknown Normalization unit %s' % str( reference ) )
try:
max( min( int( iterations ), 10 ), 1 )
except ( TypeError, ValueError ), x :
return S_ERROR( x )
# This number of iterations corresponds to 250 HS06 seconds
n = int( 1000 * 1000 * 12.5 )
calib = 250.0 / UNITS[reference]
m = 0L
m2 = 0L
p = 0
p2 = 0
# Do one iteration extra to allow CPUs with variable speed
for i in range( iterations + 1 ):
if i == 1:
start = os.times()
# Now the iterations
for _j in range( n ):
t = random.normalvariate( 10, 1 )
m += t
m2 += t * t
p += t
p2 += t * t
end = os.times()
cput = sum( end[:4] ) - sum( start[:4] )
wall = end[4] - start[4]
if not cput:
return S_ERROR( 'Can not get used CPU' )
return S_OK( {'CPU': cput, 'WALL':wall, 'NORM': calib * iterations / cput, 'UNIT': reference } )
def getCPUTime( CPUNormalizationFactor ):
""" Trying to get CPUTime (in seconds) from the CS. The default is a (low) 10000s.
This is a generic method, independent from the middleware of the resource.
"""
CPUTime = gConfig.getValue( '/LocalSite/CPUTimeLeft', 0 )
if CPUTime:
# This is in HS06sseconds
# We need to convert in real seconds
CPUTime = CPUTime / int( CPUNormalizationFactor )
else:
# now we know that we have to find the CPUTimeLeft by looking in the CS
gridCE = gConfig.getValue( '/LocalSite/GridCE' )
CEQueue = gConfig.getValue( '/LocalSite/CEQueue' )
if not CEQueue:
# we have to look for a CEQueue in the CS
# A bit hacky. We should better profit from something generic
gLogger.warn( "No CEQueue in local configuration, looking to find one in CS" )
siteName = gConfig.getValue( '/LocalSite/Site' )
queueSection = '/Resources/Sites/%s/%s/CEs/%s/Queues' % ( siteName.split( '.' )[0], siteName, gridCE )
res = gConfig.getSections( queueSection )
if not res['OK']:
raise RuntimeError( res['Message'] )
queues = res['Value']
CPUTimes = []
for queue in queues:
CPUTimes.append( gConfig.getValue( queueSection + '/' + queue + '/maxCPUTime', 10000 ) )
cpuTimeInMinutes = min( CPUTimes )
# These are (real, wall clock) minutes - damn BDII!
CPUTime = int( cpuTimeInMinutes ) * 60
else:
queueInfo = getQueueInfo( '%s/%s' % ( gridCE, CEQueue ) )
if not queueInfo['OK'] or not queueInfo['Value']:
gLogger.warn( "Can't find a CE/queue, defaulting CPUTime to 10000" )
CPUTime = 10000
else:
queueCSSection = queueInfo['Value']['QueueCSSection']
# These are (real, wall clock) minutes - damn BDII!
cpuTimeInMinutes = gConfig.getValue( '%s/maxCPUTime' % queueCSSection )
CPUTime = int( cpuTimeInMinutes ) * 60
return CPUTime
|
sposs/DIRAC
|
WorkloadManagementSystem/Client/CPUNormalization.py
|
Python
|
gpl-3.0
| 5,975
|
[
"DIRAC"
] |
7cdfcdc2c5b95964c8447c276ba5d6dd0949ab97f1b9bb41697a16aa3b2169e2
|
#!/usr/bin/env python
from collections import namedtuple
from ase.data import covalent_radii, atomic_numbers, vdw_radii
from ase.structure import molecule; molecule
from ase.io import read; read
import numpy
numpy.seterr(all='raise')
class VSEPR:
def __init__(self, atoms, bonds, angles=[], nonbonded=[]):
self.bonds = bonds
self.angles = connect_angles(bonds)
if nonbonded == 'auto':
self.nonbonded = connect_nonbonded(atoms, self.angles, 3.0)
else:
self.nonbonded = nonbonded
self.atom_types = determine_atom_types(atoms, bonds)
self.force_calls = 0
self.atoms = None
def get_potential_energy(self, atoms=None, force_consistent=False):
if self.calculation_required(atoms, "energy"):
self.atoms = atoms.copy()
self.calculate()
return self.u
def get_forces(self, atoms):
if self.calculation_required(atoms, "forces"):
self.atoms = atoms.copy()
self.calculate()
return self.f.copy()
def get_stress(self, atoms):
raise NotImplementedError
def calculation_required(self, atoms, quantities):
if atoms != self.atoms or self.atoms == None:
return True
if self.f == None or self.u == None or atoms == None:
return True
return False
def set_atoms(self, atoms):
pass
def calculate(self):
u, f = force_field(self.atoms,
self.atom_types,
self.bonds,
self.angles,
self.nonbonded)
self.u = u
self.f = f
self.force_calls += 1
def bond_stretch_parameter(*atom_types):
key = ''.join(sorted([atom_types[0].symbol, atom_types[1].symbol]))
# Bond stretch force constants in eV/Ang^2.
k_ij = {
'X' : 25.0,
'CH' : 32.0,
'CC' : 23.0,
'HO' : 30.0,
}
r_ij = {
'AuN' : 2.336,
'CN' : 1.491,
'HN' : 1.026,
'CH' : 1.109,
}
if key in k_ij:
k_r = k_ij[key]
else:
k_r = k_ij['X']
if key in r_ij:
r_eq = r_ij[key]
else:
za = atomic_numbers[atom_types[0].symbol]
zb = atomic_numbers[atom_types[1].symbol]
r_eq = covalent_radii[za] + covalent_radii[zb]
return r_eq, k_r
def nonbonded_parameter(*atom_types):
zi = atomic_numbers[atom_types[0].symbol]
zj = atomic_numbers[atom_types[1].symbol]
if zi == 'N' and zj == 'N':
return 4.5, 1e-3
r_vdw = 1.1*(vdw_radii[zi] + vdw_radii[zj])
C6 = {
'H' : 0.00086728,
'C' : 0.0052037,
'O' : 0.0086728,
'N' : 0.0069383,
'Au' : 0.007,
'X' : 0.007,
}
if atom_types[0].symbol in C6:
C6_i = C6[atom_types[0].symbol]
else:
C6_i = C6['X']
if atom_types[1].symbol in C6:
C6_j = C6[atom_types[1].symbol]
else:
C6_j = C6['X']
C6_ij = numpy.sqrt(C6_i * C6_j)
return r_vdw, C6_ij
def angle_bending_parameter(*atom_types):
hybridization = atom_types[1].hybridization
theta_eq = { 'sp' : 180.0 * numpy.pi/180.0,
'sp2' : 120.0 * numpy.pi/180.0,
'sp3' : 109.5 * numpy.pi/180.0 }[hybridization]
key = ''.join([ t.symbol for t in atom_types ])
# Bond bending force constants in eV/radian^2.
k_ijk = {
'XXX' : 100e-5*(180.0/numpy.pi)**2,
'HCH' : 147e-5*(180.0/numpy.pi)**2,
'CCH' : 98e-5*(180.0/numpy.pi)**2,
'HOH' : 100e-5*(180.0/numpy.pi)**2,
'CCC' : 85e-5*(180.0/numpy.pi)**2,
}
if key in k_ijk:
k_theta = k_ijk[key]
else:
k_theta = k_ijk['XXX']
return theta_eq, k_theta
def force_field(atoms, atom_types, bonds, angles, nonbonded):
total_energy = 0.0
forces = numpy.zeros((len(atoms), 3))
for bond in bonds:
i,j = bond
r = atoms.get_distance(i, j, mic=True)
r_eq, k_r = bond_stretch_parameter(atom_types[i], atom_types[j])
total_energy += 0.5 * k_r * (r - r_eq)**2
force = k_r * (r - r_eq)
diff_r = atoms.positions[i] - atoms.positions[j]
diff_r = diff_r/numpy.linalg.norm(diff_r)
forces[i] -= force*diff_r
forces[j] += force*diff_r
for angle in angles:
i,j,k = angle
theta_eq, k_theta = angle_bending_parameter(atom_types[i],
atom_types[j],
atom_types[k])
diff_r1 = atoms.positions[i] - atoms.positions[j]
r1_sq = numpy.dot(diff_r1, diff_r1)
r1 = numpy.sqrt(r1_sq)
diff_r2 = atoms.positions[k] - atoms.positions[j]
r2_sq = numpy.dot(diff_r2, diff_r2)
r2 = numpy.sqrt(r2_sq)
c = numpy.dot(diff_r1, diff_r2)
c /= r1*r2
if (c > 1.0): c = 1.0
if (c < - 1.0): c = -1.0
s = numpy.sqrt(1.0 - c**2)
if (s < 1e-3): s = 1e-3
s = 1.0/s
dtheta = numpy.arccos(c) - theta_eq
tk = k_theta * dtheta
total_energy += tk*dtheta
a = -2.0 * tk * s
a11 = a*c / r1_sq
a12 = -a / (r1*r2)
a22 = a*c / r2_sq
f1 = numpy.zeros(3)
f3 = numpy.zeros(3)
f1[0] = a11*diff_r1[0] + a12*diff_r2[0]
f1[1] = a11*diff_r1[1] + a12*diff_r2[1]
f1[2] = a11*diff_r1[2] + a12*diff_r2[2]
f3[0] = a22*diff_r2[0] + a12*diff_r1[0];
f3[1] = a22*diff_r2[1] + a12*diff_r1[1];
f3[2] = a22*diff_r2[2] + a12*diff_r1[2];
forces[i] += f1
forces[j] -= f1 + f3
forces[k] += f3
for i,j in nonbonded:
r = atoms.get_distance(i, j, mic=True)
sigma, epsilon = nonbonded_parameter(atom_types[i], atom_types[j])
total_energy += 4*epsilon*((sigma/r)**12-(sigma/r)**6)
force = 4*epsilon*(12*(sigma/r)**13-6*(sigma/r)**7)
r_diff = atoms.positions[i] - atoms.positions[j]
forces[i] += force*r_diff/r
forces[j] -= force*r_diff/r
return total_energy, forces
AtomType = namedtuple('AtomType', ['symbol', 'hybridization'])
def determine_atom_types(atoms, bonds):
valence_electrons = numpy.zeros(len(atoms), int)
for i in xrange(len(atoms)):
z = atoms[i].number
if z <= 2:
valence_electrons[i] = z
elif z <= 10:
valence_electrons[i] = z - 2
elif z <= 18:
valence_electrons[i] = z - 10
bond_orders = numpy.zeros(len(atoms), int)
coordination_numbers = numpy.zeros(len(atoms), int)
# Account for single bonds.
for bond in bonds:
bond_orders[bond] += 1
coordination_numbers[bond] += 1
i,j = bond
# If we bond to a metal.
if valence_electrons[i] == 0:
valence_electrons[j] -= 1
elif valence_electrons[j] == 0:
valence_electrons[i] -= 1
def satisifies_octet_rule(i):
if atoms[i].number <= 2:
shell = 2
else:
shell = 8
if valence_electrons[i] + bond_orders[i] < shell:
return False
else:
return True
# Account for double bonds.
for bond in bonds:
if satisifies_octet_rule(bond[0]): continue
if satisifies_octet_rule(bond[1]): continue
bond_orders[bond] += 1
# Account for triple bonds.
for bond in bonds:
if satisifies_octet_rule(bond[0]): continue
if satisifies_octet_rule(bond[1]): continue
bond_orders[bond] += 1
atom_types = []
for i in xrange(len(atoms)):
if valence_electrons[i] == 0:
atom_types.append(AtomType(atoms[i].symbol, 'metal'))
continue
bond_order = bond_orders[i]
if bond_order == 0 and atoms[i].number < 20:
hybrid = 'undefined'
atom_types.append(AtomType(atoms[i].symbol, 'undefined'))
continue
unpaired_electrons = valence_electrons[i] - bond_order
lone_pairs = unpaired_electrons/2.0
try:
hybrid = { 1:'s',
2:'sp',
3:'sp2',
4:'sp3' }[coordination_numbers[i]+lone_pairs]
except KeyError:
hybrid = 'sp3'
#print atoms[i]
#for bond in bonds:
# if i in bond: print bond
#raise ValueError
atom_type = AtomType(atoms[i].symbol, hybrid)
atom_types.append(atom_type)
return atom_types
def cutoff_distance(atom1, atom2, fudge_factor=1.2):
z1 = atom1.number
z2 = atom2.number
r_cut = fudge_factor*(covalent_radii[z1] + covalent_radii[z2])
return r_cut
def connect_bonds(atoms, indices=None, mask=None):
bonds = []
if indices is None:
indices = xrange(len(atoms))
if mask is not None:
assert(len(atoms) == len(mask))
indices = [ i for i in xrange(len(mask)) if mask[i] == True ]
for ii in xrange(len(indices)):
for jj in xrange(ii+1, len(indices)):
i = indices[ii]
j = indices[jj]
r_cut = cutoff_distance(atoms[i], atoms[j])
r = atoms.get_distance(i, j, mic=True)
if r < r_cut:
bonds.append([i,j])
return bonds
def connect_angles(bonds):
angles = []
for i in xrange(len(bonds)):
for j in xrange(i+1, len(bonds)):
if not (bonds[i][0] in bonds[j] or bonds[i][1] in bonds[j]):
continue
bridge = set(bonds[i]) & set(bonds[j])
angle = [ list(set(bonds[i]) - bridge)[0],
list(bridge)[0],
list(set(bonds[j]) - bridge)[0] ]
angles.append(angle)
return angles
def connect_nonbonded(atoms, angles, r_cut=20.0, mask=None):
nonbonded = []
for i in xrange(len(atoms)):
if not mask is None and mask[i] == False: continue
for j in xrange(i+1, len(atoms)):
if atoms[i].number > 20 and atoms[j].number > 20:
continue
skip = False
for angle in angles:
if i in angle and j in angle:
skip = True
break
if skip: continue
r = atoms.get_distance(i,j,mic=True)
if r < r_cut:
nonbonded.append([i,j])
return nonbonded
def connect_analysis(atoms):
print 'Connect analysis for %s' % atoms.get_chemical_formula('reduce')
bonds = connect_bonds(atoms)
angles = connect_angles(bonds)
nonbonded = connect_nonbonded(atoms, angles)
atom_types = determine_atom_types(atoms, bonds)
from pprint import pprint
print 'bond pairs:', len(bonds)
pprint(bonds)
print
print 'angles triples:', len(angles)
pprint(angles)
print
print 'nonbonded pairs:', len(nonbonded)
pprint(nonbonded)
print
print 'atom types:'
for i,atom_type in enumerate(atom_types):
print '%4i: Element: %2s type: %s' % (i, atom_type.symbol, atom_type.hybridization)
print
print 'Force Field Parameters'
print
print 'Bond Terms'
already_seen = []
for bond in bonds:
i,j = bond
if {atoms[i].symbol, atoms[j].symbol} in already_seen:
continue
else:
already_seen.append({atoms[i].symbol, atoms[j].symbol})
r_eq, k_bond = bond_stretch_parameter(atom_types[i], atom_types[j])
print '%s-%s: r_eq=%.3f Ang k_bond=%.3f eV/Ang^2' % \
(atoms[i].symbol, atoms[j].symbol, r_eq, k_bond)
print
print 'Angle Terms'
already_seen = []
for angle in angles:
i,j,k = angle
if {atoms[i].symbol, atoms[j].symbol, atoms[k].symbol} in already_seen:
continue
else:
already_seen.append({atoms[i].symbol, atoms[j].symbol, atoms[k].symbol})
theta_eq, k_theta= angle_bending_parameter(atom_types[i], atom_types[j], atom_types[k])
print '%s-%s-%s: theta_eq=%.3f deg k_theta=%.3e eV/deg^2' % \
(atoms[i].symbol, atoms[j].symbol, atoms[k].symbol,
theta_eq*180/numpy.pi, k_theta*(numpy.pi/180)**2)
def demo_H2O():
atoms = molecule('H2O')
connect_analysis(atoms)
def demo_C2H4():
atoms = molecule('C2H4')
connect_analysis(atoms)
def demo_benzene():
atoms = read('benzene.xyz')
connect_analysis(atoms)
def demo_pamam():
atoms = read('PAMAM-monomer.xyz')
connect_analysis(atoms)
def demo_Au147_pamam():
atoms = read('CONTCAR')
connect_analysis(atoms)
def main():
#demo_C2H4()
#demo_benzene()
#demo_pamam()
demo_Au147_pamam()
#from ase.constraints import FixAtoms
#mask = [ atom.symbol == 'Au' for atom in atoms ]
#atoms.set_constraint(FixAtoms(mask=mask))
#atoms.set_calculator(VSEPR(atoms, nonbonded=True))
#from ase.optimize import LBFGS, FIRE; LBFGS; FIRE
#opt = FIRE(atoms, trajectory='opt.traj')
#opt.run(fmax=1e-3, steps=1000)
if __name__ == '__main__':
main()
|
SamChill/ligandizer
|
VSEPR.py
|
Python
|
bsd-2-clause
| 13,136
|
[
"ASE"
] |
3df7e4ccc51b86ef3baeb30fc08a71ee8d80e4690074f43beffbf1baf9e3f2ed
|
# -*- coding: utf-8 -*-
"""
Created on 28 Nov 2013
@author: Kimon Tsitsikas
Copyright © 2012-2013 Kimon Tsitsikas, Delmic
This file is part of Odemis.
Odemis is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License version 2 as published by the Free
Software Foundation.
Odemis 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
Odemis. If not, see http://www.gnu.org/licenses/.
"""
from __future__ import division
from itertools import compress
import logging
import math
from numpy import fft
from numpy import histogram
from numpy import unravel_index
import numpy
from odemis import model
import operator
from scipy.spatial import cKDTree
import scipy.ndimage as ndimage
import scipy.ndimage.filters as filters
from ..align import transform
MAX_STEPS_NUMBER = 100 # How many steps to perform in coordinates matching
SHIFT_THRESHOLD = 0.04 # When to still perform the shift (percentage)
DIFF_NUMBER = 0.95 # Number of values that should be within the allowed difference
def DivideInNeighborhoods(data, number_of_spots, scale, sensitivity_limit=100):
"""
Given an image that includes N spots, divides it in N subimages with each of them
to include one spot. Briefly, it filters the image, finds the N “brightest” spots
and crops the region around them generating the subimages. This process is repeated
until image division is feasible.
data (model.DataArray): 2D array containing the intensity of each pixel
number_of_spots (int,int): The number of CL spots
scale (float): Distance between spots in optical grid (in pixels)
sensitivity_limit (int): Limit of sensitivity
returns subimages (List of DataArrays): One subimage per spot
subimage_coordinates (List of tuples): The coordinates of the center of each
subimage with respect to the overall image
"""
# Denoise
filtered_image = ndimage.median_filter(data, 3)
# Bold spots
# Third parameter must be a length in pixels somewhat larger than a typical
# spot
filtered_image = _BandPassFilter(filtered_image, 1, 20)
image = model.DataArray(filtered_image, data.metadata)
avg_intensity = numpy.average(image)
spot_factor = 10
step = 1
sensitivity = 4
# After filtering based on optical scale there is no need to adjust
# filter window size
filter_window_size = 8
# Increase sensitivity until expected number of spots is detected
while sensitivity <= sensitivity_limit:
subimage_coordinates = []
subimages = []
i_max, j_max = unravel_index(image.argmax(), image.shape)
i_min, j_min = unravel_index(image.argmin(), image.shape)
max_diff = image[i_max, j_max] - image[i_min, j_min]
data_max = filters.maximum_filter(image, filter_window_size)
data_min = filters.minimum_filter(image, filter_window_size)
# Determine threshold
i = sensitivity
threshold = max_diff / i
# Filter the parts of the image with variance in intensity greater
# than the threshold
maxima = (image == data_max)
diff = ((data_max - data_min) > threshold)
maxima[diff == 0] = 0
labeled, num_objects = ndimage.label(maxima)
slices = ndimage.find_objects(labeled)
(x_center_last, y_center_last) = (-10, -10)
# Go through these parts and crop the subimages based on the neighborhood_size
# value
for dy, dx in slices:
x_center = (dx.start + dx.stop - 1) / 2
y_center = (dy.start + dy.stop - 1) / 2
# Make sure we don't detect spots on the top of each other
tab = tuple(map(operator.sub, (x_center_last, y_center_last),
(x_center, y_center)))
subimage = image[int(dy.start - 2.5):int(dy.stop + 2.5),
int(dx.start - 2.5):int(dx.stop + 2.5)]
if subimage.shape[0] == 0 or subimage.shape[1] == 0:
continue
if (subimage > spot_factor * avg_intensity).sum() < 6:
continue
# if spots detected too close keep the brightest one
if (len(subimages) > 0) and (math.hypot(tab[0], tab[1]) < (scale / 2)):
if numpy.sum(subimage) > numpy.sum(subimages[len(subimages) - 1]):
subimages.pop()
subimage_coordinates.pop()
subimage_coordinates.append((x_center, y_center))
subimages.append(subimage)
else:
subimage_coordinates.append((x_center, y_center))
subimages.append(subimage)
(x_center_last, y_center_last) = (x_center, y_center)
# Take care of outliers
expected_spots = numpy.prod(number_of_spots)
clean_subimages, clean_subimage_coordinates = FilterOutliers(image, subimages,
subimage_coordinates,
expected_spots)
if len(clean_subimages) >= numpy.prod(number_of_spots):
break
if sensitivity > 4:
step = 4
sensitivity += step
return clean_subimages, clean_subimage_coordinates
def ReconstructCoordinates(subimage_coordinates, spot_coordinates):
"""
Given the coordinates of each subimage as also the coordinates of the spot into it,
generates the coordinates of the spots with respect to the overall image.
subimage_coordinates (List of tuples): The coordinates of the
center of each subimage with
respect to the overall image
spot_coordinates (List of tuples): Coordinates of spot centers relative to
the center of the subimage
returns (List of tuples): Coordinates of spots in optical image
"""
optical_coordinates = []
for ta, tb in zip(subimage_coordinates, spot_coordinates):
t = tuple(a + b for a, b in zip(ta, tb))
optical_coordinates.append(t)
return optical_coordinates
def FilterOutliers(image, subimages, subimage_coordinates, expected_spots):
"""
It removes subimages that contain outliers (e.g. cosmic rays).
image (model.DataArray): 2D array containing the intensity of each pixel
subimages (List of model.DataArray): List of 2D arrays containing pixel intensity
returns (List of model.DataArray): List of subimages without the ones containing
outliers
(List of tuples): The coordinates of the center of each subimage with respect
to the overall image
"""
number_of_subimages = len(subimages)
clean_subimages = []
clean_subimage_coordinates = []
filtered_subimages = []
filtered_subimage_coordinates = []
for i in xrange(number_of_subimages):
hist, bin_edges = histogram(subimages[i], bins=10)
# Remove subimage if its histogram implies a cosmic ray
hist_list = hist.tolist()
if hist_list.count(0) < 6:
clean_subimages.append(subimages[i])
clean_subimage_coordinates.append(subimage_coordinates[i])
# If we removed more than 3 subimages give up and return the initial list
# This is based on the assumption that each image would contain at maximum
# 3 cosmic rays.
if (((len(subimages) - len(clean_subimages)) > 3) or (len(clean_subimages) == 0)):
clean_subimages = subimages
clean_subimage_coordinates = subimage_coordinates
# If we still have more spots than expected we discard the ones
# with "stranger" distances from their closest spots. Only applied
# if we have an at least 2x2 grid.
if (expected_spots >= 4) and (len(clean_subimage_coordinates) > expected_spots):
points = numpy.array(clean_subimage_coordinates)
tree = cKDTree(points, 5)
distance, index = tree.query(clean_subimage_coordinates, 5)
list_distance = numpy.array(distance)
avg_1 = numpy.average(list_distance[:, 1])
avg_2 = numpy.average(list_distance[:, 2])
avg_3 = numpy.average(list_distance[:, 3])
avg_4 = numpy.average(list_distance[:, 4])
diff_avg_list = numpy.array(list_distance[:, 1:5])
for i in xrange(0, len(list_distance), 1):
diff_avg = [abs(list_distance[i, 1] - avg_1),
abs(list_distance[i, 2] - avg_2),
abs(list_distance[i, 3] - avg_3),
abs(list_distance[i, 4] - avg_4)]
diff_avg_list[i] = diff_avg
var_1 = numpy.average(diff_avg_list[:, 0])
var_2 = numpy.average(diff_avg_list[:, 1])
var_3 = numpy.average(diff_avg_list[:, 2])
var_4 = numpy.average(diff_avg_list[:, 3])
for i in xrange(len(clean_subimage_coordinates)):
if (diff_avg_list[i, 0] <= var_1
or diff_avg_list[i, 1] <= var_2
or diff_avg_list[i, 2] <= var_3
or diff_avg_list[i, 3] <= var_4):
filtered_subimages.append(clean_subimages[i])
filtered_subimage_coordinates.append(clean_subimage_coordinates[i])
return filtered_subimages, filtered_subimage_coordinates
return clean_subimages, clean_subimage_coordinates
def MatchCoordinates(input_coordinates, electron_coordinates, guess_scale, max_allowed_diff):
"""
Orders the list of spot coordinates of the grid in the electron image in order to
match the corresponding spot coordinates generated by FindCenterCoordinates.
input_coordinates (List of tuples): Coordinates of spots in optical image
electron_coordinates (List of tuples): Coordinates of spots in electron image
guess_scale (float): Guess scaling for the first transformation
max_allowed_diff (float): Maximum allowed difference in electron coordinates
returns (List of tuples): Ordered list of coordinates in electron image with respect
to the order in the electron image
(List of tuples): List of coordinates in optical image corresponding to the
ordered electron list
"""
# Remove large outliers
if len(input_coordinates) > 1:
optical_coordinates = _FindOuterOutliers(input_coordinates)
if len(optical_coordinates) > len(electron_coordinates):
optical_coordinates = _FindInnerOutliers(optical_coordinates)
else:
logging.warning("Cannot find overlay (only %s spot found).",
len(input_coordinates))
return [], []
# Informed guess
guess_coordinates = _TransformCoordinates(optical_coordinates, (0, 0), 0, (guess_scale, guess_scale))
# Overlay center
guess_center = numpy.mean(guess_coordinates, 0) - numpy.mean(electron_coordinates, 0)
transformed_coordinates = [(c[0] - guess_center[0], c[1] - guess_center[1]) for c in guess_coordinates]
max_wrong_points = math.ceil(0.5 * math.sqrt(len(electron_coordinates)))
for step in xrange(MAX_STEPS_NUMBER):
# Calculate nearest point
estimated_coordinates, index1, e_wrong_points, o_wrong_points, total_shift = _MatchAndCalculate(transformed_coordinates,
optical_coordinates,
electron_coordinates)
if not estimated_coordinates:
logging.warning("Failed to get any coordinate match")
return [], []
# Calculate successful
e_match_points = [not i for i in e_wrong_points]
o_match_points = [not i for i in o_wrong_points]
e_coord_exp = [estimated_coordinates[i] for i in compress(index1, e_match_points)]
e_coord_actual = list(compress(electron_coordinates, e_match_points))
# Calculate distance between the expected and found electron coordinates
coord_diff = []
for ta, tb in zip(e_coord_exp, e_coord_actual):
coord_diff.append(math.hypot(ta[0] - tb[0], ta[1] - tb[1]))
# Look at the worse distance, not including 5% outliers
sort_diff = sorted(coord_diff)
outlier_i = max(0, math.trunc(DIFF_NUMBER * len(sort_diff)) - 1)
max_diff = sort_diff[outlier_i]
if (max_diff < max_allowed_diff
and sum(e_wrong_points) <= max_wrong_points
and total_shift <= max_allowed_diff):
break
transformed_coordinates = estimated_coordinates
else:
logging.warning("Cannot find overlay: distance = %f px (> %f px), after %d steps.",
max_diff, max_allowed_diff, step + 1)
logging.warning("Optical coordinates found: %s", estimated_coordinates)
logging.warning("SEM coordinates distances: %s", sort_diff)
return [], []
# The ordered list gives for each electron coordinate the corresponding optical coordinates
ordered_coordinates_index = zip(index1, electron_coordinates)
ordered_coordinates_index.sort()
ordered_coordinates = []
for i in xrange(len(ordered_coordinates_index)):
ordered_coordinates.append(ordered_coordinates_index[i][1])
# Remove unknown coordinates
known_ordered_coordinates = list(compress(ordered_coordinates, e_match_points))
if len(optical_coordinates) == len(known_ordered_coordinates):
known_optical_coordinates = optical_coordinates
else:
known_optical_coordinates = list(compress(optical_coordinates, o_match_points))
return known_ordered_coordinates, known_optical_coordinates
def _KNNsearch(x_coordinates, y_coordinates):
"""
Applies K-nearest neighbors search to the lists x_coordinates and y_coordinates.
x_coordinates (List of tuples): List of coordinates
y_coordinates (List of tuples): List of coordinates
returns (List of integers): Contains the index of nearest neighbor in x_coordinates
for the corresponding element in y_coordinates
"""
points = numpy.array(x_coordinates)
tree = cKDTree(points)
distance, index = tree.query(y_coordinates)
list_index = numpy.array(index).tolist()
return list_index
def _TransformCoordinates(x_coordinates, translation, rotation, scale):
"""
Transforms the x_coordinates according to the parameters.
x_coordinates (List of tuples): List of coordinates
translation (Tuple of floats): Translation
rotation (float): Rotation in rad
scale (Tuple of floats): Scaling
returns (List of tuples): Transformed coordinates
"""
transformed_coordinates = []
for ta in x_coordinates:
# translation-scaling-rotation
translated = [a + t for a, t in zip(ta, translation)]
scaled = [t * s for t, s in zip(translated, scale)]
x, y = scaled
x_rotated = x * math.cos(-rotation) - y * math.sin(-rotation)
y_rotated = x * math.sin(-rotation) + y * math.cos(-rotation)
rotated = (x_rotated, y_rotated)
transformed_coordinates.append(rotated)
return transformed_coordinates
def _MatchAndCalculate(transformed_coordinates, optical_coordinates, electron_coordinates):
"""
Applies transformation to the optical coordinates in order to match electron coordinates and returns
the transformed coordinates. This function must be used recursively until the transformed coordinates
reach the required accuracy.
transformed_coordinates (List of tuples): List of transformed coordinates
optical_coordinates (List of tuples): List of optical coordinates
electron_coordinates (List of tuples): List of electron coordinates
returns estimated_coordinates (List of tuples): Estimated optical coordinates
index1 (List of integers): Indexes of nearest points in optical with respect to electron
e_wrong_points (List of booleans): Electron coordinates that have no proper match
o_wrong_points (List of booleans): Optical coordinates that have no proper match
total_shift (float): Calculated total shift
"""
index1 = _KNNsearch(transformed_coordinates, electron_coordinates)
# Sort optical coordinates based on the _KNNsearch output index
knn_points1 = [optical_coordinates[i] for i in index1]
index2 = _KNNsearch(electron_coordinates, transformed_coordinates)
# Sort electron coordinates based on the _KNNsearch output index
knn_points2 = [electron_coordinates[i] for i in index2]
# Sort index1 based on index2 and the opposite
o_index = [index1[i] for i in index2]
e_index = [index2[i] for i in index1]
transformed_range = range(len(transformed_coordinates))
electron_range = range(len(electron_coordinates))
# Coordinates that have no proper match (optical and electron)
o_wrong_points = [i != r for i, r in zip(o_index, transformed_range)]
o_match_points = [not i for i in o_wrong_points]
e_wrong_points = [i != r for i, r in zip(e_index, electron_range)]
e_match_points = [not i for i in e_wrong_points]
if (all(o_wrong_points) or all(e_wrong_points)):
# TODO: raise exception?
logging.warning("Cannot perform matching.")
return [], [], [], []
# Calculate the transform parameters for the correct electron_coordinates
move1, scale1, rotation1 = transform.CalculateTransform(
list(compress(electron_coordinates, e_match_points)),
list(compress(knn_points1, e_match_points)))
# Calculate the transform parameters for the correct optical_coordinates
move2, scale2, rotation2 = transform.CalculateTransform(
list(compress(knn_points2, o_match_points)),
list(compress(optical_coordinates, o_match_points)))
# Average between the two parameters
# TODO: use numpy.mean()
avg_move = ((move1[0] + move2[0]) / 2, (move1[1] + move2[1]) / 2)
avg_scale = ((scale1[0] + scale2[0]) / 2, (scale1[1] + scale2[1]) / 2)
avg_rotation = (rotation1 + rotation2) / 2
total_shift = 0
# Correct for shift if 'too many' points are wrong, with 'too many' defined by:
threshold = math.ceil(0.5 * math.sqrt(len(electron_coordinates)))
# If the number of wrong points is above threshold perform corrections
if sum(o_wrong_points) > threshold and sum(e_wrong_points) > threshold:
# Shift
electron_o_index2 = [electron_coordinates[i] for i in compress(index2, o_wrong_points)]
transformed_o_points = list(compress(transformed_coordinates, o_wrong_points))
o_wrong_diff = []
for ta, tb in zip(electron_o_index2, transformed_o_points):
o_wrong_diff.append((ta[0] - tb[0], ta[1] - tb[1]))
transformed_e_index1 = [transformed_coordinates[i] for i in compress(index1, e_wrong_points)]
electron_e_points = list(compress(electron_coordinates, e_wrong_points))
e_wrong_diff = []
for ta, tb in zip(transformed_e_index1, electron_e_points):
e_wrong_diff.append((ta[0] - tb[0], ta[1] - tb[1]))
mean_wrong_diff = numpy.mean(e_wrong_diff, 0) - numpy.mean(o_wrong_diff, 0)
avg_move = (avg_move[0] - (0.65 * mean_wrong_diff[0]) / avg_scale[0],
avg_move[1] - (0.65 * mean_wrong_diff[1]) / avg_scale[1])
total_shift = math.hypot((0.65 * mean_wrong_diff[0]) / avg_scale[0],
(0.65 * mean_wrong_diff[1]) / avg_scale[1])
# Angle
# Calculate angle with respect to its center, therefore move points towards center
electron_coordinates_vs_center = []
mean_electron_coordinates = numpy.mean(electron_coordinates, 0)
for ta in electron_coordinates:
# translation
translated = tuple(map(operator.sub, ta, mean_electron_coordinates))
electron_coordinates_vs_center.append(translated)
transformed_coordinates_vs_center = []
for tb in transformed_coordinates:
# translation
translated = tuple(map(operator.sub, tb, mean_electron_coordinates))
transformed_coordinates_vs_center.append(translated)
# Calculate the angle with its center for every point
angle_vect_electron = numpy.arctan2([float(i[0]) for i in electron_coordinates_vs_center], [float(i[1]) for i in electron_coordinates_vs_center])
angle_vect_transformed = numpy.arctan2([float(i[0]) for i in transformed_coordinates_vs_center], [float(i[1]) for i in transformed_coordinates_vs_center])
# Calculate the angle difference for the wrong electron_coordinates
angle_vect_transformed_e_index1 = [angle_vect_transformed[i] for i in compress(index1, e_wrong_points)]
angle_diff_electron_wrong = []
for x, y in zip(compress(angle_vect_electron, e_wrong_points), angle_vect_transformed_e_index1):
a = (x - y)
# Ensure the angle is between -Pi and Pi
a %= (2 * math.pi)
if a > math.pi:
a -= 2 * math.pi
angle_diff_electron_wrong.append(a)
# Calculate the angle difference for the wrong transformed_coordinates
angle_vect_electron_o_index2 = [angle_vect_electron[i] for i in compress(index2, o_wrong_points)]
angle_diff_transformed_wrong = []
for x, y in zip(compress(angle_vect_transformed, o_wrong_points), angle_vect_electron_o_index2):
a = (x - y)
# Ensure the angle is between -Pi and Pi
a %= (2 * math.pi)
if a > math.pi:
a -= 2 * math.pi
angle_diff_transformed_wrong.append(a)
# Apply correction
angle_correction = 0.5 * (numpy.mean(angle_diff_electron_wrong) - numpy.mean(angle_diff_transformed_wrong))
avg_rotation += angle_correction
# Perform transformation
estimated_coordinates = _TransformCoordinates(optical_coordinates, avg_move,
avg_rotation,
avg_scale)
index1 = _KNNsearch(estimated_coordinates, electron_coordinates)
index2 = _KNNsearch(electron_coordinates, estimated_coordinates)
e_index = [index2[i] for i in index1]
e_wrong_points = [i != r for i, r in zip(e_index, electron_range)]
if (all(e_wrong_points) or index1.count(index1[0]) == len(index1)):
logging.warning("Cannot perform matching..")
return [], [], [], []
return estimated_coordinates, index1, e_wrong_points, o_wrong_points, total_shift
def _FindOuterOutliers(x_coordinates):
"""
Removes large outliers from the optical coordinates.
x_coordinates (List of tuples): List of coordinates
returns (List of tuples): Coordinates without outer outliers
"""
# For each point, search for the 2 closest neighbors
points = numpy.array(x_coordinates)
tree = cKDTree(points, 2)
distance, index = tree.query(x_coordinates, 2)
list_distance = numpy.array(distance)
# Keep only the second ones because the first ones are the points themselves
sorted_distance = sorted(list_distance[:, 1])
outlier_value = 1.5 * sorted_distance[int(math.ceil(0.5 * len(sorted_distance)))]
no_outlier_index = list_distance[:, 1] < outlier_value
return list(compress(x_coordinates, no_outlier_index))
def _FindInnerOutliers(x_coordinates):
"""
Removes inner outliers from the optical coordinates. It assumes
that our grid is rectangular.
x_coordinates (List of tuples): List of coordinates
returns (List of tuples): Coordinates without inner outliers
"""
points = numpy.array(x_coordinates)
tree = cKDTree(points, 2)
distance, index = tree.query(x_coordinates, 2)
list_index = numpy.array(index)
counts = numpy.bincount(list_index[:, 1])
inner_outliers = numpy.argwhere(counts == numpy.amax(counts))
inner_outliers = inner_outliers.flatten().tolist()
inner_outlier = numpy.max(inner_outliers)
del x_coordinates[inner_outlier]
return x_coordinates
def _BandPassFilter(image, len_noise, len_object):
"""
bandpass filter implementation.
Source: http://physics-server.uoregon.edu/~raghu/particle_tracking.html
"""
b = len_noise
w = int(round(len_object))
N = 2 * w + 1
# Gaussian Convolution Kernel
sm = numpy.arange(0, N, dtype=numpy.float)
r = (sm - w) / (2 * b)
gx = numpy.power(math.e, -r ** 2) / (2 * b * math.sqrt(math.pi))
gx = numpy.reshape(gx, (gx.shape[0], 1))
gy = gx.conj().transpose()
# Boxcar average kernel, background
bx = numpy.zeros((1, N), numpy.float) + 1 / N
by = bx.conj().transpose()
# Convolution with the matrix and kernels
gxy = gx * gy
bxy = bx * by
kernel = fft.rfft2(gxy - bxy, image.shape)
res = fft.irfft2(fft.rfft2(image) * kernel)
arr_out = numpy.zeros((image.shape))
arr_out[w:-w, w:-w] = res[2 * w:, 2 * w:]
res = numpy.maximum(arr_out, 0)
return res
|
ktsitsikas/odemis
|
src/odemis/acq/align/coordinates.py
|
Python
|
gpl-2.0
| 25,638
|
[
"Gaussian"
] |
a96582a40f5b095429ce8bb27554e696e16fa57f2474325e11593c768f71dce3
|
#!/usr/bin/env python
from .._externals.srm import SRM
from .procrustes import procrustes
import numpy as np
from .format_data import format_data as formatter
from .._shared.helpers import memoize
import warnings
@memoize
def align(data, align='hyper', normalize=None, ndims=None, method=None,
format_data=True):
"""
Aligns a list of arrays
This function takes a list of high dimensional arrays and 'hyperaligns' them
to a 'common' space, or coordinate system following the approach outlined by
Haxby et al, 2011. Hyperalignment uses linear transformations (rotation,
reflection, translation, scaling) to register a group of arrays to a common
space. This can be useful when two or more datasets describe an identical
or similar system, but may not be in same coordinate system. For example,
consider the example of fMRI recordings (voxels by time) from the visual
cortex of a group of subjects watching the same movie: The brain responses
should be highly similar, but the coordinates may not be aligned.
Haxby JV, Guntupalli JS, Connolly AC, Halchenko YO, Conroy BR, Gobbini
MI, Hanke M, and Ramadge PJ (2011) A common, high-dimensional model of
the representational space in human ventral temporal cortex. Neuron 72,
404 -- 416. (used to implement hyperalignment, see https://github.com/PyMVPA/PyMVPA)
Brain Imaging Analysis Kit, http://brainiak.org. (used to implement Shared Response Model [SRM], see https://github.com/IntelPNI/brainiak)
Parameters
----------
data : numpy array, pandas df, or list of arrays/dfs
A list of Numpy arrays or Pandas Dataframes
align : str or dict
If str, either 'hyper' or 'SRM'. If 'hyper', alignment algorithm will be
hyperalignment. If 'SRM', alignment algorithm will be shared response
model. You can also pass a dictionary for finer control, where the 'model'
key is a string that specifies the model and the params key is a dictionary
of parameter values (default : 'hyper').
format_data : bool
Whether or not to first call the format_data function (default: True).
normalize : None
Deprecated argument. Please use new analyze function to perform
combinations of transformations
ndims : None
Deprecated argument. Please use new analyze function to perform
combinations of transformations
Returns
----------
aligned : list
An aligned list of numpy arrays
"""
# if model is None, just return data
if align is None:
return data
elif isinstance(align, dict):
if align['model'] is None:
return data
else:
if method is not None:
warnings.warn('The method argument will be deprecated. Please use align. See the API docs for more info: http://hypertools.readthedocs.io/en/latest/hypertools.tools.align.html#hypertools.tools.align')
align = method
if align is True:
warnings.warn("Setting align=True will be deprecated. Please specify the \
type of alignment, i.e. align='hyper'. See API docs for more info: http://hypertools.readthedocs.io/en/latest/hypertools.tools.align.html#hypertools.tools.align")
align = 'hyper'
# common format
if format_data:
data = formatter(data, ppca=True)
if len(data) == 1:
warnings.warn('Data in list of length 1 can not be aligned. '
'Skipping the alignment.')
if data[0].shape[1] >= data[0].shape[0]:
warnings.warn('The number of features exceeds number of samples. This can lead \
to overfitting. We recommend reducing the dimensionality to be \
less than the number of samples prior to hyperalignment.')
if (align == 'hyper') or (method == 'hyper'):
##STEP 0: STANDARDIZE SIZE AND SHAPE##
sizes_0 = [x.shape[0] for x in data]
sizes_1 = [x.shape[1] for x in data]
#find the smallest number of rows
R = min(sizes_0)
C = max(sizes_1)
m = [np.empty((R,C), dtype=np.ndarray)] * len(data)
for idx,x in enumerate(data):
y = x[0:R,:]
missing = C - y.shape[1]
add = np.zeros((y.shape[0], missing))
y = np.append(y, add, axis=1)
m[idx]=y
##STEP 1: TEMPLATE##
for x in range(0, len(m)):
if x==0:
template = np.copy(m[x])
else:
next = procrustes(m[x], template / (x + 1))
template += next
template /= len(m)
##STEP 2: NEW COMMON TEMPLATE##
#align each subj to the template from STEP 1
template2 = np.zeros(template.shape)
for x in range(0, len(m)):
next = procrustes(m[x], template)
template2 += next
template2 /= len(m)
#STEP 3 (below): ALIGN TO NEW TEMPLATE
aligned = [np.zeros(template2.shape)] * len(m)
for x in range(0, len(m)):
next = procrustes(m[x], template2)
aligned[x] = next
return aligned
elif (align == 'SRM') or (method == 'SRM'):
data = [i.T for i in data]
srm = SRM(features=np.min([i.shape[0] for i in data]))
fit = srm.fit(data)
return [i.T for i in srm.transform(data)]
|
ContextLab/hypertools
|
hypertools/tools/align.py
|
Python
|
mit
| 5,589
|
[
"NEURON"
] |
045cdddbdff266abd61a8551fef066bee5f66f1401f291148f56885e797fa209
|
# -*- coding: utf-8 -*-
#
# This file is part of cclib (http://cclib.github.io), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2009-2014, the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
"""Tools for identifying and working with files and streams for any supported program"""
from __future__ import print_function
import os
import sys
from . import data
from . import logfileparser
from .adfparser import ADF
from .daltonparser import DALTON
from .gamessparser import GAMESS
from .gamessukparser import GAMESSUK
from .gaussianparser import Gaussian
from .jaguarparser import Jaguar
from .molproparser import Molpro
from .mopacparser import MOPAC
from .nwchemparser import NWChem
from .orcaparser import ORCA
from .psiparser import Psi
from .qchemparser import QChem
try:
from ..bridge import cclib2openbabel
_has_cclib2openbabel = True
except ImportError:
_has_cclib2openbabel = False
# Parser choice is triggered by certain phrases occuring the logfile. Where these
# strings are unique, we can set the parser and break. In other cases, the situation
# is a little but more complicated. Here are the exceptions:
# 1. The GAMESS trigger also works for GAMESS-UK files, so we can't break
# after finding GAMESS in case the more specific phrase is found.
# 2. Molro log files don't have the program header, but always contain
# the generic string 1PROGRAM, so don't break here either to be cautious.
# 3. The Psi header has two different strings with some variation
#
# The triggers are defined by the tuples in the list below like so:
# (parser, phrases, flag whether we should break)
triggers = [
(ADF, ["Amsterdam Density Functional"], True),
(DALTON, ["Dalton - An Electronic Structure Program"], True),
(GAMESS, ["GAMESS"], False),
(GAMESS, ["GAMESS VERSION"], True),
(GAMESSUK, ["G A M E S S - U K"], True),
(Gaussian, ["Gaussian, Inc."], True),
(Jaguar, ["Jaguar"], True),
(Molpro, ["PROGRAM SYSTEM MOLPRO"], True),
(Molpro, ["1PROGRAM"], False),
(MOPAC, ["MOPAC2012, James J. P. Stewart, Stewart"], True),
(NWChem, ["Northwest Computational Chemistry Package"], True),
(ORCA, ["O R C A"], True),
(Psi, ["PSI", "Ab Initio Electronic Structure"], True),
(QChem, ["A Quantum Leap Into The Future Of Chemistry"], True),
]
def guess_filetype(inputfile):
"""Try to guess the filetype by searching for trigger strings."""
if not inputfile:
return None
filetype = None
for line in inputfile:
for parser, phrases, do_break in triggers:
if all([line.find(p) >= 0 for p in phrases]):
filetype = parser
if do_break:
return filetype
return filetype
def ccread(source, *args, **kargs):
"""Attempt to open and read computational chemistry data from a file.
If the file is not appropriate for cclib parsers, a fallback mechanism
will try to recognize some common chemistry formats and read those using
the appropriate bridge such as OpenBabel.
Inputs:
source - a single logfile, a list of logfiles, or an input stream
Returns:
a ccData object containing cclib data attributes
"""
log = ccopen(source, *args, **kargs)
if log:
if kargs.get('verbose', None):
print('Identified logfile to be in %s format' % log.logname)
return log.parse()
else:
if kargs.get('verbose', None):
print('Attempting to use fallback mechanism to read file')
return fallback(source)
def ccopen(source, *args, **kargs):
"""Guess the identity of a particular log file and return an instance of it.
Inputs:
source - a single logfile, a list of logfiles, or an input stream
Returns:
one of ADF, DALTON, GAMESS, GAMESS UK, Gaussian, Jaguar, Molpro, MOPAC, NWChem, ORCA,
Psi, QChem, or None (if it cannot figure it out or the file does not
exist).
"""
inputfile = None
isstream = False
is_string = isinstance(source, str)
is_listofstrings = isinstance(source, list) and all([isinstance(s, str) for s in source])
# Try to open the logfile(s), using openlogfile, if the source if a string (filename)
# or list of filenames. If it can be read, assume it is an open file object/stream.
if is_string or is_listofstrings:
try:
inputfile = logfileparser.openlogfile(source)
except IOError as error:
if not kargs.get('quiet', False):
(errno, strerror) = error.args
print("I/O error %s (%s): %s" % (errno, source, strerror))
return None
elif hasattr(source, "read"):
inputfile = source
isstream = True
# Proceed to return an instance of the logfile parser only if the filetype
# could be guessed. Need to make sure the input file is closed before creating
# an instance, because parsers will handle opening/closing on their own.
filetype = guess_filetype(inputfile)
if filetype:
if not isstream:
inputfile.close()
return filetype(source, *args, **kargs)
def fallback(source):
"""Attempt to read standard molecular formats using other libraries.
Currently this will read XYZ files with OpenBabel, but this can easily
be extended to other formats and libraries, too.
"""
if isinstance(source, str):
ext = os.path.splitext(source)[1][1:].lower()
if _has_cclib2openbabel:
if ext in ('xyz', ):
return cclib2openbabel.readfile(source, ext)
else:
print("Could not import openbabel, fallback mechanism might not work.")
|
ben-albrecht/cclib
|
cclib/parser/ccio.py
|
Python
|
lgpl-2.1
| 6,323
|
[
"ADF",
"Dalton",
"GAMESS",
"Gaussian",
"Jaguar",
"MOPAC",
"Molpro",
"NWChem",
"ORCA",
"cclib"
] |
f99cd123bbe8bd9332eb63a5cbb8604464f912d3ee787740673fa217edb5c99a
|
# -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# --------------------------------------------------------------------------- #
# Copyright (c) 2008-2013 Raoul Snyman #
# Portions copyright (c) 2008-2013 Tim Bentley, Gerald Britton, Jonathan #
# Corwin, Samuel Findlay, Michael Gorven, Scott Guerrieri, Matthias Hub, #
# Meinert Jordan, Armin Köhler, Erik Lundin, Edwin Lunando, Brian T. Meyer. #
# Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias Põldaru, #
# Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, #
# Maikel Stuivenberg, Martin Thompson, Jon Tibble, Dave Warnock, #
# Frode Woldsund, Martin Zibricky, Patrick Zimmermann #
# --------------------------------------------------------------------------- #
# 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; version 2 of the License. #
# #
# 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., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
###############################################################################
"""
Module implementing BookNameForm.
"""
import logging
import re
from PyQt4.QtGui import QDialog
from PyQt4 import QtCore
from openlp.core.lib import translate
from openlp.core.lib.ui import critical_error_message_box
from openlp.plugins.bibles.forms.booknamedialog import Ui_BookNameDialog
from openlp.plugins.bibles.lib import BibleStrings
from openlp.plugins.bibles.lib.db import BiblesResourcesDB
log = logging.getLogger(__name__)
class BookNameForm(QDialog, Ui_BookNameDialog):
"""
Class to manage a dialog which help the user to refer a book name a
to a english book name
"""
log.info('BookNameForm loaded')
def __init__(self, parent = None):
"""
Constructor
"""
super(BookNameForm, self).__init__(parent)
self.setupUi(self)
self.custom_signals()
self.book_names = BibleStrings().BookNames
self.book_id = False
def custom_signals(self):
"""
Set up the signals used in the booknameform.
"""
self.old_testament_check_box.stateChanged.connect(self.onCheckBoxIndexChanged)
self.new_testament_check_box.stateChanged.connect(self.onCheckBoxIndexChanged)
self.apocrypha_check_box.stateChanged.connect(self.onCheckBoxIndexChanged)
def onCheckBoxIndexChanged(self, index):
"""
Reload Combobox if CheckBox state has changed
"""
self.reload_combo_box()
def reload_combo_box(self):
"""
Reload the Combobox items
"""
self.corresponding_combo_box.clear()
items = BiblesResourcesDB.get_books()
for item in items:
add_book = True
for book in self.books:
if book.book_reference_id == item['id']:
add_book = False
break
if self.old_testament_check_box.checkState() == QtCore.Qt.Unchecked and item['testament_id'] == 1:
add_book = False
elif self.new_testament_check_box.checkState() == QtCore.Qt.Unchecked and item['testament_id'] == 2:
add_book = False
elif self.apocrypha_check_box.checkState() == QtCore.Qt.Unchecked and item['testament_id'] == 3:
add_book = False
if add_book:
self.corresponding_combo_box.addItem(self.book_names[item['abbreviation']])
def exec_(self, name, books, max_books):
self.books = books
log.debug(max_books)
if max_books <= 27:
self.old_testament_check_box.setCheckState(QtCore.Qt.Unchecked)
self.apocrypha_check_box.setCheckState(QtCore.Qt.Unchecked)
elif max_books <= 66:
self.apocrypha_check_box.setCheckState(QtCore.Qt.Unchecked)
self.reload_combo_box()
self.current_book_label.setText(str(name))
self.corresponding_combo_box.setFocus()
return QDialog.exec_(self)
def accept(self):
if not self.corresponding_combo_box.currentText():
critical_error_message_box(message=translate('BiblesPlugin.BookNameForm', 'You need to select a book.'))
self.corresponding_combo_box.setFocus()
return False
else:
cor_book = self.corresponding_combo_box.currentText()
for character in '\\.^$*+?{}[]()':
cor_book = cor_book.replace(character, '\\' + character)
books = [key for key in list(self.book_names.keys()) if re.match(cor_book, str(self.book_names[key]), re.UNICODE)]
books = [_f for _f in map(BiblesResourcesDB.get_book, books) if _f]
if books:
self.book_id = books[0]['id']
return QDialog.accept(self)
|
marmyshev/item_title
|
openlp/plugins/bibles/forms/booknameform.py
|
Python
|
gpl-2.0
| 5,820
|
[
"Brian"
] |
5e74595dffc00abece3ca174ac69c19996c879ee44af952d36eb454ad91ce1e0
|
"""Small utility for bootstrapping a Conda environment for Pulsar.
This should probably be moved into galaxy-tool-util.
"""
import os.path
import sys
from argparse import ArgumentParser
from galaxy.tool_util.deps.conda_util import CondaContext, install_conda
from galaxy.util import safe_makedirs
def main(argv=None):
mod_docstring = sys.modules[__name__].__doc__
arg_parser = ArgumentParser(description=mod_docstring)
arg_parser.add_argument("--conda_prefix", required=True)
args = arg_parser.parse_args(argv)
conda_prefix = args.conda_prefix
safe_makedirs(os.path.dirname(conda_prefix))
conda_context = CondaContext(
conda_prefix=conda_prefix,
)
install_conda(conda_context)
if __name__ == "__main__":
main()
|
galaxyproject/pulsar
|
pulsar/scripts/_conda_init.py
|
Python
|
apache-2.0
| 766
|
[
"Galaxy"
] |
1a26679552871ae2165e37dfc8d9072e3cdabc74802741745322e7c1da0fb45b
|
#!/usr/bin/env python3
"""
If you have a large FASTA file with a great number of entries, this script is used to
split the file into multiple new files with an even number of records (or as close
as possible.)
Use case example: I have a reference genome collection with 2000 genomes and want to
search this using bowtie. But the bowtie index memory footprint is too large for
a large search, so I needed to split the reference genome file into 4 even parts
and index them individually.
Usage example:
./split_fasta_into_even_files.py -i reference_genomes.fna -fc 4
The script uses the same file name as before but appends '.partN' where 'N' is replaced
by an increasing digit to indicate the file number.
"""
import argparse
import os
import sys
def main():
parser = argparse.ArgumentParser( description='Split a large FASTA file into new evenly sized files')
## output file to be written
parser.add_argument('-i', '--input_file', type=str, required=True, help='Path to an input FASTA file to be read' )
parser.add_argument('-fc', '--file_count', type=int, required=True, help='Number of files to split the records into' )
args = parser.parse_args()
# First, we need to know how many entries are in the file
total_record_count = 0
for line in open(args.input_file):
if line.startswith(">"):
total_record_count += 1
# It doesn't make sense for there to be fewer records than file count passed
if total_record_count < args.file_count:
raise Exception("Error: You asked for {0} split files to be created but there were only {1} " \
"entries in the input file.".format(args.file_count, total_record_count))
print("INFO: There were {0} records found in the input file.".format(total_record_count))
min_records_per_file = int(total_record_count / args.file_count)
file_count_to_create = int(total_record_count / min_records_per_file)
print("INFO: {0} files will be created.".format(file_count_to_create))
print("INFO: Most files will have {0} records in each.".format(min_records_per_file))
#sys.exit(1)
file_part_num = 1
current_fragment_record_count = 0
current_fh = open("{0}.part{1}".format(args.input_file, file_part_num), 'w')
for line in open(args.input_file):
if line.startswith(">"):
current_fragment_record_count += 1
if current_fragment_record_count == min_records_per_file and file_part_num < file_count_to_create:
if file_part_num <= args.file_count:
if current_fh is not None:
current_fh.close()
file_part_num += 1
current_fh = open("{0}.part{1}".format(args.input_file, file_part_num), 'w')
current_fragment_record_count = 0
current_fh.write(line)
current_fh.close()
if __name__ == '__main__':
main()
|
zctea/biocode
|
fasta/split_fasta_into_even_files.py
|
Python
|
gpl-3.0
| 2,920
|
[
"Bowtie"
] |
eb7c96fbd8b86cfb9768a9d18bd7560fb13a7ae1fabe7c341bbda6b8d9b66cb6
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
## \package pts.magic.core.pointsource Contains the PointSource class.
# -----------------------------------------------------------------
# Ensure Python 3 functionality
from __future__ import absolute_import, division, print_function
# Import astronomical modules
from astropy.coordinates import Angle
# Import the relevant PTS classes and modules
from .source import Source
from .detection import Detection
from ..core.cutout import CutoutMask, Cutout
from ..tools import statistics, fitting, masks, plotting
from ..analysis import sources
from ..region.ellipse import PixelEllipseRegion
from ...core.basics.log import log
from ..basics.stretch import PixelStretch
from ...core.units.parsing import parse_unit as u
# -----------------------------------------------------------------
class PointSource(Source):
"""
This class...
"""
def __init__(self, **kwargs):
"""
The constructor ...
:param kwargs:
"""
# Call the constructor of the base class
super(PointSource, self).__init__(**kwargs)
# Set other properties
self.catalog = kwargs.pop("catalog", None)
self.id = kwargs.pop("id", None)
self.ra_error = kwargs.pop("ra_error", None)
self.dec_error = kwargs.pop("dec_error", None)
self.confidence = kwargs.pop("confidence", None)
self.magnitudes = kwargs.pop("magnitudes", dict())
self.magnitude_errors = kwargs.pop("magnitude_errors", dict())
self.on_galaxy = kwargs.pop("on_galaxy", False)
# PSF model
self.psf_model = None
# Saturation detection
self.saturation = None
# -----------------------------------------------------------------
@property
def has_model(self):
"""
This function ...
:return:
"""
return self.psf_model is not None
# -----------------------------------------------------------------
@property
def fwhm(self):
"""
This function ...
:return:
"""
return fitting.fwhm(self.psf_model) if self.has_model else None
# -----------------------------------------------------------------
@property
def has_saturation(self):
"""
This function ...
:return:
"""
return self.saturation is not None
# -----------------------------------------------------------------
@property
def flux(self):
"""
This function ...
:return:
"""
# Return the flux of the source
return self.detection.flux
# -----------------------------------------------------------------
def get_flux(self, without_background=False):
"""
This function ...
:param without_background:
:return:
"""
return self.detection.get_flux(without_background)
# -----------------------------------------------------------------
def find_contour(self, frame, config, saturation=False):
"""
This function ...
:param frame:
:param config:
:param saturation:
:return:
"""
# Determine which box and mask
if saturation:
box = self.saturation.cutout
mask = self.saturation.mask
# Implementation
self._find_contour_impl(frame.wcs, box, mask, config)
# Call the base class implementation
else: super(PointSource, self).find_contour(frame, config)
# -----------------------------------------------------------------
def detection_from_shape(self, frame, shape, outer_factor):
"""
This function ...
:param frame:
:param shape:
:param outer_factor:
:return:
"""
# Create the detection
self.detection = Detection.from_shape(frame, shape, outer_factor)
# -----------------------------------------------------------------
def detection_at_sigma_level(self, frame, default_fwhm, sigma_level, outer_factor, use_default_fwhm=False, shape=None):
"""
This function ...
:param frame:
:param default_fwhm:
:param sigma_level:
:param outer_factor:
:param use_default_fwhm:
:param shape:
:return:
"""
# Convert FWHM to sigma
default_sigma = default_fwhm * statistics.fwhm_to_sigma
# Determine the radius of the contour in which the star will be removed
if self.psf_model is None or use_default_fwhm: radius = default_sigma * sigma_level
else: radius = fitting.sigma(self.psf_model) * sigma_level
# Determine the center position of the detection (center of model if present, otherwise position of the star)
if self.detection is not None:
# If the star has been modeled succesfully, use the center position of the model
# Otherwise, use the source's peak
if self.psf_model is not None: center = fitting.center(self.psf_model)
elif self.detection.has_peak: center = self.detection.peak
else:
log.warning("Star source does not have peak")
center = self.pixel_position(frame.wcs)
# Calculate the pixel coordinate of the star's position
else: center = self.pixel_position(frame.wcs)
# Create the new source
radius = PixelStretch(radius, radius)
ellipse = PixelEllipseRegion(center, radius)
detection = Detection.from_ellipse(frame, ellipse, outer_factor, shape=shape)
# Set peak to that of the previous source
detection.peak = self.detection.peak if self.detection is not None else None
# Set the model to that of the previous source
if self.psf_model is not None:
x_min = self.detection.x_min
y_min = self.detection.y_min
x_shift = x_min - detection.x_min
y_shift = y_min - detection.y_min
shifted_model = fitting.shifted_model(self.psf_model, x_shift, y_shift)
# Set the new model
detection.model = shifted_model
# Return the new detection
return detection
# -----------------------------------------------------------------
def ellipse(self, wcs, default_radius):
"""
This function ...
:param wcs:
:param default_radius:
:return:
"""
center, radius, angle = self.ellipse_parameters(wcs, default_radius)
return PixelEllipseRegion(center, radius, angle)
# -----------------------------------------------------------------
def ellipse_parameters(self, wcs, default_radius):
"""
This function ...
:param wcs:
:param default_radius:
:return:
"""
# Return the parameters
return self.pixel_position(wcs), default_radius, Angle(0.0, "deg")
# -----------------------------------------------------------------
def remove(self, frame, mask, config, default_fwhm, force=False):
"""
This function removes the star from a given frame
:param frame:
:param mask:
:param config:
:param default_fwhm:
:param force:
:return:
"""
# Check which removal method to use, depending on the case
# (star has model, star has no model but source, star has neither)
if self.has_model: removal_method = config.method[0]
elif self.has_detection: removal_method = config.method[1]
else: removal_method = config.method[2]
# Star that is 'forced' to be removed
if removal_method is None and force: removal_method = "interpolation"
# Stars from the DustPedia catalog should always be removed (because we trust this catalog)
# New: only enable this for optical and NIR (some stars are not present in UV maps and MIR maps)
if frame.wavelength is None or (frame.wavelength > 0.39 * u("micron") and frame.wavelength < 10.0 * u("micron")):
if self.catalog == "DustPedia" and removal_method is None: removal_method = "interpolation"
# Remove the star by subtracting the model if a model was found and the method is set to 'model'
if removal_method == "model":
# Check whether this star has a model
if not self.has_model: raise ValueError("Cannot use 'model' mode for stars without a model")
# Add a new stage to the track record
#if self.has_track_record: self.track_record.set_stage("removal")
# Create a source for the desired sigma level and outer factor
self.detection = self.detection_at_sigma_level(frame, default_fwhm, config.sigma_level, config.outer_factor)
# Evaluate the model in the cutout of the star's source
evaluated = self.detection.cutout.evaluate_model(self.psf_model)
# Determine the value at the peak for both the source and the model
rel_peak = self.detection.cutout.rel_position(self.detection.peak)
# Create a box where the model has been subtracted
subtracted = self.detection.cutout - evaluated
# To plot the difference between the source and the fitted model
if self.special: plotting.plot_star(self.detection.cutout, rel_peak, self.psf_model, "Star about to be removed by subtracting model")
# Add the evaluated and subtracted boxes to the track record
#if self.has_track_record: self.track_record.append(evaluated)
#if self.has_track_record: self.track_record.append(subtracted)
# Replace the frame with the subtracted box
subtracted.replace(frame, where=self.detection.mask)
# Set the subtracted cutout as the background of the source
self.detection.background = subtracted
# Update the mask
mask[self.detection.cutout.y_slice, self.detection.cutout.x_slice] += self.detection.mask
# If a segment was found that can be identified with a source
elif removal_method == "interpolation":
# Add a new stage to the track record
#if self.has_track_record: self.track_record.set_stage("removal")
# Create a source for the desired sigma level and outer factor
self.detection = self.detection_at_sigma_level(frame, default_fwhm, config.sigma_level, config.outer_factor)
# Determine whether we want the background to be sigma-clipped when interpolating over the source
if self.on_galaxy and config.no_sigma_clip_on_galaxy: sigma_clip = False
else: sigma_clip = config.sigma_clip
# Determine whether we want the background to be estimated by a polynomial if we are on the galaxy
# NEW: only enable this for optical and NIR (galaxy has smooth emission there but not in UV and MIR)
# We take 0.39 micron and 20 micron as the limits for 'smoothness'
if frame.wavelength is None or (frame.wavelength > 0.39 * u("micron") and frame.wavelength < 10.0 * u("micron")):
if self.on_galaxy and config.polynomial_on_galaxy: method = "polynomial"
else: method = config.interpolation_method
else: method = config.interpolation_method
# Estimate the background
self.detection.estimate_background(method, sigma_clip)
# FOR PLOTTING THE REMOVAL
if self.special:
cutout_interpolated = self.detection.cutout.copy()
cutout_interpolated[self.detection.mask] = self.detection.background[self.detection.mask]
# Do the plotting
plotting.plot_removal(self.detection.cutout, self.detection.mask, self.detection.background, cutout_interpolated)
# Add the source to the track record
#if self.has_track_record: self.track_record.append(self.source)
# Replace the frame with the estimated background
self.detection.background.replace(frame, where=self.detection.mask)
# Update the mask
mask[self.detection.cutout.y_slice, self.detection.cutout.x_slice] += self.detection.mask
# None is a valid removal method
elif removal_method is None: return
else: raise ValueError("The valid options for removal methods are 'model', 'interpolation' or None")
# -----------------------------------------------------------------
def fit_model(self, config, detection=None):
"""
This function ...
:param config:
:param detection:
:param debug:
:return:
"""
# Add a new stage to the track record
#if self.has_track_record: self.track_record.set_stage("fitting")
track_record = None
# Fit model to the source, in a loop over different analytical forms for the model
for level in range(len(config.model_names)):
# Do the fitting
if detection is None: detection, model = sources.fit_model_to_source(self.detection, config, track_record, level=level, special=self.special)
else: detection, model = sources.fit_model_to_source(detection, config, track_record, level=level)
# If a model was found, set the attributes of the star object and exit the loop
if model is not None:
self.detection = detection
self.psf_model = model
break
# -----------------------------------------------------------------
def find_saturation(self, frame, config, default_fwhm, star_mask=None):
"""
This function ...
:param frame:
:param config:
:param default_fwhm:
:param star_mask:
:return:
"""
# Convert FWHM to sigma
default_sigma = default_fwhm * statistics.fwhm_to_sigma
# Determine the radius for the saturation detection
model = self.psf_model
radius = fitting.sigma(model) * config.sigmas if model is not None else default_sigma * config.sigmas
# Make sure the radius is never smaller than 4 pixels
radius = max(radius, 4.)
# Add a new stage to the track record
#if self.has_track_record: self.track_record.set_stage("saturation")
# Look for a center segment corresponding to a 'saturation' source
radius_ellipse = PixelStretch(radius, radius)
ellipse = PixelEllipseRegion(self.pixel_position(frame.wcs), radius_ellipse)
# frame_star_erased = frame.copy()
# frame_star_erased[self.source.y_slice, self.source.x_slice][self.source.mask] = 0.0
# saturation_source = sources.find_source_segmentation(frame, ellipse, config, track_record=self.track_record, special=self.special)
# saturation_source = sources.find_source_segmentation(frame_star_erased, ellipse, config, track_record=self.track_record, special=self.special)
mask_cutout = CutoutMask(self.detection.mask, self.detection.x_min, self.detection.x_max, self.detection.y_min, self.detection.y_max)
track_record = None
saturation_source = sources.find_source_segmentation(frame, ellipse, config, track_record=track_record, special=self.special)
# Check if the found source segment is larger than the PSF source
if saturation_source is not None:
mask_saturation = CutoutMask(saturation_source.mask, saturation_source.x_min,
saturation_source.x_max, saturation_source.y_min,
saturation_source.y_max)
mask_saturation_as_cutout = mask_saturation.as_cutout(mask_cutout)
if self.detection.mask.covers(mask_saturation_as_cutout): saturation_source = None
# If a 'saturation' source was found
if saturation_source is not None:
if self.special: log.debug("Initial saturation source found")
x_min = saturation_source.x_min
x_max = saturation_source.x_max
y_min = saturation_source.y_min
y_max = saturation_source.y_max
# DEBLEND FIRST
if config.deblend:
import numpy as np
from photutils.segmentation import deblend_sources
# from astropy.convolution import Kernel2D
# Kernel2D._model = self.psf_model
# if self.psf_model is not None:
# kernelsize = 2 * int(round(fitting.sigma(self.psf_model) * 3.))
# print("kernelsize", kernelsize)
# kernel = Kernel2D(x_size=kernelsize)
# else: kernel = None
kernel = None
segments = deblend_sources(saturation_source.cutout, saturation_source.mask.astype(int),
npixels=config.deblending.min_npixels, contrast=config.deblending.contrast,
mode=config.deblending.mode, nlevels=config.deblending.nlevels,
filter_kernel=kernel)
plotting.plot_box(segments)
smallest_distance = None
smallest_distance_mask = None
for index in np.unique(segments)[1:]:
where = segments == index
fake_box = Cutout(where.astype(int), x_min, x_max, y_min, y_max)
contour = sources.find_contour(fake_box, where, sigma_level=1)
difference = contour.center - self.pixel_position(frame.wcs)
distance = difference.norm
if smallest_distance is None or distance < smallest_distance:
smallest_distance = distance
smallest_distance_mask = where
# print(index, difference.norm)
# SET NEW MASK
saturation_source.mask = smallest_distance_mask
# AFTER DEBLENDING, CALCULATE CONTOUR
# Calculate the elliptical contour
# contour = sources.find_contour(saturation_source.cutout, saturation_source.mask, config.apertures.sigma_level)
contour = sources.find_contour(Cutout(saturation_source.mask.astype(int), x_min, x_max, y_min, y_max),
saturation_source.mask,
config.apertures.sigma_level) # determine the segment properties of the actual mask segment
# Check whether the source centroid matches the star position
if config.check_centroid:
if self.special: log.debug("Checking contour parameters ...")
# Calculate the offset
difference = contour.center - self.pixel_position(frame.wcs)
star_mask_cutout = star_mask[saturation_source.cutout.y_slice, saturation_source.cutout.x_slice]
# Remove the mask of this star from the star_mask_cutout
x_min_cutout = saturation_source.cutout.x_min
x_max_cutout = saturation_source.cutout.x_max
y_min_cutout = saturation_source.cutout.y_min
y_max_cutout = saturation_source.cutout.y_max
x_min_source = self.detection.cutout.x_min
x_max_source = self.detection.cutout.x_max
y_min_source = self.detection.cutout.y_min
y_max_source = self.detection.cutout.y_max
try:
# plotting.plot_box(star_mask_cutout, title="before removing central source")
star_mask_cutout[y_min_source - y_min_cutout:y_max_source - y_min_cutout,
x_min_source - x_min_cutout:x_max_source - x_min_cutout][self.detection.mask] = False
# plotting.plot_box(star_mask_cutout, title="after removing central source")
except IndexError:
pass
# plotting.plot_box(frame[saturation_source.y_slice, saturation_source.x_slice])
# plotting.plot_box(saturation_source.mask)
# plotting.plot_box(star_mask_cutout)
# print(star_mask_cutout.shape)
# plotting.plot_box(saturation_source.cutout)
# print(saturation_source.cutout.shape)
# plotting.plot_box(self.source.mask)
# print(self.source.mask.shape)
# print(y_min_source, y_min_cutout, y_max_source, y_min_cutout, x_min_source, x_min_cutout, x_max_source, x_min_cutout)
# print(y_min_source-y_min_cutout) # becomes negative!
# print(y_max_source-y_min_cutout)
# print(x_min_source-x_min_cutout) # becomes negative !
# print(x_max_source-x_min_cutout)
# print(star_mask_cutout[y_min_source-y_min_cutout:y_max_source-y_min_cutout, x_min_source-x_min_cutout:x_max_source-x_min_cutout].shape)
# source_mask_smaller = self.source.mask[y_min_cutout-y_min_source:,x_min_cutout-x_min_source]
# star_mask_cutout[0:y_max_source-y_min_cutout][0:x_max_source-x_min_cutout][source_mask_smaller] = False
# TODO: fix this problem ! (how can it be that the source box is not inside the saturation box??)
# saturation sources are created by expanding the initial source box ??
# Discard this saturation source if the centroid offset or the ellipticity is too large
if not masks.overlap(saturation_source.mask, star_mask_cutout):
if self.special: log.debug("Checking offset and ellipticity")
if difference.norm > config.max_centroid_offset or contour.ellipticity > config.max_centroid_ellipticity:
if self.special: log.debug(
"Found to large offset or ellipticity: not a saturation source")
return
else:
if self.special: log.debug("Saturation mask overlaps other stars, so contour parameters will not be checked")
if config.second_segmentation:
# Find all of the saturation light in a second segmentation step
track_record = None
saturation_source = sources.find_source_segmentation(frame, ellipse, config,
track_record=track_record,
special=self.special,
sigma_level=config.second_sigma_level)
# contour = sources.find_contour(saturation_source.cutout, saturation_source.mask, config.apertures.sigma_level)
contour = sources.find_contour(saturation_source.mask.astype(int), saturation_source.mask, config.apertures.sigma_level) # determine the segment properties of the actual mask segment
# Check whether the source centroid matches the star position
if config.check_centroid:
# Calculate the offset
difference = contour.center - self.pixel_position(frame.wcs)
star_mask_cutout = star_mask[saturation_source.cutout.y_slice, saturation_source.cutout.x_slice]
# Remove the mask of this star from the star_mask_cutout
x_min_cutout = saturation_source.cutout.x_min
x_max_cutout = saturation_source.cutout.x_max
y_min_cutout = saturation_source.cutout.y_min
y_max_cutout = saturation_source.cutout.y_max
x_min_source = self.detection.cutout.x_min
x_max_source = self.detection.cutout.x_max
y_min_source = self.detection.cutout.y_min
y_max_source = self.detection.cutout.y_max
# plotting.plot_box(star_mask_cutout, title="before removing central source")
star_mask_cutout[y_min_source - y_min_cutout:y_max_source - y_min_cutout,
x_min_source - x_min_cutout:x_max_source - x_min_cutout][self.detection.mask] = False
# plotting.plot_box(star_mask_cutout, title="after removing central source")
# Discard this saturation source if the centroid offset or the ellipticity is too large
if not masks.overlap(saturation_source.mask, star_mask_cutout):
if difference.norm > config.max_centroid_offset or contour.ellipticity > config.max_centroid_ellipticity: return
# Replace the pixels of the cutout box by the pixels of the original frame (because the star itself is already removed)
# saturation_source.cutout = frame.box_like(saturation_source.cutout)
# TODO: check with classifier to verify this is actually a saturation source!
if self.special: saturation_source.plot(title="Final saturation source")
# Replace the source by a source that covers the saturation
self.saturation = saturation_source
self.contour = contour
# -----------------------------------------------------------------
def remove_saturation(self, frame, mask, config):
"""
This function ...
:param frame:
:param mask:
:param config:
"""
# Determine whether we want the background to be sigma-clipped when interpolating over the (saturation) source
if self.on_galaxy and config.no_sigma_clip_on_galaxy: sigma_clip = False
else: sigma_clip = config.sigma_clip
# Determine whether we want the background to be estimated by a polynomial if we are on the galaxy
# NEW: only enable this for optical and IR (galaxy has smooth emission there but not in UV)
if frame.wavelength is None or frame.wavelength > 0.39 * u("micron"):
if self.on_galaxy and config.polynomial_on_galaxy:
interpolation_method = "polynomial"
else: interpolation_method = config.interpolation_method
else: interpolation_method = config.interpolation_method
# Estimate the background
self.saturation.estimate_background(interpolation_method, sigma_clip)
# FOR PLOTTING THE REMOVAL
if self.special:
cutout_interpolated = self.saturation.cutout.copy()
cutout_interpolated[self.saturation.mask] = self.saturation.background[self.saturation.mask]
# Do the plotting
plotting.plot_removal(self.saturation.cutout, self.saturation.mask, self.saturation.background,
cutout_interpolated)
# Replace the frame with the estimated background
self.saturation.background.replace(frame, where=self.saturation.mask)
# Update the mask
mask[self.saturation.cutout.y_slice, self.saturation.cutout.x_slice] += self.saturation.mask
# -----------------------------------------------------------------
|
SKIRT/PTS
|
magic/core/pointsource.py
|
Python
|
agpl-3.0
| 27,632
|
[
"Galaxy"
] |
39a13021389f49b128eface77c80075eb9d7de6e47ee0b529ca6aa4591f8bf79
|
# -*- coding: utf-8 -*-
from django import forms
from Product_manage.models import Product, Chemical
from django.forms import modelform_factory
from rdkit import Chem
from django.forms import Widget
from django.utils.safestring import mark_safe
def get_or_none(model, *args, **kwargs):
try:
return model.objects.get(*args, **kwargs)
except model.DoesNotExist:
return None
class CategorySelector(Widget):
def render(self, name, value, attrs=None):
ret = '''
<input id = "id_{name}" name="{name}" value = "{value}">
<script type="text/javascript">
$('#id_{name}').w2field('{name}', {{
url: 'w2ui_product',
renderItem: function (item) {{
return item.fname + ' ' + item.lname;
}},
renderDrop: function (item) {{
return item.fname + ' ' + item.lname;
}},
compare: function (item, search) {{
var fname = search,
lname = search;
if (search.indexOf(' ') != -1) {{
fname = search.split(' ')[0];
lname = search.split(' ')[1];
}}
var match = false;
var re1 = new RegExp(fname, 'i');
var re2 = new RegExp(lname, 'i');
if (fname == lname) {{
if (re1.test(item.fname) || re2.test(item.lname)) match = true;
}} else {{
if (re1.test(item.fname) && re2.test(item.lname)) match = true;
}}
return match;
}}
}});
</script>
'''
return mark_safe(ret.format(name=name, value=value))
class ProductForm(forms.ModelForm):
mol = forms.HiddenInput()
class Meta:
model = Product
fields = ("id", "category", "cat_no", "en_name", "en_synonymous", "chs_synonymous", "cas", "possible_cas",
"en_website_avail", "chs_website_avail",)
widgets = {"cat_no": forms.TextInput(),
"en_name": forms.TextInput(),
"en_synonymous": forms.Textarea(attrs={'cols': 30, 'rows': 2}),
"chs_synonymous": forms.Textarea(attrs={'cols': 30, 'rows': 2}),
"category": CategorySelector(),
}
def save(self, commit=True, *args, **kwargs):
instance = super(ProductForm, self).save(commit=False)
mol_block = self.cleaned_data.get("mol", None)
m = Chem.MolFromMol2Block(mol_block)
if m:
smiles = Chem.MolToSmiles(m, isomericSmiles=True)
try:
chem = Chemical.objects.get(smiles=smiles)
except Chemical.DoesNotExist:
chem = Chemical.objects.create(mol=mol_block)
instance.chem = chem
if not instance.cas:
instance.cas = chem.cas
if not instance.possible_cas:
instance.possible_cas = chem.possible_cas
instance.save()
return instance
|
Pandaaaa906/ChemErpSystem
|
ERP/forms.py
|
Python
|
apache-2.0
| 3,092
|
[
"RDKit"
] |
72b9018520f51acb48caf4ceeec38ede59000f70b8fdba9e9561cd76c3a2eefc
|
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Show the constant kernel. Smooth an impulse function.
s1 = vtk.vtkImageCanvasSource2D()
s1.SetScalarTypeToFloat()
s1.SetExtent(0,255,0,255,0,0)
s1.SetDrawColor(0)
s1.FillBox(0,255,0,255)
s1.SetDrawColor(1.0)
s1.FillBox(75,175,75,175)
convolve = vtk.vtkImageConvolve()
convolve.SetInputConnection(s1.GetOutputPort())
convolve.SetKernel5x5([1,1,1,1,1,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,1,1,1,1,1])
viewer = vtk.vtkImageViewer()
viewer.SetInputConnection(convolve.GetOutputPort())
viewer.SetColorWindow(18)
viewer.SetColorLevel(9)
viewer.Render()
# --- end of script --
|
HopeFOAM/HopeFOAM
|
ThirdParty-0.1/ParaView-5.0.1/VTK/Imaging/Core/Testing/Python/TestConvolve.py
|
Python
|
gpl-3.0
| 702
|
[
"VTK"
] |
4996a11428072fc196a8b57a7ee71f3ada31f4479d92cffc22c09d29167a46d8
|
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import os
import tempfile
import unittest
import numpy as np
from pymatgen.core.structure import Structure
from pymatgen.io.abinit.inputs import (
BasicAbinitInput,
BasicMultiDataset,
ShiftMode,
calc_shiftk,
ebands_input,
gs_input,
ion_ioncell_relax_input,
num_valence_electrons,
)
from pymatgen.util.testing import PymatgenTest
_test_dir = os.path.join(PymatgenTest.TEST_FILES_DIR, "abinit")
def abiref_file(filename):
"""Return absolute path to filename in ~pymatgen/test_files/abinit"""
return os.path.join(_test_dir, filename)
def abiref_files(*filenames):
"""Return list of absolute paths to filenames in ~pymatgen/test_files/abinit"""
return [os.path.join(_test_dir, f) for f in filenames]
class AbinitInputTestCase(PymatgenTest):
"""Unit tests for BasicAbinitInput."""
def test_api(self):
"""Testing BasicAbinitInput API."""
# Build simple input with structure and pseudos
unit_cell = {
"acell": 3 * [10.217],
"rprim": [[0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0]],
"ntypat": 1,
"znucl": [14],
"natom": 2,
"typat": [1, 1],
"xred": [[0.0, 0.0, 0.0], [0.25, 0.25, 0.25]],
}
inp = BasicAbinitInput(structure=unit_cell, pseudos=abiref_file("14si.pspnc"))
shiftk = [[0.5, 0.5, 0.5], [0.5, 0.0, 0.0], [0.0, 0.5, 0.0], [0.0, 0.0, 0.5]]
self.assertArrayEqual(calc_shiftk(inp.structure), shiftk)
assert num_valence_electrons(inp.structure, inp.pseudos) == 8
repr(inp), str(inp)
assert len(inp) == 0 and not inp
assert inp.get("foo", "bar") == "bar" and inp.pop("foo", "bar") == "bar"
assert inp.comment is None
inp.set_comment("This is a comment")
assert inp.comment == "This is a comment"
assert inp.isnc and not inp.ispaw
inp["ecut"] = 1
assert inp.get("ecut") == 1 and len(inp) == 1 and "ecut" in inp.keys() and "foo" not in inp
# Test to_string
assert inp.to_string(with_structure=True, with_pseudos=True)
assert inp.to_string(with_structure=False, with_pseudos=False)
inp.set_vars(ecut=5, toldfe=1e-6)
assert inp["ecut"] == 5
inp.set_vars_ifnotin(ecut=-10)
assert inp["ecut"] == 5
_, tmpname = tempfile.mkstemp(text=True)
inp.write(filepath=tmpname)
# Cannot change structure variables directly.
with self.assertRaises(inp.Error):
inp.set_vars(unit_cell)
with self.assertRaises(TypeError):
inp.add_abiobjects({})
with self.assertRaises(KeyError):
inp.remove_vars("foo", strict=True)
assert not inp.remove_vars("foo", strict=False)
# Test deepcopy and remove_vars.
inp["bdgw"] = [1, 2]
inp_copy = inp.deepcopy()
inp_copy["bdgw"][1] = 3
assert inp["bdgw"] == [1, 2]
assert inp.remove_vars("bdgw") and "bdgw" not in inp
removed = inp.pop_tolerances()
assert len(removed) == 1 and removed["toldfe"] == 1e-6
# Test set_spin_mode
old_vars = inp.set_spin_mode("polarized")
assert "nsppol" in inp and inp["nspden"] == 2 and inp["nspinor"] == 1
inp.set_vars(old_vars)
# Test set_structure
new_structure = inp.structure.copy()
new_structure.perturb(distance=0.1)
inp.set_structure(new_structure)
assert inp.structure == new_structure
# Compatible with Pickle and MSONable?
self.serialize_with_pickle(inp, test_eq=False)
def test_input_errors(self):
"""Testing typical BasicAbinitInput Error"""
si_structure = Structure.from_file(abiref_file("si.cif"))
# Ambiguous list of pseudos.
with self.assertRaises(BasicAbinitInput.Error):
BasicAbinitInput(si_structure, pseudos=abiref_files("14si.pspnc", "14si.4.hgh"))
# Pseudos do not match structure.
with self.assertRaises(BasicAbinitInput.Error):
BasicAbinitInput(si_structure, pseudos=abiref_file("H-wdr.oncvpsp"))
si1_negative_volume = dict(
ntypat=1,
natom=1,
typat=[1],
znucl=14,
acell=3 * [7.60],
rprim=[[0.0, 0.5, 0.5], [-0.5, -0.0, -0.5], [0.5, 0.5, 0.0]],
xred=[[0.0, 0.0, 0.0]],
)
# Negative triple product.
with self.assertRaises(BasicAbinitInput.Error):
BasicAbinitInput(si1_negative_volume, pseudos=abiref_files("14si.pspnc"))
def test_helper_functions(self):
"""Testing BasicAbinitInput helper functions."""
inp = BasicAbinitInput(structure=abiref_file("si.cif"), pseudos="14si.pspnc", pseudo_dir=_test_dir)
inp.set_kmesh(ngkpt=(1, 2, 3), shiftk=(1, 2, 3, 4, 5, 6))
assert inp["kptopt"] == 1 and inp["nshiftk"] == 2
inp.set_gamma_sampling()
assert inp["kptopt"] == 1 and inp["nshiftk"] == 1
assert np.all(inp["shiftk"] == 0)
inp.set_kpath(ndivsm=3, kptbounds=None)
assert inp["ndivsm"] == 3 and inp["iscf"] == -2 and len(inp["kptbounds"]) == 12
class TestMultiDataset(PymatgenTest):
"""Unit tests for BasicMultiDataset."""
def test_api(self):
"""Testing BasicMultiDataset API."""
structure = Structure.from_file(abiref_file("si.cif"))
pseudo = abiref_file("14si.pspnc")
pseudo_dir = os.path.dirname(pseudo)
multi = BasicMultiDataset(structure=structure, pseudos=pseudo)
with self.assertRaises(ValueError):
BasicMultiDataset(structure=structure, pseudos=pseudo, ndtset=-1)
multi = BasicMultiDataset(structure=structure, pseudos=pseudo, pseudo_dir=pseudo_dir)
assert len(multi) == 1 and multi.ndtset == 1
assert multi.isnc
for i, inp in enumerate(multi):
assert list(inp.keys()) == list(multi[i].keys())
multi.addnew_from(0)
assert multi.ndtset == 2 and multi[0] is not multi[1]
assert multi[0].structure == multi[1].structure
assert multi[0].structure is not multi[1].structure
multi.set_vars(ecut=2)
assert all(inp["ecut"] == 2 for inp in multi)
self.assertEqual(multi.get("ecut"), [2, 2])
multi[1].set_vars(ecut=1)
assert multi[0]["ecut"] == 2 and multi[1]["ecut"] == 1
self.assertEqual(multi.get("ecut"), [2, 1])
self.assertEqual(multi.get("foo", "default"), ["default", "default"])
multi[1].set_vars(paral_kgb=1)
assert "paral_kgb" not in multi[0]
self.assertEqual(multi.get("paral_kgb"), [None, 1])
pert_structure = structure.copy()
pert_structure.perturb(distance=0.1)
assert structure != pert_structure
assert multi.set_structure(structure) == multi.ndtset * [structure]
assert all(s == structure for s in multi.structure)
assert multi.has_same_structures
multi[1].set_structure(pert_structure)
assert multi[0].structure != multi[1].structure and multi[1].structure == pert_structure
assert not multi.has_same_structures
split = multi.split_datasets()
assert len(split) == 2 and all(split[i] == multi[i] for i in range(multi.ndtset))
repr(multi)
str(multi)
assert multi.to_string(with_pseudos=False)
tmpdir = tempfile.mkdtemp()
filepath = os.path.join(tmpdir, "run.abi")
inp.write(filepath=filepath)
multi.write(filepath=filepath)
new_multi = BasicMultiDataset.from_inputs([inp for inp in multi])
assert new_multi.ndtset == multi.ndtset
assert new_multi.structure == multi.structure
for old_inp, new_inp in zip(multi, new_multi):
assert old_inp is not new_inp
self.assertDictEqual(old_inp.as_dict(), new_inp.as_dict())
ref_input = multi[0]
new_multi = BasicMultiDataset.replicate_input(input=ref_input, ndtset=4)
assert new_multi.ndtset == 4
for inp in new_multi:
assert ref_input is not inp
self.assertDictEqual(ref_input.as_dict(), inp.as_dict())
# Compatible with Pickle and MSONable?
self.serialize_with_pickle(multi, test_eq=False)
class ShiftModeTest(PymatgenTest):
def test_shiftmode(self):
"""Testing shiftmode"""
gamma = ShiftMode.GammaCentered
assert ShiftMode.from_object("G") == gamma
assert ShiftMode.from_object(gamma) == gamma
with self.assertRaises(TypeError):
ShiftMode.from_object({})
class FactoryTest(PymatgenTest):
def setUp(self):
# Si ebands
self.si_structure = Structure.from_file(abiref_file("si.cif"))
self.si_pseudo = abiref_file("14si.pspnc")
def test_gs_input(self):
"""Testing gs_input factory."""
inp = gs_input(self.si_structure, self.si_pseudo, kppa=10, ecut=10, spin_mode="polarized")
str(inp)
assert inp["nsppol"] == 2
assert inp["nband"] == 14
self.assertArrayEqual(inp["ngkpt"], [2, 2, 2])
def test_ebands_input(self):
"""Testing ebands_input factory."""
multi = ebands_input(self.si_structure, self.si_pseudo, kppa=10, ecut=2)
str(multi)
scf_inp, nscf_inp = multi.split_datasets()
# Test dos_kppa and other options.
multi_dos = ebands_input(
self.si_structure,
self.si_pseudo,
nscf_nband=10,
kppa=10,
ecut=2,
spin_mode="unpolarized",
smearing=None,
charge=2.0,
dos_kppa=50,
)
assert len(multi_dos) == 3
assert all(i["charge"] == 2 for i in multi_dos)
self.assertEqual(multi_dos.get("nsppol"), [1, 1, 1])
self.assertEqual(multi_dos.get("iscf"), [None, -2, -2])
multi_dos = ebands_input(
self.si_structure,
self.si_pseudo,
nscf_nband=10,
kppa=10,
ecut=2,
spin_mode="unpolarized",
smearing=None,
charge=2.0,
dos_kppa=[50, 100],
)
assert len(multi_dos) == 4
self.assertEqual(multi_dos.get("iscf"), [None, -2, -2, -2])
str(multi_dos)
def test_ion_ioncell_relax_input(self):
"""Testing ion_ioncell_relax_input factory."""
multi = ion_ioncell_relax_input(self.si_structure, self.si_pseudo, kppa=10, ecut=2)
str(multi)
ion_inp, ioncell_inp = multi.split_datasets()
assert ion_inp["chksymbreak"] == 0
assert ion_inp["ionmov"] == 3 and ion_inp["optcell"] == 0
assert ioncell_inp["ionmov"] == 3 and ioncell_inp["optcell"] == 2
|
vorwerkc/pymatgen
|
pymatgen/io/abinit/tests/test_inputs.py
|
Python
|
mit
| 10,871
|
[
"ABINIT",
"pymatgen"
] |
3e61fd6076ab46df3f1168fbef02fbd13c9627b2179dcb8e52a862391c50d2b0
|
import numpy as np
import h5py
from dedalus import public as de
from dedalus.extras import flow_tools
import time
import argparse
import dedalus_plots as dp
import matplotlib.pyplot as plt
from subprocess import call
parser = argparse.ArgumentParser(description='simulate a Boussinesq pulse')
parser.add_argument('k', metavar = 'k', type = int, help='forcing wavenumber in the horizontal')
parser.add_argument('m', metavar = 'm', type = int, help='forcing wavenumber in the vertical')
parser.add_argument('eps', metavar = 'eps', type = float, help='epsilon, the ratio of buoyancy frequency in troposphere and stratosphere')
parser.add_argument('sim_name',metavar = 'sim_name', type = str, help = 'simulation name')
parser.add_argument('-nh','--non-hstat', dest='hstat', action='store_false')
parser.add_argument('-p','--pulse', dest='pulse', action='store_true')
parser.add_argument('-pl', '--pulse-len', dest = 'pulse_len' , type = float)
parser.add_argument('-rl', '--rigid-lid', dest='rigid_lid', action = 'store_true')
parser.add_argument('-tau', '--damping-tau', dest = 'tau', type = int, help='rayleigh damping timescale in days')
parser.set_defaults(pulse_len=1000)
parser.set_defaults(hstat=True)
parser.set_defaults(pulse=False)
parser.set_defaults(rigid_lid=False)
args = parser.parse_args()
PULSE = args.pulse
HYDROSTATIC = args.hstat
#print('pulse_len is ', args.pulse_len)
if HYDROSTATIC == True:
print('using hydrostatic boussinesq solver')
else:
print('using non-hydrostatic boussinesq solver')
if PULSE == True:
print('solving for gaussian forcing')
else:
print('solving initial gaussian buoyancy perturbation')
import logging
root = logging.root
for h in root.handlers:
h.setLevel("INFO")
logger = logging.getLogger(__name__)
def onetwoone(field, niter = 100):
'''1-2-1 filter'''
newfield = field
j=0
while j < niter:
lastfield = newfield
for i in range(1,len(field)-1):
newfield[i] = 0.5*lastfield[i] + 0.25*(lastfield[i+1] + lastfield[i-1])
j += 1
return newfield
stop_time = 86400.*2. # simulation stop time (seconds)
pulse_len = args.pulse_len # seconds of forcing
N1 = 0.01 # buoyancy frequency in the troposphere (1/s)
Lx, Lz = (stop_time*100, 15000) # domain size in meters
nx, nz = (196*2, 124) # number of points in each direction
# Create bases and domain
x_basis = de.Fourier('x', nx, interval=(-Lx/2., Lx/2.))
# compound z basis -- better to resolve jump condition?
#zb1 = de.Chebyshev('z1',int(nz/4), interval=(0, Lz+1000), dealias=3/2)
#zb2 = de.Chebyshev('z2', nz, interval=(Lz+1000,model_top), dealias = 3/2)
#z_basis = de.Compound('z',(zb1,zb2), dealias = 3/2)
#
m = args.m # vertical mode number
k = args.k # horizontal mode number
eps = args.eps # ratio of N1/N2
N2 = N1/eps # buoyancy frequency in the stratosphere
if (args.rigid_lid):
model_top = Lz
nz = int(nz/4)
else:
model_top = 8. * Lz # lid height
z_basis = de.Chebyshev('z', nz, interval= (0, model_top))
domain = de.Domain([x_basis, z_basis], grid_dtype=np.float64)
x, z = domain.grids(scales=1)
xd, zd = domain.grids(scales=domain.dealias)
# set up problem
problem = de.IVP(domain, variables=['p','u','B','w'])
problem.parameters['rho'] = 1. #kg/m^3
#problem.parameters['Nsq'] = 0.0001 #1/s; constant Nsq
# non-constant coefficient N^2
ncc = domain.new_field(name='Nsq')
ncc['g'] = N1**2
if not (args.rigid_lid):
strat = np.where( z > Lz)
ncc['g'][:,strat] = N2**2
ncc['g'][:,0] = N1**2
ncc.meta['x']['constant'] = True
problem.parameters['Nsq'] = ncc
print(ncc['g'][20,:])
# non-constant coefficient alpha (rayleigh drag)
tmp = np.zeros(z.shape[1])
if (args.tau):
tmp[:] = 1./(args.tau*86400.) # set the rayleigh damping timescale
strat2 = np.where( z[:] > 5.*Lz)
tmp[strat2[1]] = 24./86400.
#tmp[strat2[0]]= 0. ### try inviscid case
tmp = onetwoone(tmp, niter=30)
tmpgrid, _ = np.meshgrid(tmp,x)
aa = domain.new_field(name='alpha')
aa['g'] = tmpgrid
aa.meta['x']['constant'] = True
problem.parameters['alpha'] = aa
# mask (for analysis)
strat = np.where(z>Lz)
mask = domain.new_field(name = 'mask')
mask['g'] = 1
mask['g'][:,strat] = 0
mask.meta['x']['constant'] = True
problem.parameters['mask'] = mask
if PULSE == True:
sigma_t = args.pulse_len
sigma_x = args.k
def forcing(solver):
# if using dealiasing, it's important to apply the forcing on the dealiased doman (xd,zd)
if solver.sim_time < stop_time:
td = solver.sim_time
f = 0.00001*np.sin(m *np.pi*zd/Lz) * np.exp(-(xd*xd)/(sigma_x**2)) * np.exp(-(td - 2.*sigma_t)**2/sigma_t**2)
strat = np.where(zd>Lz)
if not (args.rigid_lid):
f[:,strat] = 0.
# subtract the horizontal mean at each level so there's no k=0
# fprof = np.mean(f, axis = 0 )
# ftmp = np.repeat(fprof, xd.shape[0])
# fmask = ftmp.reshape(zd.shape[1],xd.shape[0])
# f = f - fmask.T
else:
f = 0.
return f
else:
def forcing(solver):
# if using dealiasing, it's important to apply the forcing on the dealiased doman (xd,zd)
f = 0.
return f
#define general forcing function
forcing_func = de.operators.GeneralFunction(domain,'g',forcing, args=[])
forcing_func.build_metadata()
#forcing_func.meta = ncc.meta # just tricking it for now, this metadata is wrong
# let's make a general parameter and use that metadata instead
dummy = domain.new_field(name='dum')
dummy['g'] = 1.
forcing_func.meta = dummy.meta
problem.parameters['forcing_func'] = forcing_func
# need to add 'meta' attribute for General Function class
# otherwise system fails consistency check
# system to solve (2D, linearized, hydrostatic boussinesq)
problem.add_equation("dt(u) + 1/rho*dx(p) + alpha*u = 0")
problem.add_equation("dt(B) + Nsq*w + alpha*B = forcing_func")
#problem.add_equation("dt(B) + Nsq*w = 0")
problem.add_equation("dx(u) + dz(w) = 0")
if HYDROSTATIC == True:
problem.add_equation("B - 1/rho*dz(p) = 0")
else:
problem.add_equation("B - 1/rho*dz(p) - dt(w) = 0")
# fourier direction has periodic bc, chebyshev has a lid
problem.add_bc("left(w) = 0") # refers to the first end point in chebyshev direction
problem.add_bc("right(w) = 0", condition="(nx != 0)") # rigid lid, condition note for k = 0 mode
problem.add_bc("integ(p,'z') = 0", condition="(nx == 0)") # pressure gauge condition for k = 0
# build solver
ts = de.timesteppers.RK443 # arbitrary choice of time stepper
#ts = de.timesteppers.CNAB2
solver = problem.build_solver(ts)
sim_name = args.sim_name
print('simulation name is', sim_name)
print('effective forcing horizontal wavelength is' , Lx/k/1000., 'kilometers')
print('effective forcing vertical wavelength is' , 2.*Lz/m/1000., 'kilometers')
print('stratification ratio N1/N2 is' , N1/N2 )
# initial conditions
# tell the forcing function what its arg is (clunky)
forcing_func.args = [solver]
forcing_func.original_args = [solver]
# initial conditions
x, z = domain.grids(scales=1)
u = solver.state['u']
w = solver.state['w']
p = solver.state['p']
B = solver.state['B'] # zero for everything
u['g'] = 0.
w['g'] = 0.
p['g'] = 0.
B['g'] = 0.
if not (args.pulse):
# start with an initial buoyancy perturbation in the tropopshere
sigma_x = args.k
B['g'] = 0.1*np.sin(m *np.pi*z/Lz) * np.exp(-(x*x)/(sigma_x**2))
strat = np.where(zd>Lz)
if not (args.rigid_lid):
f[:,strat] = 0.
solver.stop_sim_time = stop_time
solver.stop_wall_time = np.inf
solver.stop_iteration = np.inf
# CFL conditions
#initial_dt = 0.8*Lz/nz
initial_dt = 100
cfl = flow_tools.CFL(solver,initial_dt,safety=0.8, max_change=30., min_change=0.5, max_dt=900)
# too large of a timestep makes things rather diffusive
cfl.add_velocities(('u','w'))
# fields to record
analysis = solver.evaluator.add_file_handler(sim_name, sim_dt=900, max_writes=50000)
analysis.add_task('B', name = 'buoyancy' )
analysis.add_task('u', name = 'horizontal velocity' )
analysis.add_task('w', name = 'vertical velocity' )
analysis.add_task('p', name = 'pressure' )
# 1d fields
analysis.add_task('mask')
analysis.add_task("integ(B, 'z')", name = 'tropo b') # use mask to integrate over troposphere only
analysis.add_task("integ(0.5 * mask *(u*u + w*w + B*B/Nsq ), 'z')", name = 'tropo energy') # use mask to integrate over troposphere only
#analysis.add_task("integ(0.5 * (u*u + w*w + B*B/Nsq ))", name='total e')
try:
logger.info('Starting loops')
start_time = time.time()
while solver.ok:
dt = cfl.compute_dt()
solver.step(dt)
if solver.iteration % 4 == 0:
print('Completed iteration {}'.format(solver.iteration))
print('simulation time {}'.format(solver.sim_time))
except:
logger.error('Exception raised, triggering end of main loop.')
raise
finally:
end_time = time.time()
# Print statistics
logger.info('Run time: %f' %(end_time-start_time))
logger.info('Iterations: %i' %solver.iteration)
# archive decay timescales
# merge parallel files
#call(['./merge.py', sim_name])
#filepath = sim_name + "/" + sim_name + "_s1.h5"
#filepath = sim_name + "/" + sim_name + "_s1/" + sim_name + "_s1_p0.h5"
#print(filepath)
# open data file
#data = h5py.File(filepath, "r")
# read in variables and dimensions
#dict_vars = {'tropenergy':'tropo energy', 'b3d':'buoyancy', 'u3d':'horizontal velocity', 'w3d':'vertical velocity', 'p':'pressure'}
#vars = dp.read_vars(data, dict_vars)
#dims = dp.read_dims(data)
#data.close()
#energ_normed = vars['tropenergy'][:,0,0]
#dp.make_1D_plot(sim_name+'/energytest.pdf', dims['t'], simulation = energ_normed)
#dp.make_2D_plot(sim_name+'/binit.pdf', (dims['x']/1000., dims['z']/1000.),vars['b3d'][10,:,:].T , title='b initial', xlabel = 'x (km)', ylabel = 'z (km)')
#plt.clf()
#dp.make_2D_plot(sim_name+'/bfinal.pdf', (dims['x']/1000., dims['z']/1000.),vars['b3d'][-1,:,:].T , title='b final', xlabel = 'x (km)', ylabel = 'z (km)')
#plt.clf()
#dp.make_2D_plot(sim_name+'/ufinal.pdf', (dims['x']/1000., dims['z']/1000.),vars['u3d'][-1,:,:].T , title='u final', xlabel = 'x (km)', ylabel = 'z (km)')
#plt.clf()
#dp.make_2D_plot(sim_name+'/umid.pdf', (dims['x']/1000., dims['z']/1000.),vars['u3d'][50,:,:].T , title='u mid', xlabel = 'x (km)', ylabel = 'z (km)')
#plt.clf()
#dp.make_2D_plot(sim_name+'/wfinal.pdf', (dims['x']/1000., dims['z']/1000.),vars['w3d'][-1,:,:].T , title='w final', xlabel = 'x (km)', ylabel = 'z (km)')
#plt.clf()
#taufit.plot_taus(archive_list)
#import pickle
#outfile = open( "eps02_mpi.p", "wb" )
#pickle.dump(archive_list, outfile)
#dp.make_1D_plot(sim_name+'/energytest.pdf', dims['t'], simulation = energ_normed,
# theory = energ_theory, offmode = energ_off)
#dp.make_2D_plot(sim_name+'/bend.pdf', (dims['x']/1000., dims['z']/1000.),vars['b3d'][-1,:,:].T , title='b final', xlabel = 'x (km)', ylabel = 'z (km)')i
|
jedman/dedalus-leakylid
|
dedalus_pulse.py
|
Python
|
gpl-2.0
| 10,925
|
[
"Gaussian"
] |
27bb67377f03e15b7b402167fd855ab29785108efb99f87a85557106f7e47354
|
from unittest import TestCase
from omicexperiment.taxonomy import GreenGenesProcessedTaxonomy
class GreenGenesProcessedTaxonomyTestCase(TestCase):
def setUp(self):
pass
def test_highest_res_rank_tax_string_full(self):
test_str = "k__Fungi;p__Ascomycota;c__Eurotiomycetes;o__Eurotiales;f__Trichocomaceae;g__Aspergillus;s__Aspergillus bombycis"
tax = GreenGenesProcessedTaxonomy(test_str)
self.assertEqual(tax.highest_res_rank, 'species')
def test_highest_res_rank_tax_string_short(self):
test_str = "k__Fungi;p__Ascomycota;c__Dothideomycetes;o__Pleosporales;f__Pleosporaceae"
tax = GreenGenesProcessedTaxonomy(test_str)
self.assertEqual(tax.highest_res_rank, 'family')
test_str = "k__Fungi;p__Ascomycota;c__Eurotiomycetes;o__Eurotiales;f__Trichocomaceae;g__Aspergillus"
tax = GreenGenesProcessedTaxonomy(test_str)
self.assertEqual(tax.highest_res_rank, 'genus')
def test_highest_res_rank_tax_string_contains_unidentified(self):
test_str = "k__Fungi;p__Ascomycota;c__Dothideomycetes;o__unidentified;f__Pleosporaceae"
tax = GreenGenesProcessedTaxonomy(test_str)
self.assertEqual(tax.highest_res_rank, 'class')
test_str = "k__Fungi;p__Ascomycota;c__unidentified;o__unidentified"
tax = GreenGenesProcessedTaxonomy(test_str)
self.assertEqual(tax.highest_res_rank, 'phylum')
def test_highest_res_rank_tax_string_contains_emptystr(self):
test_str = "k__Fungi;p__Ascomycota;c__;o__;f__"
tax = GreenGenesProcessedTaxonomy(test_str)
self.assertEqual(tax.highest_res_rank, 'phylum')
test_str = "k__Fungi;p__Ascomycota;c__;o__unidentified"
tax = GreenGenesProcessedTaxonomy(test_str)
self.assertEqual(tax.highest_res_rank, 'phylum')
def test_highest_res_rank_tax_string_unassigned(self):
unassigned_test_strings = []
unassigned_test_strings.append("No blast hit")
unassigned_test_strings.append("unassigned")
unassigned_test_strings.append("Unassigned")
unassigned_test_strings.append("k__")
unassigned_test_strings.append("k__unidentified")
unassigned_test_strings.append("k__Unidentified")
unassigned_test_strings.append("k__unidentified;")
for test_str in unassigned_test_strings:
tax = GreenGenesProcessedTaxonomy(test_str)
self.assertEqual(tax.highest_res_rank_index, -1)
self.assertEqual(tax.highest_res_rank, 'unassigned')
if __name__ == "__main__":
from unittest import main
main()
|
bassio/omicexperiment
|
omicexperiment/tests/test_taxonomy.py
|
Python
|
bsd-3-clause
| 2,654
|
[
"BLAST"
] |
8f399f8eef7394809842489c51fea786437c6a49a160557bcc1f156026e25621
|
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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
import os.path
import subprocess # pylint: disable=unused-import
import pytest # pylint: disable=unused-import
import pysam
from tool.bam_utils import bamUtils
def touch(path):
"""
Functio to create empty test files for functions
"""
with open(path, 'a'):
os.utime(path, None)
@pytest.mark.code
def test_bam_index(mocker):
"""
Test the bam_index function code
"""
cmd_view = ' '.join([
'samtools index',
'-b',
'example.bam',
'example.bam_tmp.bai'
])
mocker.patch('subprocess.Popen')
touch('example.bam')
touch('example.bam_tmp.bai')
result = bamUtils.bam_index('example.bam', 'example.bam.bai')
subprocess.Popen.assert_called_once_with(cmd_view, shell=True) # pylint: disable=no-member
assert result is True
@pytest.mark.code
def test_bam_sort(mocker):
"""
Test the bam_sort function code
"""
mocker.patch('pysam.sort')
result = bamUtils.bam_sort('example.bam')
pysam.sort.assert_called_once_with( # pylint: disable=no-member
'-o', 'example.bam', '-T', 'example.bam' + '_sort', 'example.bam')
assert result is True
@pytest.mark.code
def test_bam_merge_list(mocker):
"""
Test the bam_merge list function code
"""
mocker.patch('pysam.merge')
touch('example_1.bam')
touch('example_2.bam')
result = bamUtils.bam_merge(['example_1.bam', 'example_2.bam'])
pysam.merge.assert_called_once_with( # pylint: disable=no-member
'-f', 'example_1.bam_merge.bam', 'example_1.bam', 'example_2.bam')
assert result is False
@pytest.mark.code
def test_bam_merge(mocker):
"""
Test the bam_merge function code
"""
mocker.patch('pysam.merge')
touch('example_1.bam')
touch('example_2.bam')
result = bamUtils.bam_merge('example_1.bam', 'example_2.bam')
pysam.merge.assert_called_once_with( # pylint: disable=no-member
'-f', 'example_1.bam_merge.bam', 'example_1.bam', 'example_2.bam')
assert result is False
|
Multiscale-Genomics/mg-process-fastq
|
tests/test_code_bam_utils.py
|
Python
|
apache-2.0
| 2,736
|
[
"pysam"
] |
5374a1b7cd5934f0294ef3c6f46d29a1087262416d85c4c0ed894d3cce36c8ed
|
# Copyright (C) 2012,2013
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ 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.
#
# ESPResSo++ 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/>.
r"""
*************************************
**espressopp.interaction.SoftCosine**
*************************************
This class provides methods to compute forces and energies ofthe SoftCosine potential.
.. math::
V(r) = A \left[ 1.0 + cos \left( \frac{\pi r}{r_c} \right) \right]
.. function:: espressopp.interaction.SoftCosine(A, cutoff, shift)
:param A: (default: 1.0)
:param cutoff: (default: infinity)
:param shift: (default: "auto")
:type A: real
:type cutoff:
:type shift:
.. function:: espressopp.interaction.VerletListSoftCosine(stor)
:param stor:
:type stor:
.. function:: espressopp.interaction.VerletListSoftCosine.setPotential(type1, type2, potential)
:param type1:
:param type2:
:param potential:
:type type1:
:type type2:
:type potential:
.. function:: espressopp.interaction.CellListSoftCosine(stor)
:param stor:
:type stor:
.. function:: espressopp.interaction.CellListSoftCosine.setPotential(type1, type2, potential)
:param type1:
:param type2:
:param potential:
:type type1:
:type type2:
:type potential:
.. function:: espressopp.interaction.FixedPairListSoftCosine(system, vl, potential)
:param system:
:param vl:
:param potential:
:type system:
:type vl:
:type potential:
.. function:: espressopp.interaction.FixedPairListSoftCosine.setPotential(potential)
:param potential:
:type potential:
"""
from espressopp import pmi, infinity
from espressopp.esutil import *
from espressopp.interaction.Potential import *
from espressopp.interaction.Interaction import *
from _espressopp import interaction_SoftCosine, \
interaction_VerletListSoftCosine, \
interaction_CellListSoftCosine, \
interaction_FixedPairListSoftCosine
class SoftCosineLocal(PotentialLocal, interaction_SoftCosine):
def __init__(self, A=1.0, cutoff=infinity, shift="auto"):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
if shift =="auto":
cxxinit(self, interaction_SoftCosine, A, cutoff)
else:
cxxinit(self, interaction_SoftCosine, A, cutoff, shift)
class VerletListSoftCosineLocal(InteractionLocal, interaction_VerletListSoftCosine):
'The (local) SoftCosine interaction using Verlet lists.'
def __init__(self, vl):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
cxxinit(self, interaction_VerletListSoftCosine, vl)
def setPotential(self, type1, type2, potential):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
self.cxxclass.setPotential(self, type1, type2, potential)
def getPotential(self, type1, type2):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
return self.cxxclass.getPotential(self, type1, type2)
class VerletListSoftCosineLocal(InteractionLocal, interaction_VerletListSoftCosine):
def __init__(self, stor):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
cxxinit(self, interaction_VerletListSoftCosine, stor)
def setPotential(self, type1, type2, potential):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
self.cxxclass.setPotential(self, type1, type2, potential)
class CellListSoftCosineLocal(InteractionLocal, interaction_CellListSoftCosine):
def __init__(self, stor):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
cxxinit(self, interaction_CellListSoftCosine, stor)
def setPotential(self, type1, type2, potential):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
self.cxxclass.setPotential(self, type1, type2, potential)
class FixedPairListSoftCosineLocal(InteractionLocal, interaction_FixedPairListSoftCosine):
def __init__(self, system, vl, potential):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
cxxinit(self, interaction_FixedPairListSoftCosine, system, vl, potential)
def setPotential(self, potential):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
self.cxxclass.setPotential(self, potential)
if pmi.isController:
class SoftCosine(Potential):
'The SoftCosine potential.'
pmiproxydefs = dict(
cls = 'espressopp.interaction.SoftCosineLocal',
pmiproperty = ['A']
)
class VerletListSoftCosine(Interaction):
__metaclass__ = pmi.Proxy
pmiproxydefs = dict(
cls = 'espressopp.interaction.VerletListSoftCosineLocal',
pmicall = ['setPotential','getPotential']
)
class CellListSoftCosine(Interaction):
__metaclass__ = pmi.Proxy
pmiproxydefs = dict(
cls = 'espressopp.interaction.CellListSoftCosineLocal',
pmicall = ['setPotential']
)
class FixedPairListSoftCosine(Interaction):
__metaclass__ = pmi.Proxy
pmiproxydefs = dict(
cls = 'espressopp.interaction.FixedPairListSoftCosineLocal',
pmicall = ['setPotential']
)
|
capoe/espressopp.soap
|
src/interaction/SoftCosine.py
|
Python
|
gpl-3.0
| 6,469
|
[
"ESPResSo"
] |
70b48633ba41aadd32913714ead80bf25b0fd094fdabc772246fe87733fce206
|
from setuptools import setup
setup(
name = 'linearsolve',
packages = ['linearsolve'],
version = '3.4.10',
description = 'A module for approximating, solving, and simulating dynamic stochastic general equilibrium (DSGE) models',
author = 'Brian C. Jenkins',
author_email = 'bcjenkin@uci.edu',
url = 'https://github.com/letsgoexploring/linearsolve-package',
download_url = 'https://github.com/letsgoexploring/linearsolve-package/raw/master/dist/linearsolve-3.4.10.tar.gz',
keywords = ['economics','solution','dsge','schur','macroconomics','rbc','new keynesian','business cycles'],
classifiers = [],
)
|
letsgoexploring/linearsolve-package
|
setup.py
|
Python
|
mit
| 619
|
[
"Brian"
] |
951f90bbf689017d8b8eef1aeae4059066cd9372b6d155ec3efd9d566dc045eb
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
create_barcode_proj.py
'''
#import pdb; pdb.set_trace()
#import the necessary libraries
import sys, string, argparse, textwrap, os, time, shutil, re
from dnabarcodes import dbcodeConfig
from dnabarcodes.dnabarcodes_class import DNABarcodes
from test_regex import validate_regex
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent('''\
DNABarcodes
============
Process DNA barcodes through quality control and annotation steps.
By
Anders Goncalves da Silva and Rohan H. Clarke
Monash University
(C) 2014
'''))
parser.add_argument('-c', metavar='FILENAME', type=argparse.FileType('r'), help='a config file')
args = parser.parse_args()
if args.c:
cfg = dbcodeConfig.read(args.configfile)
elif os.path.isfile('dbcode.cfg'):
cfg = dbcodeConfig.read('dbcode.cfg')
else:
cfg = dbcodeConfig.create()
#########################################################################################
## Menu items ###########################################################################
#########################################################################################
def main_menu():
global cfg
while True:
os.system('clear')
print "#Welcome to DNABarcodes setup utility#"
print "====================================="
print "Version 0.1dev"
print "Authors: Anders Goncalves da Silva and Rohan H. Clarke"
print "Monash University"
print "(C) 2014"
print "Date: April 2014"
print "-------------------------------------------------------"
print ""
print "Please select from one of the available options:"
print ""
print "(P)roject metadata"
print "(T)asks setup"
print "(R)eporting options"
print "(S)ave configuration"
print "(E)xecute DNAbarcodes"
print "(Q)uit"
print ""
menu_item=raw_input('---> ')
if menu_item not in ['P','T','S','R','E', 'Q']:
print 'Please choose either P, T, R, S, E or Q...'
print ''
raw_input("Press any key to continue...")
main_menu()
if menu_item == 'Q':
break
if menu_item == 'P':
metadata_menu()
if menu_item == 'T':
task_menu()
if menu_item == 'R':
reports_menu()
if menu_item == 'S':
fname = os.path.join(cfg.get('metadata','home_folder'),'dbcode.cfg')
fh = open(fname,'wb')
cfg.write(fh)
fh.close()
print 'Config file {} saved successfully'.format(fname)
raw_input('Press any key to continue...')
if menu_item == 'E':
run = DNABarcodes(cfg)
run.sync()
break
def metadata_menu():
global cfg
while True:
os.system('clear')
print "Metadata menu"
print "============="
print "(P)roject basename: {} [project basename]".format(cfg.get('metadata','project_basename'))
print "(H)ome folder: {} [the location and name of the project's main folder]".format(cfg.get('metadata','home_folder'))
print "(T)race data folder: {} ({}) [location of raw trace data (and trace file extension)]".format(cfg.get('metadata','traces_folder'),cfg.get('metadata','trace_ext'))
print "(E)xpression: {} [regex to search for trace files]".format(cfg.get('metadata','regex'))
print "(A)ssemblies folder: {} [folder where individual sample assemblies are stored]".format(cfg.get('metadata','barcodes_folder'))
print "(O)utput folder: {} [folder where reports and QC'ed barcodes are stored]".format(cfg.get('metadata','reports_folder'))
print "(R)eferences folder: {} [folder where reference FASTA files are kept]".format(cfg.get('metadata','ref_folder'))
print "(C)opy existing phd files: {}".format(cfg.get('metadata','copy_phd'))
print "(B)ack to main menu."
print ""
meta_menu_item=raw_input('--> ')
if meta_menu_item not in ['P','H'',T','E','A','O','R','C','B']:
print 'Please choose either T, E, H, R, ,C or B.'
print ''
raw_input("Press any key to continue...")
metadata_menu()
if meta_menu_item=='B':
break
if meta_menu_item=='P':
print "Enter a new basename (leave blank for default: {}):".format(cfg.get('metadata','project_basename'))
tmp=raw_input('--> ')
if tmp=='':
continue
else:
cfg.set('metadata','project_basename',tmp)
if meta_menu_item=='E':
print "Enter a new regex (leave blank for default):"
tmp=raw_input('--> ')
if tmp=='':
pass
else:
cfg.set('metadata','regex',tmp)
while True:
print "Would you like to test the regex expression? [y/n]"
ans = raw_input('--> ')
if ans not in ['y','n']:
print 'Please print y or n...'
raw_input('Press any key to continue...')
continue
elif ans == 'n':
print 'It is recommended you test your regex to ensure it is working before continuning'
raw_input('Press any key to return to the menu...')
break
else:
if validate_regex(cfg.get('metadata','regex'),cfg.get('metadata','traces_folder'),cfg.get('metadata','trace_ext')):
print ""
print "Your regex is finding a number of samples that match."
print "Double check if it is finding the right number of files"
raw_input('Press any key to continue...')
break
else:
print ''
print ''
print "It seems the regex tester failed to find any matchs"
print "Test it out out at http://regexpal.com."
print "If it works on regexpal but not with DNABarcodes, email andersgs at googlemail dot com"
print "Please send a test trace file and your regex."
raw_input("Press any key to continue...")
break
if meta_menu_item=='H':
while True:
print "Enter a new home folder (leave blank for default):"
tmp=raw_input('--> ')
if tmp=='':
pass
else:
home_folder=cfg.set('metadata','home_folder',os.path.abspath(tmp))
if test_dir(cfg.get('metadata','home_folder')) =='break':
break
if meta_menu_item=='T':
while True:
print "Enter the name for the raw trace data folder for your project (leave blank for default)."
print "If the folder does not exist, it will be created. If you already"
print "have raw traces, you will have the opportunity to copy them over."
tmp=raw_input('--> ')
if tmp=='':
pass
else:
raw_folder=cfg.set('metadata','traces_folder',os.path.join(cfg.get('metadata','home_folder'),tmp))
print "Please type the extension to the trace files (if blank default=ab1)"
tmp = raw_input('--> ')
if tmp == '':
continue
else:
cfg.set('metadata','trace_ext',tmp)
if test_dir(cfg.get('metadata','traces_folder')) == 'break':
traces = []
for dr,dn,fn in os.walk(cfg.get('metadata','traces_folder')):
for f in fn:
if re.search(cfg.get('metadata','trace_ext'),f):
traces.append(f)
if os.listdir(cfg.get('metadata','traces_folder'))==[] or traces == []:
print "It appears that your raw data folder is empty."
print "Would you like to copy over sequencing data run folders now?[y/n]"
while True:
ans = raw_input('--> ')
if ans not in ['y','n']:
print "Answer should be 'y' or 'n'. Please try again"
raw_input("Please press any to try again...")
else:
break
if ans == 'n':
break
else:
while True:
print 'Please enter a folder path to the folder containing'
print 'folders with sequencing trace data (one sub-folder per run)'
while True:
src = os.path.abspath(raw_input('--> '))
total_runs = 0
total_traces = 0
if validate_dir(src):
run_folders = os.listdir(src)
for folder in run_folders:
if folder[0] == '.':
continue
else:
total_runs += 1
trace_folder = os.path.join(src,folder)
trace_files = [f for f in os.listdir(trace_folder) if re.search(cfg.get('metadata','trace_ext'),f)]
if trace_files != []:
total_traces += 1
dest_folder = os.path.join(cfg.get('metadata','traces_folder'),folder)
os.mkdir(dest_folder)
for trace_file in trace_files:
shutil.copy(os.path.join(trace_folder,trace_file),dest_folder)
print "Successfully copied {} run folders, for a total {} traces.".format(total_runs,total_traces)
raw_input('Press any key to return to the menu...')
break
else:
print "Folder did not contain any trace files"
print "Please enter a new folder name"
run_input('Press any key to return to the menu...')
break
break
else:
print "It appears that your raw data folder already has some traces."
print "Would you like to copy over sequencing data run folders now?[y/n]"
while True:
ans = raw_input('--> ')
if ans not in ['y','n']:
print "Answer should be 'y' or 'n'. Please try again"
raw_input("Please press any to try again...")
else:
break
if ans == 'n':
break
else:
while True:
print 'Please enter a folder path to the folder containing'
print 'folders with sequencing trace data (one sub-folder per run)'
while True:
src = os.path.expanduser(raw_input('--> '))
if validate_dir(src):
run_folders = os.listdir(src)
for folder in run_folders:
if folder[0] == '.':
continue
else:
trace_folder = os.path.join(src,folder)
trace_files = [f for f in os.listdir(trace_folder) if re.search(cfg.get('metadata','trace_ext'),f)]
if trace_files != '[]':
dest_folder = os.path.join(cfg.get('metadata','traces_folder'),folder)
os.mkdir(dest_folder)
for trace_file in trace_files:
shutil.copy(os.path.join(trace_folder,trace_file),dest_folder)
break
else:
print "Folder did not contain any trace files"
print "Please enter a new folder name"
run_input('Press any key to return to the menu...')
break
break
else:
print 'Folder {} does not exist or could not be created.'.format(cfg.get('metadata','traces_folder'))
print 'Please try again.'
raw_input('Press any key to return to the menu')
break
if meta_menu_item=='A':
while True:
print "Please enter the full path for the assemblies folder"
print "Default is {} - leave blank to accept the default".format(cfg.get('metadata','barcodes_folder'))
tmp = raw_input('--> ')
if tmp == '':
if test_dir(cfg.get('metadata','barcodes_folder')) == 'break':
break
else:
if test_dir(tmp) == 'break':
cfg.set('metadata','barcodes_folder',tmp)
break
if meta_menu_item=='O':
while True:
print "Please enter the full path for the output folder"
print "Default is {} - leave blank to accept the default".format(cfg.get('metadata','reports_folder'))
tmp = raw_input('--> ')
if tmp == '':
if test_dir(cfg.get('metadata','reports_folder')) == 'break':
break
else:
if test_dir(tmp) == 'break':
cfg.set('metadata','reports_folder',tmp)
break
if meta_menu_item=='R':
while True:
print "Please enter the full path for the references folder"
print "Default is {} - leave blank to accept the default".format(cfg.get('metadata','ref_folder'))
tmp = raw_input('--> ')
if tmp == '':
if test_dir(cfg.get('metadata','ref_folder')) == 'break':
break
else:
if test_dir(tmp) == 'break':
cfg.set('metadata','ref_folder',tmp)
break
if meta_menu_item=='C':
while True:
print "Copy existing phd files ((T)rue or (F)alse) (Default: {}.".format(cfg.get('metadata','copy_phd'))
print "By copying over phd files into phredPhrap assembly folders"
print "You will skip Phred base-calling step."
tmp=raw_input('--> ')
if tmp=='':
continue
elif tmp not in ['T','F']:
print "Please select: (T)rue or (F)alse."
print ""
raw_input("Press any key to continue...")
else:
if tmp =='T':
cfg.set('metadata','copy_phd','True')
while True:
phd_files = []
for dr,dn,fn in os.walk(cfg.get('metadata','traces_folder')):
for f in fn:
if re.search('phd',f):
phd_files.append(f)
if phd_files == []:
print "There appears to be no phd files in your raw data folder."
print "Would you like to copy them over from another file? [y/n]"
while True:
ans = raw_input('--> ')
if ans not in ['y','n']:
print 'Please answer y or n...'
raw_input('Press any key to continue...')
else:
break
if ans == 'n':
print 'You have selected to copy phd files, yet there seems to be none in your raw data folder.'
print 'This may lead to problems when running DNABarcodes.'
print ' Please make sure to copy the phd files over before running the program'
raw_input('Press any key to return to the menu...')
break
else:
while True:
print 'Please enter the path to the phd files folder.'
print 'The path should be to a master folder containing sub-folders named by run'
print 'As when copying over trace files'
src = os.path.abspath(raw_input('--> '))
if validate_dir(src):
phd_folders = os.listdir(src)
total_folders = 0
total_files = 0
for folder in phd_folders:
if folder[0] == '.':
continue
total_folders += 1
src_folder = os.path.join(src,folder)
dest_folder = os.path.join(cfg.get('metadata','traces_folder'),folder)
files = os.listdir(src_folder)
for fi in files:
if re.search('phd',fi):
total_files += 1
shutil.copy(os.path.join(src_folder,fi),dest_folder)
if total_files == 0:
print 'Found no phd files in {}'.format(src)
print "Would you like to enter a new folder name? [y/n]"
while True:
ans = raw_input('--> ')
if ans not in ['y','n']:
print 'Please enter y or n'
raw_input('Press any key to continue...')
else:
break
if ans == 'y':
continue
else:
print 'Please make sure to copy the phd files to their respective run folders'
print 'in the {} folder before running DNABarcodes.'
break
else:
print "Copied {} phd files from {} folders".format(total_files,total_folders)
raw_input('Press any key to continue')
break
else:
print "Could find the folder {}".format(src)
print "Would you like to enter a new folder name? [y/n]"
while True:
ans = raw_input('--> ')
if ans not in ['y','n']:
print 'Please enter y or n'
raw_input('Press any key to continue...')
else:
break
if ans == 'y':
continue
else:
break
break
else:
print "Found phd files in your raw data folder."
break
break
else:
cfg.set('metadata','copy_phd','False')
break
def task_menu():
global cfg
while True:
os.system('clear')
print "Tasks menu"
print "============="
print "(P)hredPhrap: {} [run phredPhrap]".format(cfg.get('tasks','run_phredphrap'))
print "(V)ector/flank region database: {} [database for use with cross_match]".format(cfg.get('tasks','vector_db'))
print "(N)CBI Blast: {} ({}) [run NCBI Blast (with database)]".format(cfg.get('tasks','run_wwwBlast'),cfg.get('tasks','wwwBlast_db'))
print "(L)ocal Blast: {} ({}) [run local Blast (with database)]".format(cfg.get('tasks','run_localBlast'),cfg.get('tasks','localBlast_db'))
print "(C)orrect reading frame: {} ({}) [correct reading frame (with protein database)]".format(cfg.get('tasks','correct_readingFrame'),cfg.get('tasks','localBlastX_db'))
print "(B)ack to main menu."
print ""
task_menu_item=raw_input('--> ')
if task_menu_item not in ['P','V','N','L','C','B']:
print 'Please choose either P, N, L, C, B..'
print ''
raw_input("Press any key to continue...")
task_menu()
if task_menu_item=='B':
break
if task_menu_item=='P':
while True:
print "Run phredPhrap ((T)rue or (F)alse) (Default {}):".format(cfg.get('tasks','run_phredphrap'))
tmp=raw_input('--> ')
if tmp=='':
break
elif tmp not in ['T','F']:
print "Please select: (T)rue or (F)alse."
print ""
raw_input("Press any key to continue...")
else:
if tmp =='T':
cfg.set('tasks','run_phredphrap','True')
else:
cfg.set('tasks','run_phredphrap','False')
print "*****WARNING*****"
print "By not running phredPhrap, the rest of DNA Barcodes"
print " might not work properly."
print "*****WARNING*****"
raw_input("Press any key to continue...")
break
if task_menu_item=='V':
while True:
print "Please give the full path to the FASTA file containing flanking regions to the barcode for use in cross_match"
print "Default is {} - leave blank for default".format(cfg.get('tasks','vector_db'))
tmp = raw_input('--> ')
if tmp == '':
break
else:
if os.path.isfile(tmp):
cfg.set('tasks','vector_db',tmp)
else:
print "File {} does not exist in this path.".format(tmp)
print "Do you wish to accept this filename [y] or do you wish to enter a new one [n] or accept the default [c]?"
ans = raw_input('--> ')
if tmp == 'y':
print "Ok, but make sure that it exists before running dnabarcodes."
raw_input("Press any key to continue...")
break
elif tmp == 'n':
continue
elif tmp == 'c':
print "Accepting default {}.".format(cfg.get('tasks','cfg'))
raw_input('Press any key to continue')
break
else:
continue
if task_menu_item=='N':
while True:
print "Run NCBI BLAST ((T)rue or (F)alse) (Default: {} with db {}):".format(cfg.get('tasks','run_wwwBlast'),cfg.get('tasks','wwwBlast_db'))
tmp=raw_input('--> ')
if tmp=='':
break
elif tmp not in ['T','F']:
print "Please select: (T)rue or (F)alse."
print ""
raw_input("Press any key to continue...")
else:
if tmp == 'T':
cfg.set('tasks','run_wwwBlast','True')
else:
cfg.set('tasks','run_wwwBlast','False')
if run_wwwBlast:
while True:
print "Please name the BLAST database (nr,nt - leave blank for default {}):".format(cfg.get('tasks','wwwBlast_db'))
tmp = raw_input('--> ')
if tmp=='':
break
elif tmp not in ['nr','nt']:
print "Please select either nr or nt"
print ""
raw_input("Press any key to continue...")
else:
cfg.set('tasks','rwwwBlast_db',tmp)
break
break
if task_menu_item=='L':
while True:
print "Run local BLAST ((T)rue or (F)alse) (Default: {} with db {}:".format(cfg.get('tasks','run_localBlast'),cfg.get('tasks','localBlast_db'))
tmp=raw_input('--> ')
if tmp=='':
break
elif tmp not in ['T','F']:
print "Please select: (T)rue or (F)alse."
print ""
raw_input("Press any key to continue...")
else:
if tmp == 'T':
cfg.set('tasks','run_localBlast','True')
else:
cfg.set('tasks','run_localBlast','False')
if run_localBlast:
while True:
print "Type to the path to the local BLAST database (leave blank for default):"
tmp = raw_input('--> ')
if tmp=='':
print "Please type in the location of a FASTA file with reference nucleotide sequences"
else:
cfg.set('tasks','localBlast_db',tmp)
if os.path.isfile(cfg.get('tasks','localBlast_db')):
break
else:
print "The file {} does seem to exist".format(cfg.get('tasks','localBlast_db'))
print "Please try again..."
if raw_input("Please press 'c' to cancel, or any key to try again...") == 'c':
break
else:
continue
break
if task_menu_item=='C':
while True:
print "Ensure that all barcodes are in the same reading frame ((T)rue or (F)alse) (Default: {}):".format(cfg.get('tasks','correct_readingFrame'),cfg.get('task','localBlastX_db'))
tmp=raw_input('--> ')
if tmp=='':
break
elif tmp not in ['T','F']:
print "Please select: (T)rue or (F)alse."
print ""
raw_input("Press any key to continue...")
else:
if tmp == 'T':
cfg.set('tasks','correct_readingFrame','True')
else:
cfg.set('tasks','correct_readingFrame','False')
if correct_readingFrame:
while True:
print "Please type the path to the BLASTX database (leave blank for default):"
tmp = raw_input('--> ')
if tmp=='':
print "Please type in the location of a FASTA file with reference protein sequences"
else:
cfg.set('tasks','localBlastX_db',os.path.abspath(tmp))
if os.path.isfile(cfg.get('tasks','localBlastX_db')):
break
else:
print "The file {} does seem to exist".format(cfg.get('tasks','localBlastX_db'))
print "Please try again..."
if raw_input("Please press 'c' to cancel, or any key to try again...") == 'c':
break
else:
continue
break
def reports_menu():
global cfg
global out_barcodes
global bcode_format
global bcode_fname
global bcode_minQ
global bcode_minQP
while True:
os.system('clear')
print "Reports menu"
print "============="
print "(O)utput barcodes: {} [should a barcodes file be outputted]".format(cfg.get('reports','out_barcodes'))
print "(D)NA Barcodes format: {} [output barcodes in what format]".format(cfg.get('reports','bcode_format'))
print "(F)ilename for barcodes file: {} [barcode filename without extension]".format(cfg.get('reports','bcode_fname'))
print "(M)inimum Phred-base quality to accept base-call: {} [default=20]".format(cfg.get('reports','bcode_minQ'))
print "(P)roportion of bases with at least minimum quality: {} [default=0.975]".format(cfg.get('reports','bcode_minQP'))
print "(B)ack to main menu."
print ""
reports_menu_item=raw_input('--> ')
if reports_menu_item not in ['O','D','F','M','P','B']:
print 'Please choose either O, D, F, M, P, B..'
print ''
raw_input("Press any key to continue...")
reports_menu()
if reports_menu_item=='B':
break
if reports_menu_item=='O':
while True:
print "Output a barcodes file to the reporting directory ((T)rue or (F)alse) (Default: {}):".format(cfg.get('reports','out_barcodes'))
tmp=raw_input('--> ')
if tmp=='':
break
elif tmp not in ['T','F']:
print "Please select: (T)rue or (F)alse."
print ""
raw_input("Press any key to continue...")
else:
if tmp == 'T':
cfg.set('reports','out_barcodes','True')
else:
cfg.set('reports','out_barcodes','False')
break
if reports_menu_item=='D':
while True:
print "Output barcodes in what format (fa:fasta or fq:fastq) (Default: {}):".format(cfg.get('reports','bcode_format'))
tmp=raw_input('--> ')
if tmp=='':
break
elif tmp not in ['fa','fasta','fq','fastq']:
print "Please select: fa for FASTA or fq for FASTQ."
print ""
raw_input("Press any key to continue...")
else:
if tmp in ['fa','fasta']:
cfg.set('reports','bcode_format','fasta')
else:
cfg.set('reports','bcode_format','fastq')
break
if reports_menu_item=='F':
print "Type in a DNA barcodes filename (without extension) (Default: {}):".format(cfg.get('reports','bcode_fname'))
tmp=raw_input('--> ')
if tmp=='':
continue
else:
cfg.set('reports','bcode_fname',tmp)
break
if reports_menu_item=='M':
while True:
print "Choose a minimum Phred base-quality score to filter barcodes (default={}).".format(cfg.get('reports','bcode_minQ'))
print "Acceptable values are integers between 0 and 126."
print "A value of zero means no filtering."
tmp=raw_input('--> ')
try:
tmp=int(tmp)
except:
print "Please select an integer value between 1 and 126."
print ""
raw_input("Press any key to continue...")
continue
if tmp=='':
break
elif tmp < 0 or tmp > 126:
print "Please select an integer value between 1 and 126."
print ""
raw_input("Press any key to continue...")
continue
else:
cfg.set('reports','bcode_minQ',str(tmp))
break
if reports_menu_item=='P':
while True:
print "Choose a minimum proportion of bases with the minimum Phred base-quality"
print "score to filter barcodes (default={}).".format(cfg.get('reports','bcode_minQP'))
print "Acceptable values are floats between 0 and 1."
print "A value of zero means no filtering."
print "A value of 1 means 100% of bases must have a base-quality score"
print "equal to or larger than the minimum value of {}.".format(cfg.get('reports','bcode_minQ'))
tmp=raw_input('--> ')
try:
tmp=float(tmp)
except:
print "Please select float between 0 and 1 (e.g., 0.5)."
print ""
raw_input("Press any key to continue...")
continue
if tmp=='':
break
elif tmp < 0 or tmp > 1:
print "Please select float between 0 and 1 (e.g., 0.5)."
print ""
raw_input("Press any key to continue...")
continue
else:
cfg.set('reports','bcode_minQP',str(tmp))
break
#########################################################################################
## Auxiliary functions ##################################################################
#########################################################################################
def validate_dir(path):
'''
Check if a directory exists
'''
if os.path.exists(os.path.abspath(path)):
return True
else:
return False
def test_dir(path):
'''
test if directory exists, if not create it
'''
path = os.path.expanduser(path)
dir = validate_dir(path)
if dir:
print "Congratulations, the folder {} exists.".format(path)
print "Please make sure you are not overriding any pre-existing projects."
raw_input("Please press any key to continue...")
return 'break'
else:
print "Folder {} does not exist".format(path)
print "Would you like to create it? [y/n]"
while True:
ans = raw_input("--> ")
if ans not in ['y','n']:
print "Answer should be 'y' or 'n'. Please try again"
raw_input("Please press any to try again...")
else:
break
if ans =='n':
print 'Could not create folder {}, please try again.'.format(path)
raw_input("Please press any key to continue...")
return 'break'
else:
try:
os.mkdir(path)
print "Successfully created folder {}.".format(path)
raw_input("Please press any key to continue...")
return 'break'
except:
print "You do not seem to have sufficient priviledges to create this directory"
print "or, there was something wrong with your path"
print "Would you like to try again? [y/n]"
while True:
ans = raw_input("--> ")
if ans not in ['y','n']:
print "Answer should be 'y' or 'n'. Please try again"
else:
break
if ans =='y':
return 'continue'
else:
return 'break'
#########################################################################################
## Main function ########################################################################
#########################################################################################
def main():
'''
Create a new project from a parameter file or from interaction with the user
'''
main_menu()
if __name__=="__main__":
main()
|
andersgs/DNABarcodes
|
bin/create_barcode_proj.py
|
Python
|
gpl-3.0
| 28,119
|
[
"BLAST"
] |
dcc9ba040cd04fee44bd597a0667506a7c8031be4f9836589b5ee41c4abefc33
|
#! /usr/bin/env python
import sys
sys.path.insert(0, '../')
sys.path.insert(0, '../rnn')
from config import config as cc
cc.loadConfig('../local/config.yml')
cc.exp['params'] = {}
cc.exp['params']['data']={}
cc.exp['params']['rnn']={}
import db.db as db
import pandas as pd
import numpy as np
from rdkit import Chem
from rdkit.Chem import Descriptors
from rdkit.Chem import MACCSkeys
import data
from sets import Set
LELIMIT = 10000
SICHO_RIPTORS = Set(['MinAbsPartialCharge','HeavyAtomMolWt','MaxAbsPartialCharge','MinAbsEStateIndex','Chi3n','HallKierAlpha','PEOE_VSA1','PEOE_VSA10','PEOE_VSA11','PEOE_VSA12','PEOE_VSA13','PEOE_VSA14','PEOE_VSA2','PEOE_VSA3','PEOE_VSA6','PEOE_VSA8','PEOE_VSA9','SMR_VSA1','SMR_VSA10','SMR_VSA3','SMR_VSA6','SMR_VSA9','SlogP_VSA10','SlogP_VSA3','SlogP_VSA4','SlogP_VSA6','TPSA','EState_VSA3','EState_VSA5','EState_VSA7','EState_VSA8','VSA_EState9','NHOHCount','NumAliphaticHeterocycles','NumAromaticHeterocycles','MolLogP','fr_Ar_COO','fr_C_O','fr_Imine','fr_NH1','fr_Ndealkylation2','fr_amide','fr_aryl_methyl','fr_ester','fr_ether','fr_furan','fr_imidazole','fr_methoxy','fr_piperzine','fr_pyridine','fr_sulfide','fr_thiazole','fr_urea'])
DOWNLOAD_TABLE = 'output.target_a549'
DOWNLOAD_COLS = ['canonical_smiles','standard_value_log']
WHERE = 'length(canonical_smiles) <= 80'
LIMIT = None
# DOWNLOAD_TABLE = 'output.target_geminin_deduplicated'
# DOWNLOAD_COLS = ['molregno','canonical_smiles','is_testing','standard_value_min','standard_value_max','standard_value_count','standard_value_std','standard_value_relative_std','standard_value_median']
# SEND_TABLE = 'output.target_geminin_deduplicated_rdkit_maccs'
def getData(con):
query = 'SELECT {} FROM {}'.format(
','.join(['"{}"'.format(x) for x in DOWNLOAD_COLS]),
DOWNLOAD_TABLE)
if WHERE:
query += ' WHERE {}'.format(WHERE)
if LIMIT:
query += ' LIMIT {}'.format(LIMIT)
print(query)
df = pd.read_sql(
sql = query,
con = con)
return df
def formatNonSequential(smilesDf):
smilesMaxLen = 80
nonSeq = np.zeros((len(smilesDf), smilesMaxLen, data.SMILES_ALPHABET_LEN))
# translate to one hot for smiles
for i,smiles in enumerate(smilesDf):
for j in range(smilesMaxLen):
transChar = data.SMILES_ALPHABET_LOOKUP_TABLE[data.SMILES_ALPHABET_UNKNOWN]
if j < len(smiles) and smiles[j] in data.SMILES_ALPHABET_LOOKUP_TABLE:
transChar = data.SMILES_ALPHABET_LOOKUP_TABLE[smiles[j]]
nonSeq[i][j][transChar] = 1
cols = []
for i in range(smilesMaxLen):
for sym in data.SMILES_ALPHABET:
cols.append('{}:{}'.format(i,sym))
# print(nonSeq.tolist()[0][0])
nonSeq = nonSeq.reshape(len(smilesDf),smilesMaxLen*data.SMILES_ALPHABET_LEN)
return pd.DataFrame(nonSeq, columns=cols)
def formatBagOfWrods(smilesDf):
smilesMaxLen = 80
nonSeq = np.zeros((len(smilesDf),data.SMILES_ALPHABET_LEN))
for i,smiles in enumerate(smilesDf):
for j in range(smilesMaxLen):
transChar = data.SMILES_ALPHABET_LOOKUP_TABLE[data.SMILES_ALPHABET_UNKNOWN]
if j < len(smiles) and smiles[j] in data.SMILES_ALPHABET_LOOKUP_TABLE:
transChar = data.SMILES_ALPHABET_LOOKUP_TABLE[smiles[j]]
nonSeq[i][transChar]+=1
df = pd.DataFrame(nonSeq, columns=data.SMILES_ALPHABET)
return df
con = db.getCon()
df = getData(con)
con.close()
nonSeq = formatNonSequential(df.canonical_smiles)
# nonSeq = formatBagOfWrods(df.canonical_smiles)
# print nonSeq.shape
nonSeq = nonSeq.loc[:,nonSeq.apply(pd.Series.nunique) != 1]
# print nonSeq.shape
dfNonSeq = pd.concat((nonSeq, df.standard_value_log), axis = 1)
# print(df.canonical_smiles)
# print(dfNonSeq.standard_value_log)
# dfNonSeq.to_csv('target_206_1977_nonseq_smiles.csv')
dfNonSeq.to_csv('../local/data/a549_nonseq_smiles.csv')
|
PMitura/smiles-neural-network
|
computing/non_seq_formatting.py
|
Python
|
bsd-3-clause
| 3,911
|
[
"RDKit"
] |
3d1168da38eb04aad7153ffb7588fef8bdf08ddbc2a318826d28cef19db5da5d
|
# Copyright (C) 2012-2018
# Max Planck Institute for Polymer Research
# Copyright (C) 2008-2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ 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.
#
# ESPResSo++ 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/>.
from espressopp.esutil import pmiimport
pmiimport('espressopp.analysis')
from espressopp.analysis.Observable import *
from espressopp.analysis.AnalysisBase import *
from espressopp.analysis.Temperature import *
from espressopp.analysis.Pressure import *
from espressopp.analysis.PressureTensor import *
from espressopp.analysis.PressureTensorLayer import *
from espressopp.analysis.PressureTensorMultiLayer import *
from espressopp.analysis.Configurations import *
from espressopp.analysis.ConfigurationsExt import *
from espressopp.analysis.ConfigurationsExtAdress import *
from espressopp.analysis.Velocities import *
from espressopp.analysis.CenterOfMass import *
from espressopp.analysis.NPart import *
from espressopp.analysis.NPartSubregion import *
from espressopp.analysis.SubregionTracking import *
from espressopp.analysis.MaxPID import *
from espressopp.analysis.AllParticlePos import *
from espressopp.analysis.IntraChainDistSq import *
from espressopp.analysis.NeighborFluctuation import *
from espressopp.analysis.OrderParameter import *
from espressopp.analysis.LBOutput import *
from espressopp.analysis.LBOutputScreen import *
from espressopp.analysis.LBOutputVzInTime import *
from espressopp.analysis.LBOutputVzOfX import *
from espressopp.analysis.CMVelocity import *
from espressopp.analysis.ConfigsParticleDecomp import *
from espressopp.analysis.VelocityAutocorrelation import *
from espressopp.analysis.MeanSquareDispl import *
from espressopp.analysis.MeanSquareInternalDist import *
from espressopp.analysis.Autocorrelation import *
from espressopp.analysis.RadialDistrF import *
from espressopp.analysis.StaticStructF import *
from espressopp.analysis.RDFatomistic import *
from espressopp.analysis.Energy import *
from espressopp.analysis.Viscosity import *
from espressopp.analysis.XDensity import *
from espressopp.analysis.XTemperature import *
from espressopp.analysis.XPressure import *
from espressopp.analysis.AdressDensity import *
from espressopp.analysis.RadGyrXProfilePI import *
from espressopp.analysis.Test import *
from espressopp.analysis.ParticleRadiusDistribution import *
from espressopp.analysis.SystemMonitor import *
from espressopp.analysis.PotentialEnergy import *
from espressopp.analysis.KineticEnergy import *
|
kkreis/espressopp
|
src/analysis/__init__.py
|
Python
|
gpl-3.0
| 3,120
|
[
"ESPResSo"
] |
42627e2aec48cbce938377b0496610f6ad13cdb7691a97c8593568c6c5ca7b8d
|
# Copyright (C) 2010-2019 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo 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.
#
# ESPResSo 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/>.
from .script_interface import ScriptObjectRegistry, ScriptInterfaceHelper, script_interface_register
import numpy as np
from itertools import product
@script_interface_register
class Constraints(ScriptObjectRegistry):
"""
List of active constraints. Add a :class:`espressomd.constraints.Constraint`
to make it active in the system, or remove it to make it inactive.
"""
_so_name = "Constraints::Constraints"
def add(self, *args, **kwargs):
"""
Add a constraint to the list.
Parameters
----------
constraint: :class:`espressomd.constraints.Constraint`
Either a constraint object...
\*\*kwargs : any
... or parameters to construct an
:class:`espressomd.constraints.ShapeBasedConstraint`
Returns
----------
constraint : :class:`espressomd.constraints.Constraint`
The added constraint
"""
if len(args) == 1:
if isinstance(args[0], Constraint):
constraint = args[0]
else:
raise TypeError(
"Either a Constraint object or key-value pairs for the parameters of a ShapeBasedConstraint object need to be passed.")
else:
constraint = ShapeBasedConstraint(**kwargs)
self.call_method("add", object=constraint)
return constraint
def remove(self, constraint):
"""
Remove a constraint from the list.
Parameters
----------
constraint : :obj:`espressomd.constraints.Constraint`
"""
self.call_method("remove", object=constraint)
def clear(self):
"""
Remove all constraints.
"""
self.call_method("clear")
class Constraint(ScriptInterfaceHelper):
"""
Base class for constraints. A constraint provides a force and
an energy contribution for a single particle.
"""
_so_name = "Constraints::Constraint"
@script_interface_register
class ShapeBasedConstraint(Constraint):
"""
Attributes
----------
only_positive : :obj:`bool`
Act only in the direction of positive normal,
only useful if penetrable is ``True``.
particle_type : :obj:`int`
Interaction type of the constraint.
particle_velocity : array_like of :obj:`float`
Interaction velocity of the boundary
penetrable : :obj:`bool`
Whether particles are allowed to penetrate the constraint.
shape : :class:`espressomd.shapes.Shape`
One of the shapes from :mod:`espressomd.shapes`
See Also
----------
espressomd.shapes : shape module that define mathematical surfaces
Examples
----------
>>> import espressomd
>>> from espressomd import shapes
>>> system = espressomd.System()
>>>
>>> # create first a shape-object to define the constraint surface
>>> spherical_cavity = shapes.Sphere(center=[5,5,5], radius=5.0, direction=-1.0)
>>>
>>> # now create an un-penetrable shape-based constraint of type 0
>>> spherical_constraint = system.constraints.add(particle_type=0, penetrable=False, shape=spherical_cavity)
>>>
>>> # place a trapped particle inside this sphere
>>> system.part.add(id=0, pos=[5, 5, 5], type=1)
"""
_so_name = "Constraints::ShapeBasedConstraint"
def min_dist(self):
"""
Calculates the minimum distance to all interacting particles.
Returns
----------
:obj:`float` :
The minimum distance
"""
return self.call_method("min_dist", object=self)
def total_force(self):
"""
Get total force acting on this constraint.
Examples
----------
>>> import espressomd
>>> from espressomd import shapes
>>> system = espressomd.System()
>>>
>>> system.time_step = 0.01
>>> system.box_l = [50, 50, 50]
>>> system.thermostat.set_langevin(kT=0.0, gamma=1.0)
>>> system.cell_system.set_n_square(use_verlet_lists=False)
>>> system.non_bonded_inter[0, 0].lennard_jones.set_params(
... epsilon=1, sigma=1,
... cutoff=2**(1. / 6), shift="auto")
>>>
>>> floor = system.constraints.add(shape=shapes.Wall(normal=[0, 0, 1], dist=0.0),
... particle_type=0, penetrable=False, only_positive=False)
>>>
>>> system.part.add(id=0, pos=[0,0,1.5], type=0, ext_force=[0, 0, -.1])
>>> # print the particle position as it falls
>>> # and print the force it applies on the floor
>>> for t in range(10):
... system.integrator.run(100)
... print(system.part[0].pos, floor.total_force())
"""
return self.call_method("total_force", constraint=self)
def total_normal_force(self):
"""
Get the total summed normal force acting on this constraint.
"""
return self.call_method("total_normal_force", constraint=self)
@script_interface_register
class HomogeneousMagneticField(Constraint):
"""
Attributes
----------
H : (3,) array_like of :obj:`float`
Magnetic field vector. Describes both field direction and
strength of the magnetic field (via length of the vector).
"""
_so_name = "Constraints::HomogeneousMagneticField"
class _Interpolated(Constraint):
"""
Tabulated field data.
The actual field value is calculated by linear
interpolation (force fields) or gradient linear
interpolation.
The data has to have one point of halo in each direction,
and is shifted by half a grid spacing in the +xyz direction,
so that the element (0,0,0) has coordinates -0.5 * grid_spacing.
The number of points has to be such that the data spans the whole
box, e.g. the most up right back point has to be at least at
box + 0.5 * grid_spacing. There are convenience functions on this
class that can calculate the required grid dimensions and the coordinates.
Arguments
----------
field : (M, N, O, P) array_like of :obj:`float`
The actual field on a grid of size (M, N, O) with dimension P.
grid_spacing : (3,) array_like of :obj:`float`
Spacing of the grid points.
Attributes
----------
field : (M, N, O, P) array_like of :obj:`float`
The actual field on a grid of size (M, N, O) with dimension P.
Please be aware that depending on the interpolation
order additional points are used on the boundaries.
grid_spacing : array_like of :obj:`float`
Spacing of the grid points.
origin : (3,) array_like of :obj:`float`
Coordinates of the grid origin.
"""
def __init__(self, **kwargs):
if "sip" not in kwargs:
field = kwargs.pop("field")
shape, codim = self._unpack_dims(field)
super().__init__(_field_shape=shape, _field_codim=codim,
_field_data=field.flatten(), **kwargs)
else:
super().__init__(**kwargs)
@classmethod
def required_dims(cls, box_size, grid_spacing):
"""
Calculate the grid size and origin needed for specified box size and
grid spacing. Returns the shape and origin (coordinates of [0][0][0])
needed.
Arguments
---------
box_size : (3,) array_like of obj:`float`
The box the field should be used.
grid_spacing : array_like obj:`float`
The desired grid spacing.
"""
shape = np.array(np.ceil(box_size / grid_spacing), dtype=int) + 2
origin = -0.5 * grid_spacing
return shape, origin
@classmethod
def field_from_fn(cls, box_size, grid_spacing, f, codim=None):
"""Generate field data for a desired box size and grid spacing
by evaluating a function at the coordinates.
Arguments
---------
box_size : (3,) array_like of obj:`float`
The box the field should be used.
grid_spacing : array_like obj:`float`
The desired grid spacing.
f : callable
A function that is called with the coordinates of every
grid point to populate the grid.
"""
shape, origin = cls.required_dims(box_size, grid_spacing)
if not codim:
codim = cls._codim
field = np.zeros((shape[0], shape[1], shape[2], codim))
for i in product(*map(range, shape)):
x = origin + np.array(i) * grid_spacing
field[i] = f(x)
return field
@classmethod
def field_coordinates(cls, box_size, grid_spacing):
"""Returns an array of the coordinates of the grid points required.
Arguments
---------
box_size : (3,) array_like of obj:`float`
The box the field should be used.
grid_spacing : array_like obj:`float`
The desired grid spacing.
"""
return cls.field_from_fn(box_size, grid_spacing, lambda x: x, 3)
def _unpack_dims(self, a):
s = a.shape
shape = s[:3]
codim = s[3]
return (shape, codim)
@property
def field(self):
shape = self._field_shape
return np.reshape(self._field_data,
(shape[0], shape[1], shape[2], self._field_codim))
@script_interface_register
class ForceField(_Interpolated):
"""
A generic tabulated force field that applies a per-particle scaling factor.
Arguments
----------
field : (M, N, O, 3) array_like of :obj:`float`
Forcefield amplitude on a grid of size (M, N, O).
grid_spacing : (3,) array_like of :obj:`float`
Spacing of the grid points.
default_scale : :obj:`float`
Scaling factor for particles that have no individual scaling factor.
particle_scales : array_like of (:obj:`int`, :obj:`float`)
A list of tuples of ids and scaling factors. For
particles in the list the interaction is scaled with
their individual scaling factor before it is applied.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
_codim = 3
_so_name = "Constraints::ForceField"
@script_interface_register
class PotentialField(_Interpolated):
"""
A generic tabulated force field that applies a per-particle
scaling factor. The forces are calculated numerically from
the data by finite differences. The potential is interpolated
from the provided data.
Arguments
----------
field : (M, N, O, 1) array_like of :obj:`float`
Potential on a grid of size (M, N, O).
grid_spacing : (3,) array_like of :obj:`float`
Spacing of the grid points.
default_scale : :obj:`float`
Scaling factor for particles that have no individual scaling factor.
particle_scales : array_like (:obj:`int`, :obj:`float`)
A list of tuples of ids and scaling factors. For
particles in the list the interaction is scaled with
their individual scaling factor before it is applied.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
_codim = 1
_so_name = "Constraints::PotentialField"
@script_interface_register
class Gravity(Constraint):
"""
Gravity force
:math:`F = m \\cdot g`
Arguments
----------
g : (3,) array_like of :obj:`float`
The gravitational acceleration.
"""
def __init__(self, **kwargs):
if "sip" not in kwargs:
kwargs["value"] = kwargs.pop("g")
super().__init__(**kwargs)
@property
def g(self):
return self.value
_so_name = "Constraints::Gravity"
@script_interface_register
class LinearElectricPotential(Constraint):
"""
Electric potential of the form
:math:`\\phi = -E \\cdot x + \\phi_0`,
resulting in the electric field E
everywhere. (E.g. in a plate capacitor).
The resulting force on the particles are then
:math:`F = q \\cdot E`
where :math:`q` is the charge of the particle.
Arguments
----------
E : array_like of :obj:`float`
The electric field.
phi0 : :obj:`float`
The potential at the origin
"""
def __init__(self, phi0=0, **kwargs):
if "sip" not in kwargs:
kwargs["A"] = -np.array(kwargs.pop("E"))
kwargs["b"] = phi0
super().__init__(**kwargs)
@property
def E(self):
return -np.array(self.A)
@property
def phi0(self):
return np.array(self.b)
_so_name = "Constraints::LinearElectricPotential"
@script_interface_register
class ElectricPlaneWave(Constraint):
"""
Electric field of the form
:math:`E = E0 \\cdot \\sin(k \\cdot x + \\omega \\cdot t + \\phi)`
The resulting force on the particles are then
:math:`F = q \\cdot E`
where :math:`q` is the charge of the particle.
This can be used to generate a homogeneous AC
field by setting k to zero.
Arguments
----------
E0 : array_like of :obj:`float`
Amplitude of the electric field.
k : array_like of :obj:`float`
Wave vector of the wave
omega : :obj:`float`
Frequency of the wave
phi : :obj:`float`, optional
Phase shift
"""
_so_name = "Constraints::ElectricPlaneWave"
def __init__(self, phi=0, **kwargs):
if "sip" not in kwargs:
kwargs["amplitude"] = kwargs.pop("E0")
kwargs["wave_vector"] = kwargs.pop("k")
kwargs["frequency"] = kwargs.pop("omega")
kwargs["phase"] = phi
super().__init__(**kwargs)
@property
def E0(self):
return np.array(self.amplitude)
@property
def k(self):
return np.array(self.wave_vector)
@property
def omega(self):
return self.frequency
@property
def phi(self):
return self.phase
@script_interface_register
class FlowField(_Interpolated):
"""
Viscous coupling to a flow field that is
interpolated from tabulated data like
:math:`F = -\\gamma \\cdot \\left( u(r) - v \\right)`
where :math:`v` is the velocity of the particle.
Arguments
----------
field : (M, N, O, 3) array_like of :obj:`float`
Field velocity on a grid of size (M, N, O)
grid_spacing : (3,) array_like of :obj:`float`
Spacing of the grid points.
gamma : :obj:`float`
Coupling constant
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
_codim = 3
_so_name = "Constraints::FlowField"
@script_interface_register
class HomogeneousFlowField(Constraint):
"""
Viscous coupling to a flow field that is
constant in space with the force
:math:`F = -\\gamma \\cdot (u - v)`
where :math:`v` is the velocity of the particle.
Attributes
----------
gamma : :obj:`float`
Coupling constant
"""
def __init__(self, **kwargs):
if "sip" not in kwargs:
kwargs["value"] = kwargs.pop("u")
super().__init__(**kwargs)
@property
def u(self):
"""
Field velocity ((3,) array_like of :obj:`float`).
"""
return self.value
_so_name = "Constraints::HomogeneousFlowField"
@script_interface_register
class ElectricPotential(_Interpolated):
"""
Electric potential interpolated from
provided data. The electric field E is
calculated numerically from the potential,
and the resulting force on the particles are
:math:`F = q \\cdot E`
where :math:`q` is the charge of the particle.
Arguments
----------
field : (M, N, O, 1) array_like of :obj:`float`
Potential on a grid of size (M, N, O)
grid_spacing : (3,) array_like of :obj:`float`
Spacing of the grid points.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
_codim = 1
_so_name = "Constraints::ElectricPotential"
|
KaiSzuttor/espresso
|
src/python/espressomd/constraints.py
|
Python
|
gpl-3.0
| 16,737
|
[
"ESPResSo"
] |
2b8b0229d1b84636c28f782f53b68ce8a302f9b53a71e53520c38632211288ec
|
# Copyright 2007-2010 by Peter Cock. All rights reserved.
# Revisions copyright 2010 by Uri Laserson. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
# This code is NOT intended for direct use. It provides a basic scanner
# (for use with a event consumer such as Bio.GenBank._FeatureConsumer)
# to parse a GenBank or EMBL file (with their shared INSDC feature table).
#
# It is used by Bio.GenBank to parse GenBank files
# It is also used by Bio.SeqIO to parse GenBank and EMBL files
#
# Feature Table Documentation:
# http://www.insdc.org/files/feature_table.html
# http://www.ncbi.nlm.nih.gov/projects/collab/FT/index.html
# ftp://ftp.ncbi.nih.gov/genbank/docs/
#
# 17-MAR-2009: added wgs, wgs_scafld for GenBank whole genome shotgun master records.
# These are GenBank files that summarize the content of a project, and provide lists of
# scaffold and contig files in the project. These will be in annotations['wgs'] and
# annotations['wgs_scafld']. These GenBank files do not have sequences. See
# http://groups.google.com/group/bionet.molbio.genbank/browse_thread/thread/51fb88bf39e7dc36
# http://is.gd/nNgk
# for more details of this format, and an example.
# Added by Ying Huang & Iddo Friedberg
import warnings
import os
import re
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_alphabet, generic_protein
class InsdcScanner:
"""Basic functions for breaking up a GenBank/EMBL file into sub sections.
The International Nucleotide Sequence Database Collaboration (INSDC)
between the DDBJ, EMBL, and GenBank. These organisations all use the
same "Feature Table" layout in their plain text flat file formats.
However, the header and sequence sections of an EMBL file are very
different in layout to those produced by GenBank/DDBJ."""
#These constants get redefined with sensible values in the sub classes:
RECORD_START = "XXX" # "LOCUS " or "ID "
HEADER_WIDTH = 3 # 12 or 5
FEATURE_START_MARKERS = ["XXX***FEATURES***XXX"]
FEATURE_END_MARKERS = ["XXX***END FEATURES***XXX"]
FEATURE_QUALIFIER_INDENT = 0
FEATURE_QUALIFIER_SPACER = ""
SEQUENCE_HEADERS=["XXX"] #with right hand side spaces removed
def __init__(self, debug=0):
assert len(self.RECORD_START)==self.HEADER_WIDTH
for marker in self.SEQUENCE_HEADERS:
assert marker==marker.rstrip()
assert len(self.FEATURE_QUALIFIER_SPACER)==self.FEATURE_QUALIFIER_INDENT
self.debug = debug
self.line = None
def set_handle(self, handle):
self.handle = handle
self.line = ""
def find_start(self):
"""Read in lines until find the ID/LOCUS line, which is returned.
Any preamble (such as the header used by the NCBI on *.seq.gz archives)
will we ignored."""
while True:
if self.line:
line = self.line
self.line = ""
else:
line = self.handle.readline()
if not line:
if self.debug : print "End of file"
return None
if line[:self.HEADER_WIDTH]==self.RECORD_START:
if self.debug > 1: print "Found the start of a record:\n" + line
break
line = line.rstrip()
if line == "//":
if self.debug > 1: print "Skipping // marking end of last record"
elif line == "":
if self.debug > 1: print "Skipping blank line before record"
else:
#Ignore any header before the first ID/LOCUS line.
if self.debug > 1:
print "Skipping header line before record:\n" + line
self.line = line
return line
def parse_header(self):
"""Return list of strings making up the header
New line characters are removed.
Assumes you have just read in the ID/LOCUS line.
"""
assert self.line[:self.HEADER_WIDTH]==self.RECORD_START, \
"Not at start of record"
header_lines = []
while True:
line = self.handle.readline()
if not line:
raise ValueError("Premature end of line during sequence data")
line = line.rstrip()
if line in self.FEATURE_START_MARKERS:
if self.debug : print "Found header table"
break
#if line[:self.HEADER_WIDTH]==self.FEATURE_START_MARKER[:self.HEADER_WIDTH]:
# if self.debug : print "Found header table (?)"
# break
if line[:self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS:
if self.debug : print "Found start of sequence"
break
if line == "//":
raise ValueError("Premature end of sequence data marker '//' found")
header_lines.append(line)
self.line = line
return header_lines
def parse_features(self, skip=False):
"""Return list of tuples for the features (if present)
Each feature is returned as a tuple (key, location, qualifiers)
where key and location are strings (e.g. "CDS" and
"complement(join(490883..490885,1..879))") while qualifiers
is a list of two string tuples (feature qualifier keys and values).
Assumes you have already read to the start of the features table.
"""
if self.line.rstrip() not in self.FEATURE_START_MARKERS:
if self.debug : print "Didn't find any feature table"
return []
while self.line.rstrip() in self.FEATURE_START_MARKERS:
self.line = self.handle.readline()
features = []
line = self.line
while True:
if not line:
raise ValueError("Premature end of line during features table")
if line[:self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS:
if self.debug : print "Found start of sequence"
break
line = line.rstrip()
if line == "//":
raise ValueError("Premature end of features table, marker '//' found")
if line in self.FEATURE_END_MARKERS:
if self.debug : print "Found end of features"
line = self.handle.readline()
break
if line[2:self.FEATURE_QUALIFIER_INDENT].strip() == "":
#This is an empty feature line between qualifiers. Empty
#feature lines within qualifiers are handled below (ignored).
line = self.handle.readline()
continue
if skip:
line = self.handle.readline()
while line[:self.FEATURE_QUALIFIER_INDENT] == self.FEATURE_QUALIFIER_SPACER:
line = self.handle.readline()
else:
#Build up a list of the lines making up this feature:
if line[self.FEATURE_QUALIFIER_INDENT]!=" " \
and " " in line[self.FEATURE_QUALIFIER_INDENT:]:
#The feature table design enforces a length limit on the feature keys.
#Some third party files (e.g. IGMT's EMBL like files) solve this by
#over indenting the location and qualifiers.
feature_key, line = line[2:].strip().split(None,1)
feature_lines = [line]
warnings.warn("Overindented %s feature?" % feature_key)
else:
feature_key = line[2:self.FEATURE_QUALIFIER_INDENT].strip()
feature_lines = [line[self.FEATURE_QUALIFIER_INDENT:]]
line = self.handle.readline()
while line[:self.FEATURE_QUALIFIER_INDENT] == self.FEATURE_QUALIFIER_SPACER \
or line.rstrip() == "" : # cope with blank lines in the midst of a feature
#Use strip to remove any harmless trailing white space AND and leading
#white space (e.g. out of spec files with too much intentation)
feature_lines.append(line[self.FEATURE_QUALIFIER_INDENT:].strip())
line = self.handle.readline()
features.append(self.parse_feature(feature_key, feature_lines))
self.line = line
return features
def parse_feature(self, feature_key, lines):
"""Expects a feature as a list of strings, returns a tuple (key, location, qualifiers)
For example given this GenBank feature:
CDS complement(join(490883..490885,1..879))
/locus_tag="NEQ001"
/note="conserved hypothetical [Methanococcus jannaschii];
COG1583:Uncharacterized ACR; IPR001472:Bipartite nuclear
localization signal; IPR002743: Protein of unknown
function DUF57"
/codon_start=1
/transl_table=11
/product="hypothetical protein"
/protein_id="NP_963295.1"
/db_xref="GI:41614797"
/db_xref="GeneID:2732620"
/translation="MRLLLELKALNSIDKKQLSNYLIQGFIYNILKNTEYSWLHNWKK
EKYFNFTLIPKKDIIENKRYYLIISSPDKRFIEVLHNKIKDLDIITIGLAQFQLRKTK
KFDPKLRFPWVTITPIVLREGKIVILKGDKYYKVFVKRLEELKKYNLIKKKEPILEEP
IEISLNQIKDGWKIIDVKDRYYDFRNKSFSAFSNWLRDLKEQSLRKYNNFCGKNFYFE
EAIFEGFTFYKTVSIRIRINRGEAVYIGTLWKELNVYRKLDKEEREFYKFLYDCGLGS
LNSMGFGFVNTKKNSAR"
Then should give input key="CDS" and the rest of the data as a list of strings
lines=["complement(join(490883..490885,1..879))", ..., "LNSMGFGFVNTKKNSAR"]
where the leading spaces and trailing newlines have been removed.
Returns tuple containing: (key as string, location string, qualifiers as list)
as follows for this example:
key = "CDS", string
location = "complement(join(490883..490885,1..879))", string
qualifiers = list of string tuples:
[('locus_tag', '"NEQ001"'),
('note', '"conserved hypothetical [Methanococcus jannaschii];\nCOG1583:..."'),
('codon_start', '1'),
('transl_table', '11'),
('product', '"hypothetical protein"'),
('protein_id', '"NP_963295.1"'),
('db_xref', '"GI:41614797"'),
('db_xref', '"GeneID:2732620"'),
('translation', '"MRLLLELKALNSIDKKQLSNYLIQGFIYNILKNTEYSWLHNWKK\nEKYFNFT..."')]
In the above example, the "note" and "translation" were edited for compactness,
and they would contain multiple new line characters (displayed above as \n)
If a qualifier is quoted (in this case, everything except codon_start and
transl_table) then the quotes are NOT removed.
Note that no whitespace is removed.
"""
#Skip any blank lines
iterator = iter(filter(None, lines))
try:
line = iterator.next()
feature_location = line.strip()
while feature_location[-1:]==",":
#Multiline location, still more to come!
line = iterator.next()
feature_location += line.strip()
qualifiers=[]
for line in iterator:
if line[0]=="/":
#New qualifier
i = line.find("=")
key = line[1:i] #does not work if i==-1
value = line[i+1:] #we ignore 'value' if i==-1
if i==-1:
#Qualifier with no key, e.g. /pseudo
key = line[1:]
qualifiers.append((key,None))
elif value[0]=='"':
#Quoted...
if value[-1]!='"' or value!='"':
#No closing quote on the first line...
while value[-1] != '"':
value += "\n" + iterator.next()
else:
#One single line (quoted)
assert value == '"'
if self.debug : print "Quoted line %s:%s" % (key, value)
#DO NOT remove the quotes...
qualifiers.append((key,value))
else:
#Unquoted
#if debug : print "Unquoted line %s:%s" % (key,value)
qualifiers.append((key,value))
else:
#Unquoted continuation
assert len(qualifiers) > 0
assert key==qualifiers[-1][0]
#if debug : print "Unquoted Cont %s:%s" % (key, line)
qualifiers[-1] = (key, qualifiers[-1][1] + "\n" + line)
return (feature_key, feature_location, qualifiers)
except StopIteration:
#Bummer
raise ValueError("Problem with '%s' feature:\n%s" \
% (feature_key, "\n".join(lines)))
def parse_footer(self):
"""returns a tuple containing a list of any misc strings, and the sequence"""
#This is a basic bit of code to scan and discard the sequence,
#which was useful when developing the sub classes.
if self.line in self.FEATURE_END_MARKERS:
while self.line[:self.HEADER_WIDTH].rstrip() not in self.SEQUENCE_HEADERS:
self.line = self.handle.readline()
if not self.line:
raise ValueError("Premature end of file")
self.line = self.line.rstrip()
assert self.line[:self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS, \
"Not at start of sequence"
while True:
line = self.handle.readline()
if not line : raise ValueError("Premature end of line during sequence data")
line = line.rstrip()
if line == "//" : break
self.line = line
return ([],"") #Dummy values!
def _feed_first_line(self, consumer, line):
"""Handle the LOCUS/ID line, passing data to the comsumer
This should be implemented by the EMBL / GenBank specific subclass
Used by the parse_records() and parse() methods.
"""
pass
def _feed_header_lines(self, consumer, lines):
"""Handle the header lines (list of strings), passing data to the comsumer
This should be implemented by the EMBL / GenBank specific subclass
Used by the parse_records() and parse() methods.
"""
pass
def _feed_feature_table(self, consumer, feature_tuples):
"""Handle the feature table (list of tuples), passing data to the comsumer
Used by the parse_records() and parse() methods.
"""
consumer.start_feature_table()
for feature_key, location_string, qualifiers in feature_tuples:
consumer.feature_key(feature_key)
consumer.location(location_string)
for q_key, q_value in qualifiers:
consumer.feature_qualifier_name([q_key])
if q_value is not None:
consumer.feature_qualifier_description(q_value.replace("\n"," "))
def _feed_misc_lines(self, consumer, lines):
"""Handle any lines between features and sequence (list of strings), passing data to the consumer
This should be implemented by the EMBL / GenBank specific subclass
Used by the parse_records() and parse() methods.
"""
pass
def feed(self, handle, consumer, do_features=True):
"""Feed a set of data into the consumer.
This method is intended for use with the "old" code in Bio.GenBank
Arguments:
handle - A handle with the information to parse.
consumer - The consumer that should be informed of events.
do_features - Boolean, should the features be parsed?
Skipping the features can be much faster.
Return values:
true - Passed a record
false - Did not find a record
"""
#Should work with both EMBL and GenBank files provided the
#equivalent Bio.GenBank._FeatureConsumer methods are called...
self.set_handle(handle)
if not self.find_start():
#Could not find (another) record
consumer.data=None
return False
#We use the above class methods to parse the file into a simplified format.
#The first line, header lines and any misc lines after the features will be
#dealt with by GenBank / EMBL specific derived classes.
#First line and header:
self._feed_first_line(consumer, self.line)
self._feed_header_lines(consumer, self.parse_header())
#Features (common to both EMBL and GenBank):
if do_features:
self._feed_feature_table(consumer, self.parse_features(skip=False))
else:
self.parse_features(skip=True) # ignore the data
#Footer and sequence
misc_lines, sequence_string = self.parse_footer()
self._feed_misc_lines(consumer, misc_lines)
consumer.sequence(sequence_string)
#Calls to consumer.base_number() do nothing anyway
consumer.record_end("//")
assert self.line == "//"
#And we are done
return True
def parse(self, handle, do_features=True):
"""Returns a SeqRecord (with SeqFeatures if do_features=True)
See also the method parse_records() for use on multi-record files.
"""
from Bio.GenBank import _FeatureConsumer
from Bio.GenBank.utils import FeatureValueCleaner
consumer = _FeatureConsumer(use_fuzziness = 1,
feature_cleaner = FeatureValueCleaner())
if self.feed(handle, consumer, do_features):
return consumer.data
else:
return None
def parse_records(self, handle, do_features=True):
"""Returns a SeqRecord object iterator
Each record (from the ID/LOCUS line to the // line) becomes a SeqRecord
The SeqRecord objects include SeqFeatures if do_features=True
This method is intended for use in Bio.SeqIO
"""
#This is a generator function
while True:
record = self.parse(handle, do_features)
if record is None : break
assert record.id is not None
assert record.name != "<unknown name>"
assert record.description != "<unknown description>"
yield record
def parse_cds_features(self, handle,
alphabet=generic_protein,
tags2id=('protein_id','locus_tag','product')):
"""Returns SeqRecord object iterator
Each CDS feature becomes a SeqRecord.
alphabet - Used for any sequence found in a translation field.
tags2id - Tupple of three strings, the feature keys to use
for the record id, name and description,
This method is intended for use in Bio.SeqIO
"""
self.set_handle(handle)
while self.find_start():
#Got an EMBL or GenBank record...
self.parse_header() # ignore header lines!
feature_tuples = self.parse_features()
#self.parse_footer() # ignore footer lines!
while True:
line = self.handle.readline()
if not line : break
if line[:2]=="//" : break
self.line = line.rstrip()
#Now go though those features...
for key, location_string, qualifiers in feature_tuples:
if key=="CDS":
#Create SeqRecord
#================
#SeqRecord objects cannot be created with annotations, they
#must be added afterwards. So create an empty record and
#then populate it:
record = SeqRecord(seq=None)
annotations = record.annotations
#Should we add a location object to the annotations?
#I *think* that only makes sense for SeqFeatures with their
#sub features...
annotations['raw_location'] = location_string.replace(' ','')
for (qualifier_name, qualifier_data) in qualifiers:
if qualifier_data is not None \
and qualifier_data[0]=='"' and qualifier_data[-1]=='"':
#Remove quotes
qualifier_data = qualifier_data[1:-1]
#Append the data to the annotation qualifier...
if qualifier_name == "translation":
assert record.seq is None, "Multiple translations!"
record.seq = Seq(qualifier_data.replace("\n",""), alphabet)
elif qualifier_name == "db_xref":
#its a list, possibly empty. Its safe to extend
record.dbxrefs.append(qualifier_data)
else:
if qualifier_data is not None:
qualifier_data = qualifier_data.replace("\n"," ").replace(" "," ")
try:
annotations[qualifier_name] += " " + qualifier_data
except KeyError:
#Not an addition to existing data, its the first bit
annotations[qualifier_name]= qualifier_data
#Fill in the ID, Name, Description
#=================================
try:
record.id = annotations[tags2id[0]]
except KeyError:
pass
try:
record.name = annotations[tags2id[1]]
except KeyError:
pass
try:
record.description = annotations[tags2id[2]]
except KeyError:
pass
yield record
class EmblScanner(InsdcScanner):
"""For extracting chunks of information in EMBL files"""
RECORD_START = "ID "
HEADER_WIDTH = 5
FEATURE_START_MARKERS = ["FH Key Location/Qualifiers","FH"]
FEATURE_END_MARKERS = ["XX"] #XX can also mark the end of many things!
FEATURE_QUALIFIER_INDENT = 21
FEATURE_QUALIFIER_SPACER = "FT" + " " * (FEATURE_QUALIFIER_INDENT-2)
SEQUENCE_HEADERS=["SQ", "CO"] #Remove trailing spaces
def parse_footer(self):
"""returns a tuple containing a list of any misc strings, and the sequence"""
assert self.line[:self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS, \
"Eh? '%s'" % self.line
#Note that the SQ line can be split into several lines...
misc_lines = []
while self.line[:self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS:
misc_lines.append(self.line)
self.line = self.handle.readline()
if not self.line:
raise ValueError("Premature end of file")
self.line = self.line.rstrip()
assert self.line[:self.HEADER_WIDTH] == " " * self.HEADER_WIDTH \
or self.line.strip() == '//', repr(self.line)
seq_lines = []
line = self.line
while True:
if not line:
raise ValueError("Premature end of file in sequence data")
line = line.strip()
if not line:
raise ValueError("Blank line in sequence data")
if line=='//':
break
assert self.line[:self.HEADER_WIDTH] == " " * self.HEADER_WIDTH, \
repr(self.line)
#Remove tailing number now, remove spaces later
seq_lines.append(line.rsplit(None,1)[0])
line = self.handle.readline()
self.line = line
return (misc_lines, "".join(seq_lines).replace(" ", ""))
def _feed_first_line(self, consumer, line):
assert line[:self.HEADER_WIDTH].rstrip() == "ID"
if line[self.HEADER_WIDTH:].count(";") == 6:
#Looks like the semi colon separated style introduced in 2006
self._feed_first_line_new(consumer, line)
elif line[self.HEADER_WIDTH:].count(";") == 3:
#Looks like the pre 2006 style
self._feed_first_line_old(consumer, line)
else:
raise ValueError('Did not recognise the ID line layout:\n' + line)
def _feed_first_line_old(self, consumer, line):
#Expects an ID line in the style before 2006, e.g.
#ID SC10H5 standard; DNA; PRO; 4870 BP.
#ID BSUB9999 standard; circular DNA; PRO; 4214630 BP.
assert line[:self.HEADER_WIDTH].rstrip() == "ID"
fields = [line[self.HEADER_WIDTH:].split(None,1)[0]]
fields.extend(line[self.HEADER_WIDTH:].split(None,1)[1].split(";"))
fields = [entry.strip() for entry in fields]
"""
The tokens represent:
0. Primary accession number
(space sep)
1. ??? (e.g. standard)
(semi-colon)
2. Topology and/or Molecule type (e.g. 'circular DNA' or 'DNA')
3. Taxonomic division (e.g. 'PRO')
4. Sequence length (e.g. '4639675 BP.')
"""
consumer.locus(fields[0]) #Should we also call the accession consumer?
consumer.residue_type(fields[2])
consumer.data_file_division(fields[3])
self._feed_seq_length(consumer, fields[4])
def _feed_first_line_new(self, consumer, line):
#Expects an ID line in the style introduced in 2006, e.g.
#ID X56734; SV 1; linear; mRNA; STD; PLN; 1859 BP.
#ID CD789012; SV 4; linear; genomic DNA; HTG; MAM; 500 BP.
assert line[:self.HEADER_WIDTH].rstrip() == "ID"
fields = [data.strip() for data in line[self.HEADER_WIDTH:].strip().split(";")]
assert len(fields) == 7
"""
The tokens represent:
0. Primary accession number
1. Sequence version number
2. Topology: 'circular' or 'linear'
3. Molecule type (e.g. 'genomic DNA')
4. Data class (e.g. 'STD')
5. Taxonomic division (e.g. 'PRO')
6. Sequence length (e.g. '4639675 BP.')
"""
consumer.locus(fields[0])
#Call the accession consumer now, to make sure we record
#something as the record.id, in case there is no AC line
consumer.accession(fields[0])
#TODO - How to deal with the version field? At the moment the consumer
#will try and use this for the ID which isn't ideal for EMBL files.
version_parts = fields[1].split()
if len(version_parts)==2 \
and version_parts[0]=="SV" \
and version_parts[1].isdigit():
consumer.version_suffix(version_parts[1])
#Based on how the old GenBank parser worked, merge these two:
consumer.residue_type(" ".join(fields[2:4])) #TODO - Store as two fields?
#consumer.xxx(fields[4]) #TODO - What should we do with the data class?
consumer.data_file_division(fields[5])
self._feed_seq_length(consumer, fields[6])
def _feed_seq_length(self, consumer, text):
length_parts = text.split()
assert len(length_parts) == 2
assert length_parts[1].upper() in ["BP", "BP.", "AA."]
consumer.size(length_parts[0])
def _feed_header_lines(self, consumer, lines):
EMBL_INDENT = self.HEADER_WIDTH
EMBL_SPACER = " " * EMBL_INDENT
consumer_dict = {
'AC' : 'accession',
'SV' : 'version', # SV line removed in June 2006, now part of ID line
'DE' : 'definition',
#'RN' : 'reference_num',
#'RC' : reference comment... TODO
#'RP' : 'reference_bases',
#'RX' : reference cross reference... DOI or Pubmed
'RG' : 'consrtm', #optional consortium
#'RA' : 'authors',
#'RT' : 'title',
'RL' : 'journal',
'OS' : 'organism',
'OC' : 'taxonomy',
#'DR' : data reference
'CC' : 'comment',
#'XX' : splitter
}
#We have to handle the following specially:
#RX (depending on reference type...)
for line in lines:
line_type = line[:EMBL_INDENT].strip()
data = line[EMBL_INDENT:].strip()
if line_type == 'XX':
pass
elif line_type == 'RN':
# Reformat reference numbers for the GenBank based consumer
# e.g. '[1]' becomes '1'
if data[0] == "[" and data[-1] == "]" : data = data[1:-1]
consumer.reference_num(data)
elif line_type == 'RP':
# Reformat reference numbers for the GenBank based consumer
# e.g. '1-4639675' becomes '(bases 1 to 4639675)'
# and '160-550, 904-1055' becomes '(bases 160 to 550; 904 to 1055)'
parts = [bases.replace("-"," to ").strip() for bases in data.split(",")]
consumer.reference_bases("(bases %s)" % "; ".join(parts))
elif line_type == 'RT':
#Remove the enclosing quotes and trailing semi colon.
#Note the title can be split over multiple lines.
if data.startswith('"'):
data = data[1:]
if data.endswith('";'):
data = data[:-2]
consumer.title(data)
elif line_type == 'RX':
# EMBL support three reference types at the moment:
# - PUBMED PUBMED bibliographic database (NLM)
# - DOI Digital Object Identifier (International DOI Foundation)
# - AGRICOLA US National Agriculture Library (NAL) of the US Department
# of Agriculture (USDA)
#
# Format:
# RX resource_identifier; identifier.
#
# e.g.
# RX DOI; 10.1016/0024-3205(83)90010-3.
# RX PUBMED; 264242.
#
# Currently our reference object only supports PUBMED and MEDLINE
# (as these were in GenBank files?).
key, value = data.split(";",1)
if value.endswith(".") : value = value[:-1]
value = value.strip()
if key == "PUBMED":
consumer.pubmed_id(value)
#TODO - Handle other reference types (here and in BioSQL bindings)
elif line_type == 'CC':
# Have to pass a list of strings for this one (not just a string)
consumer.comment([data])
elif line_type == 'DR':
# Database Cross-reference, format:
# DR database_identifier; primary_identifier; secondary_identifier.
#
# e.g.
# DR MGI; 98599; Tcrb-V4.
#
# TODO - How should we store any secondary identifier?
parts = data.rstrip(".").split(";")
#Turn it into "database_identifier:primary_identifier" to
#mimic the GenBank parser. e.g. "MGI:98599"
consumer.dblink("%s:%s" % (parts[0].strip(),
parts[1].strip()))
elif line_type == 'RA':
# Remove trailing ; at end of authors list
consumer.authors(data.rstrip(";"))
elif line_type == 'PR':
# Remove trailing ; at end of the project reference
# In GenBank files this corresponds to the old PROJECT
# line which is being replaced with the DBLINK line.
consumer.project(data.rstrip(";"))
elif line_type in consumer_dict:
#Its a semi-automatic entry!
getattr(consumer, consumer_dict[line_type])(data)
else:
if self.debug:
print "Ignoring EMBL header line:\n%s" % line
def _feed_misc_lines(self, consumer, lines):
#TODO - Should we do something with the information on the SQ line(s)?
lines.append("")
line_iter = iter(lines)
try:
for line in line_iter:
if line.startswith("CO "):
line = line[5:].strip()
contig_location = line
while True:
line = line_iter.next()
if not line:
break
elif line.startswith("CO "):
#Don't need to preseve the whitespace here.
contig_location += line[5:].strip()
else:
raise ValueError('Expected CO (contig) continuation line, got:\n' + line)
consumer.contig_location(contig_location)
return
except StopIteration:
raise ValueError("Problem in misc lines before sequence")
class _ImgtScanner(EmblScanner):
"""For extracting chunks of information in IMGT (EMBL like) files (PRIVATE).
IMGT files are like EMBL files but in order to allow longer feature types
the features should be indented by 25 characters not 21 characters. In
practice the IMGT flat files tend to use either 21 or 25 characters, so we
must cope with both.
This is private to encourage use of Bio.SeqIO rather than Bio.GenBank.
"""
FEATURE_START_MARKERS = ["FH Key Location/Qualifiers",
"FH Key Location/Qualifiers (from EMBL)",
"FH Key Location/Qualifiers",
"FH"]
def parse_features(self, skip=False):
"""Return list of tuples for the features (if present)
Each feature is returned as a tuple (key, location, qualifiers)
where key and location are strings (e.g. "CDS" and
"complement(join(490883..490885,1..879))") while qualifiers
is a list of two string tuples (feature qualifier keys and values).
Assumes you have already read to the start of the features table.
"""
if self.line.rstrip() not in self.FEATURE_START_MARKERS:
if self.debug : print "Didn't find any feature table"
return []
while self.line.rstrip() in self.FEATURE_START_MARKERS:
self.line = self.handle.readline()
bad_position_re = re.compile(r'([0-9]+)>{1}')
features = []
line = self.line
while True:
if not line:
raise ValueError("Premature end of line during features table")
if line[:self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS:
if self.debug : print "Found start of sequence"
break
line = line.rstrip()
if line == "//":
raise ValueError("Premature end of features table, marker '//' found")
if line in self.FEATURE_END_MARKERS:
if self.debug : print "Found end of features"
line = self.handle.readline()
break
if line[2:self.FEATURE_QUALIFIER_INDENT].strip() == "":
#This is an empty feature line between qualifiers. Empty
#feature lines within qualifiers are handled below (ignored).
line = self.handle.readline()
continue
if skip:
line = self.handle.readline()
while line[:self.FEATURE_QUALIFIER_INDENT] == self.FEATURE_QUALIFIER_SPACER:
line = self.handle.readline()
else:
assert line[:2] == "FT"
try:
feature_key, location_start = line[2:].strip().split()
except ValueError:
#e.g. "FT TRANSMEMBRANE-REGION2163..2240\n"
#Assume indent of 25 as per IMGT spec, with the location
#start in column 26 (one-based).
feature_key = line[2:25].strip()
location_start = line[25:].strip()
feature_lines = [location_start]
line = self.handle.readline()
while line[:self.FEATURE_QUALIFIER_INDENT] == self.FEATURE_QUALIFIER_SPACER \
or line.rstrip() == "" : # cope with blank lines in the midst of a feature
#Use strip to remove any harmless trailing white space AND and leading
#white space (copes with 21 or 26 indents and orther variants)
assert line[:2] == "FT"
feature_lines.append(line[self.FEATURE_QUALIFIER_INDENT:].strip())
line = self.handle.readline()
feature_key, location, qualifiers = \
self.parse_feature(feature_key, feature_lines)
#Try to handle known problems with IMGT locations here:
if ">" in location:
#Nasty hack for common IMGT bug, should be >123 not 123>
#in a location string. At least here the meaning is clear,
#and since it is so common I don't want to issue a warning
#warnings.warn("Feature location %s is invalid, "
# "moving greater than sign before position"
# % location)
location = bad_position_re.sub(r'>\1',location)
features.append((feature_key, location, qualifiers))
self.line = line
return features
class GenBankScanner(InsdcScanner):
"""For extracting chunks of information in GenBank files"""
RECORD_START = "LOCUS "
HEADER_WIDTH = 12
FEATURE_START_MARKERS = ["FEATURES Location/Qualifiers","FEATURES"]
FEATURE_END_MARKERS = []
FEATURE_QUALIFIER_INDENT = 21
FEATURE_QUALIFIER_SPACER = " " * FEATURE_QUALIFIER_INDENT
SEQUENCE_HEADERS=["CONTIG", "ORIGIN", "BASE COUNT", "WGS"] # trailing spaces removed
def parse_footer(self):
"""returns a tuple containing a list of any misc strings, and the sequence"""
assert self.line[:self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS, \
"Eh? '%s'" % self.line
misc_lines = []
while self.line[:self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS \
or self.line[:self.HEADER_WIDTH] == " "*self.HEADER_WIDTH \
or "WGS" == self.line[:3]:
misc_lines.append(self.line.rstrip())
self.line = self.handle.readline()
if not self.line:
raise ValueError("Premature end of file")
self.line = self.line
assert self.line[:self.HEADER_WIDTH].rstrip() not in self.SEQUENCE_HEADERS, \
"Eh? '%s'" % self.line
#Now just consume the sequence lines until reach the // marker
#or a CONTIG line
seq_lines = []
line = self.line
while True:
if not line:
raise ValueError("Premature end of file in sequence data")
line = line.rstrip()
if not line:
import warnings
warnings.warn("Blank line in sequence data")
line = self.handle.readline()
continue
if line=='//':
break
if line.find('CONTIG')==0:
break
if len(line) > 9 and line[9:10]!=' ':
raise ValueError("Sequence line mal-formed, '%s'" % line)
seq_lines.append(line[10:]) #remove spaces later
line = self.handle.readline()
self.line = line
#Seq("".join(seq_lines), self.alphabet)
return (misc_lines,"".join(seq_lines).replace(" ",""))
def _feed_first_line(self, consumer, line):
#####################################
# LOCUS line #
#####################################
GENBANK_INDENT = self.HEADER_WIDTH
GENBANK_SPACER = " "*GENBANK_INDENT
assert line[0:GENBANK_INDENT] == 'LOCUS ', \
'LOCUS line does not start correctly:\n' + line
#Have to break up the locus line, and handle the different bits of it.
#There are at least two different versions of the locus line...
if line[29:33] in [' bp ', ' aa ',' rc ']:
#Old...
#
# Positions Contents
# --------- --------
# 00:06 LOCUS
# 06:12 spaces
# 12:?? Locus name
# ??:?? space
# ??:29 Length of sequence, right-justified
# 29:33 space, bp, space
# 33:41 strand type
# 41:42 space
# 42:51 Blank (implies linear), linear or circular
# 51:52 space
# 52:55 The division code (e.g. BCT, VRL, INV)
# 55:62 space
# 62:73 Date, in the form dd-MMM-yyyy (e.g., 15-MAR-1991)
#
assert line[29:33] in [' bp ', ' aa ',' rc '] , \
'LOCUS line does not contain size units at expected position:\n' + line
assert line[41:42] == ' ', \
'LOCUS line does not contain space at position 42:\n' + line
assert line[42:51].strip() in ['','linear','circular'], \
'LOCUS line does not contain valid entry (linear, circular, ...):\n' + line
assert line[51:52] == ' ', \
'LOCUS line does not contain space at position 52:\n' + line
assert line[55:62] == ' ', \
'LOCUS line does not contain spaces from position 56 to 62:\n' + line
if line[62:73].strip():
assert line[64:65] == '-', \
'LOCUS line does not contain - at position 65 in date:\n' + line
assert line[68:69] == '-', \
'LOCUS line does not contain - at position 69 in date:\n' + line
name_and_length_str = line[GENBANK_INDENT:29]
while name_and_length_str.find(' ')!=-1:
name_and_length_str = name_and_length_str.replace(' ',' ')
name_and_length = name_and_length_str.split(' ')
assert len(name_and_length)<=2, \
'Cannot parse the name and length in the LOCUS line:\n' + line
assert len(name_and_length)!=1, \
'Name and length collide in the LOCUS line:\n' + line
#Should be possible to split them based on position, if
#a clear definition of the standard exists THAT AGREES with
#existing files.
consumer.locus(name_and_length[0])
consumer.size(name_and_length[1])
#consumer.residue_type(line[33:41].strip())
if line[33:51].strip() == "" and line[29:33] == ' aa ':
#Amino acids -> protein (even if there is no residue type given)
#We want to use a protein alphabet in this case, rather than a
#generic one. Not sure if this is the best way to achieve this,
#but it works because the scanner checks for this:
consumer.residue_type("PROTEIN")
else:
consumer.residue_type(line[33:51].strip())
consumer.data_file_division(line[52:55])
if line[62:73].strip():
consumer.date(line[62:73])
elif line[40:44] in [' bp ', ' aa ',' rc ']:
#New...
#
# Positions Contents
# --------- --------
# 00:06 LOCUS
# 06:12 spaces
# 12:?? Locus name
# ??:?? space
# ??:40 Length of sequence, right-justified
# 40:44 space, bp, space
# 44:47 Blank, ss-, ds-, ms-
# 47:54 Blank, DNA, RNA, tRNA, mRNA, uRNA, snRNA, cDNA
# 54:55 space
# 55:63 Blank (implies linear), linear or circular
# 63:64 space
# 64:67 The division code (e.g. BCT, VRL, INV)
# 67:68 space
# 68:79 Date, in the form dd-MMM-yyyy (e.g., 15-MAR-1991)
#
assert line[40:44] in [' bp ', ' aa ',' rc '] , \
'LOCUS line does not contain size units at expected position:\n' + line
assert line[44:47] in [' ', 'ss-', 'ds-', 'ms-'], \
'LOCUS line does not have valid strand type (Single stranded, ...):\n' + line
assert line[47:54].strip() == "" \
or line[47:54].strip().find('DNA') != -1 \
or line[47:54].strip().find('RNA') != -1, \
'LOCUS line does not contain valid sequence type (DNA, RNA, ...):\n' + line
assert line[54:55] == ' ', \
'LOCUS line does not contain space at position 55:\n' + line
assert line[55:63].strip() in ['','linear','circular'], \
'LOCUS line does not contain valid entry (linear, circular, ...):\n' + line
assert line[63:64] == ' ', \
'LOCUS line does not contain space at position 64:\n' + line
assert line[67:68] == ' ', \
'LOCUS line does not contain space at position 68:\n' + line
if line[68:79].strip():
assert line[70:71] == '-', \
'LOCUS line does not contain - at position 71 in date:\n' + line
assert line[74:75] == '-', \
'LOCUS line does not contain - at position 75 in date:\n' + line
name_and_length_str = line[GENBANK_INDENT:40]
while name_and_length_str.find(' ')!=-1:
name_and_length_str = name_and_length_str.replace(' ',' ')
name_and_length = name_and_length_str.split(' ')
assert len(name_and_length)<=2, \
'Cannot parse the name and length in the LOCUS line:\n' + line
assert len(name_and_length)!=1, \
'Name and length collide in the LOCUS line:\n' + line
#Should be possible to split them based on position, if
#a clear definition of the stand exists THAT AGREES with
#existing files.
consumer.locus(name_and_length[0])
consumer.size(name_and_length[1])
if line[44:54].strip() == "" and line[40:44] == ' aa ':
#Amino acids -> protein (even if there is no residue type given)
#We want to use a protein alphabet in this case, rather than a
#generic one. Not sure if this is the best way to achieve this,
#but it works because the scanner checks for this:
consumer.residue_type(("PROTEIN " + line[54:63]).strip())
else:
consumer.residue_type(line[44:63].strip())
consumer.data_file_division(line[64:67])
if line[68:79].strip():
consumer.date(line[68:79])
elif line[GENBANK_INDENT:].strip().count(" ")==0 :
#Truncated LOCUS line, as produced by some EMBOSS tools - see bug 1762
#
#e.g.
#
# "LOCUS U00096"
#
#rather than:
#
# "LOCUS U00096 4639675 bp DNA circular BCT"
#
# Positions Contents
# --------- --------
# 00:06 LOCUS
# 06:12 spaces
# 12:?? Locus name
if line[GENBANK_INDENT:].strip() != "":
consumer.locus(line[GENBANK_INDENT:].strip())
else:
#Must just have just "LOCUS ", is this even legitimate?
#We should be able to continue parsing... we need real world testcases!
warnings.warn("Minimal LOCUS line found - is this correct?\n" + line)
elif len(line.split())>=4 and line.split()[3] in ["aa","bp"]:
#Cope with EMBOSS seqret output where it seems the locus id can cause
#the other fields to overflow. We just IGNORE the other fields!
consumer.locus(line.split()[1])
consumer.size(line.split()[2])
warnings.warn("Malformed LOCUS line found - is this correct?\n" + line)
else:
raise ValueError('Did not recognise the LOCUS line layout:\n' + line)
def _feed_header_lines(self, consumer, lines):
#Following dictionary maps GenBank lines to the associated
#consumer methods - the special cases like LOCUS where one
#genbank line triggers several consumer calls have to be
#handled individually.
GENBANK_INDENT = self.HEADER_WIDTH
GENBANK_SPACER = " "*GENBANK_INDENT
consumer_dict = {
'DEFINITION' : 'definition',
'ACCESSION' : 'accession',
'NID' : 'nid',
'PID' : 'pid',
'DBSOURCE' : 'db_source',
'KEYWORDS' : 'keywords',
'SEGMENT' : 'segment',
'SOURCE' : 'source',
'AUTHORS' : 'authors',
'CONSRTM' : 'consrtm',
'PROJECT' : 'project',
'DBLINK' : 'dblink',
'TITLE' : 'title',
'JOURNAL' : 'journal',
'MEDLINE' : 'medline_id',
'PUBMED' : 'pubmed_id',
'REMARK' : 'remark'}
#We have to handle the following specially:
#ORIGIN (locus, size, residue_type, data_file_division and date)
#COMMENT (comment)
#VERSION (version and gi)
#REFERENCE (eference_num and reference_bases)
#ORGANISM (organism and taxonomy)
lines = filter(None,lines)
lines.append("") #helps avoid getting StopIteration all the time
line_iter = iter(lines)
try:
line = line_iter.next()
while True:
if not line : break
line_type = line[:GENBANK_INDENT].strip()
data = line[GENBANK_INDENT:].strip()
if line_type == 'VERSION':
#Need to call consumer.version(), and maybe also consumer.gi() as well.
#e.g.
# VERSION AC007323.5 GI:6587720
while data.find(' ')!=-1:
data = data.replace(' ',' ')
if data.find(' GI:')==-1:
consumer.version(data)
else:
if self.debug : print "Version [" + data.split(' GI:')[0] + "], gi [" + data.split(' GI:')[1] + "]"
consumer.version(data.split(' GI:')[0])
consumer.gi(data.split(' GI:')[1])
#Read in the next line!
line = line_iter.next()
elif line_type == 'REFERENCE':
if self.debug >1 : print "Found reference [" + data + "]"
#Need to call consumer.reference_num() and consumer.reference_bases()
#e.g.
# REFERENCE 1 (bases 1 to 86436)
#
#Note that this can be multiline, see Bug 1968, e.g.
#
# REFERENCE 42 (bases 1517 to 1696; 3932 to 4112; 17880 to 17975; 21142 to
# 28259)
#
#For such cases we will call the consumer once only.
data = data.strip()
#Read in the next line, and see if its more of the reference:
while True:
line = line_iter.next()
if line[:GENBANK_INDENT] == GENBANK_SPACER:
#Add this continuation to the data string
data += " " + line[GENBANK_INDENT:]
if self.debug >1 : print "Extended reference text [" + data + "]"
else:
#End of the reference, leave this text in the variable "line"
break
#We now have all the reference line(s) stored in a string, data,
#which we pass to the consumer
while data.find(' ')!=-1:
data = data.replace(' ',' ')
if data.find(' ')==-1:
if self.debug >2 : print 'Reference number \"' + data + '\"'
consumer.reference_num(data)
else:
if self.debug >2 : print 'Reference number \"' + data[:data.find(' ')] + '\", \"' + data[data.find(' ')+1:] + '\"'
consumer.reference_num(data[:data.find(' ')])
consumer.reference_bases(data[data.find(' ')+1:])
elif line_type == 'ORGANISM':
#Typically the first line is the organism, and subsequent lines
#are the taxonomy lineage. However, given longer and longer
#species names (as more and more strains and sub strains get
#sequenced) the oragnism name can now get wrapped onto multiple
#lines. The NCBI say we have to recognise the lineage line by
#the presense of semi-colon delimited entries. In the long term,
#they are considering adding a new keyword (e.g. LINEAGE).
#See Bug 2591 for details.
organism_data = data
lineage_data = ""
while True:
line = line_iter.next()
if line[0:GENBANK_INDENT] == GENBANK_SPACER:
if lineage_data or ";" in line:
lineage_data += " " + line[GENBANK_INDENT:]
else:
organism_data += " " + line[GENBANK_INDENT:].strip()
else:
#End of organism and taxonomy
break
consumer.organism(organism_data)
if lineage_data.strip() == "" and self.debug > 1:
print "Taxonomy line(s) missing or blank"
consumer.taxonomy(lineage_data.strip())
del organism_data, lineage_data
elif line_type == 'COMMENT':
if self.debug > 1 : print "Found comment"
#This can be multiline, and should call consumer.comment() once
#with a list where each entry is a line.
comment_list=[]
comment_list.append(data)
while True:
line = line_iter.next()
if line[0:GENBANK_INDENT] == GENBANK_SPACER:
data = line[GENBANK_INDENT:]
comment_list.append(data)
if self.debug > 2 : print "Comment continuation [" + data + "]"
else:
#End of the comment
break
consumer.comment(comment_list)
del comment_list
elif line_type in consumer_dict:
#Its a semi-automatic entry!
#Now, this may be a multi line entry...
while True:
line = line_iter.next()
if line[0:GENBANK_INDENT] == GENBANK_SPACER:
data += ' ' + line[GENBANK_INDENT:]
else:
#We now have all the data for this entry:
getattr(consumer, consumer_dict[line_type])(data)
#End of continuation - return to top of loop!
break
else:
if self.debug:
print "Ignoring GenBank header line:\n" % line
#Read in next line
line = line_iter.next()
except StopIteration:
raise ValueError("Problem in header")
def _feed_misc_lines(self, consumer, lines):
#Deals with a few misc lines between the features and the sequence
GENBANK_INDENT = self.HEADER_WIDTH
GENBANK_SPACER = " "*GENBANK_INDENT
lines.append("")
line_iter = iter(lines)
try:
for line in line_iter:
if line.find('BASE COUNT')==0:
line = line[10:].strip()
if line:
if self.debug : print "base_count = " + line
consumer.base_count(line)
if line.find("ORIGIN")==0:
line = line[6:].strip()
if line:
if self.debug : print "origin_name = " + line
consumer.origin_name(line)
if line.find("WGS ")==0 :
line = line[3:].strip()
consumer.wgs(line)
if line.find("WGS_SCAFLD")==0 :
line = line[10:].strip()
consumer.add_wgs_scafld(line)
if line.find("CONTIG")==0:
line = line[6:].strip()
contig_location = line
while True:
line = line_iter.next()
if not line:
break
elif line[:GENBANK_INDENT]==GENBANK_SPACER:
#Don't need to preseve the whitespace here.
contig_location += line[GENBANK_INDENT:].rstrip()
else:
raise ValueError('Expected CONTIG continuation line, got:\n' + line)
consumer.contig_location(contig_location)
return
except StopIteration:
raise ValueError("Problem in misc lines before sequence")
if __name__ == "__main__":
from StringIO import StringIO
gbk_example = \
"""LOCUS SCU49845 5028 bp DNA PLN 21-JUN-1999
DEFINITION Saccharomyces cerevisiae TCP1-beta gene, partial cds, and Axl2p
(AXL2) and Rev7p (REV7) genes, complete cds.
ACCESSION U49845
VERSION U49845.1 GI:1293613
KEYWORDS .
SOURCE Saccharomyces cerevisiae (baker's yeast)
ORGANISM Saccharomyces cerevisiae
Eukaryota; Fungi; Ascomycota; Saccharomycotina; Saccharomycetes;
Saccharomycetales; Saccharomycetaceae; Saccharomyces.
REFERENCE 1 (bases 1 to 5028)
AUTHORS Torpey,L.E., Gibbs,P.E., Nelson,J. and Lawrence,C.W.
TITLE Cloning and sequence of REV7, a gene whose function is required for
DNA damage-induced mutagenesis in Saccharomyces cerevisiae
JOURNAL Yeast 10 (11), 1503-1509 (1994)
PUBMED 7871890
REFERENCE 2 (bases 1 to 5028)
AUTHORS Roemer,T., Madden,K., Chang,J. and Snyder,M.
TITLE Selection of axial growth sites in yeast requires Axl2p, a novel
plasma membrane glycoprotein
JOURNAL Genes Dev. 10 (7), 777-793 (1996)
PUBMED 8846915
REFERENCE 3 (bases 1 to 5028)
AUTHORS Roemer,T.
TITLE Direct Submission
JOURNAL Submitted (22-FEB-1996) Terry Roemer, Biology, Yale University, New
Haven, CT, USA
FEATURES Location/Qualifiers
source 1..5028
/organism="Saccharomyces cerevisiae"
/db_xref="taxon:4932"
/chromosome="IX"
/map="9"
CDS <1..206
/codon_start=3
/product="TCP1-beta"
/protein_id="AAA98665.1"
/db_xref="GI:1293614"
/translation="SSIYNGISTSGLDLNNGTIADMRQLGIVESYKLKRAVVSSASEA
AEVLLRVDNIIRARPRTANRQHM"
gene 687..3158
/gene="AXL2"
CDS 687..3158
/gene="AXL2"
/note="plasma membrane glycoprotein"
/codon_start=1
/function="required for axial budding pattern of S.
cerevisiae"
/product="Axl2p"
/protein_id="AAA98666.1"
/db_xref="GI:1293615"
/translation="MTQLQISLLLTATISLLHLVVATPYEAYPIGKQYPPVARVNESF
TFQISNDTYKSSVDKTAQITYNCFDLPSWLSFDSSSRTFSGEPSSDLLSDANTTLYFN
VILEGTDSADSTSLNNTYQFVVTNRPSISLSSDFNLLALLKNYGYTNGKNALKLDPNE
VFNVTFDRSMFTNEESIVSYYGRSQLYNAPLPNWLFFDSGELKFTGTAPVINSAIAPE
TSYSFVIIATDIEGFSAVEVEFELVIGAHQLTTSIQNSLIINVTDTGNVSYDLPLNYV
YLDDDPISSDKLGSINLLDAPDWVALDNATISGSVPDELLGKNSNPANFSVSIYDTYG
DVIYFNFEVVSTTDLFAISSLPNINATRGEWFSYYFLPSQFTDYVNTNVSLEFTNSSQ
DHDWVKFQSSNLTLAGEVPKNFDKLSLGLKANQGSQSQELYFNIIGMDSKITHSNHSA
NATSTRSSHHSTSTSSYTSSTYTAKISSTSAAATSSAPAALPAANKTSSHNKKAVAIA
CGVAIPLGVILVALICFLIFWRRRRENPDDENLPHAISGPDLNNPANKPNQENATPLN
NPFDDDASSYDDTSIARRLAALNTLKLDNHSATESDISSVDEKRDSLSGMNTYNDQFQ
SQSKEELLAKPPVQPPESPFFDPQNRSSSVYMDSEPAVNKSWRYTGNLSPVSDIVRDS
YGSQKTVDTEKLFDLEAPEKEKRTSRDVTMSSLDPWNSNISPSPVRKSVTPSPYNVTK
HRNRHLQNIQDSQSGKNGITPTTMSTSSSDDFVPVKDGENFCWVHSMEPDRRPSKKRL
VDFSNKSNVNVGQVKDIHGRIPEML"
gene complement(3300..4037)
/gene="REV7"
CDS complement(3300..4037)
/gene="REV7"
/codon_start=1
/product="Rev7p"
/protein_id="AAA98667.1"
/db_xref="GI:1293616"
/translation="MNRWVEKWLRVYLKCYINLILFYRNVYPPQSFDYTTYQSFNLPQ
FVPINRHPALIDYIEELILDVLSKLTHVYRFSICIINKKNDLCIEKYVLDFSELQHVD
KDDQIITETEVFDEFRSSLNSLIMHLEKLPKVNDDTITFEAVINAIELELGHKLDRNR
RVDSLEEKAEIERDSNWVKCQEDENLPDNNGFQPPKIKLTSLVGSDVGPLIIHQFSEK
LISGDDKILNGVYSQYEEGESIFGSLF"
ORIGIN
1 gatcctccat atacaacggt atctccacct caggtttaga tctcaacaac ggaaccattg
61 ccgacatgag acagttaggt atcgtcgaga gttacaagct aaaacgagca gtagtcagct
121 ctgcatctga agccgctgaa gttctactaa gggtggataa catcatccgt gcaagaccaa
181 gaaccgccaa tagacaacat atgtaacata tttaggatat acctcgaaaa taataaaccg
241 ccacactgtc attattataa ttagaaacag aacgcaaaaa ttatccacta tataattcaa
301 agacgcgaaa aaaaaagaac aacgcgtcat agaacttttg gcaattcgcg tcacaaataa
361 attttggcaa cttatgtttc ctcttcgagc agtactcgag ccctgtctca agaatgtaat
421 aatacccatc gtaggtatgg ttaaagatag catctccaca acctcaaagc tccttgccga
481 gagtcgccct cctttgtcga gtaattttca cttttcatat gagaacttat tttcttattc
541 tttactctca catcctgtag tgattgacac tgcaacagcc accatcacta gaagaacaga
601 acaattactt aatagaaaaa ttatatcttc ctcgaaacga tttcctgctt ccaacatcta
661 cgtatatcaa gaagcattca cttaccatga cacagcttca gatttcatta ttgctgacag
721 ctactatatc actactccat ctagtagtgg ccacgcccta tgaggcatat cctatcggaa
781 aacaataccc cccagtggca agagtcaatg aatcgtttac atttcaaatt tccaatgata
841 cctataaatc gtctgtagac aagacagctc aaataacata caattgcttc gacttaccga
901 gctggctttc gtttgactct agttctagaa cgttctcagg tgaaccttct tctgacttac
961 tatctgatgc gaacaccacg ttgtatttca atgtaatact cgagggtacg gactctgccg
1021 acagcacgtc tttgaacaat acataccaat ttgttgttac aaaccgtcca tccatctcgc
1081 tatcgtcaga tttcaatcta ttggcgttgt taaaaaacta tggttatact aacggcaaaa
1141 acgctctgaa actagatcct aatgaagtct tcaacgtgac ttttgaccgt tcaatgttca
1201 ctaacgaaga atccattgtg tcgtattacg gacgttctca gttgtataat gcgccgttac
1261 ccaattggct gttcttcgat tctggcgagt tgaagtttac tgggacggca ccggtgataa
1321 actcggcgat tgctccagaa acaagctaca gttttgtcat catcgctaca gacattgaag
1381 gattttctgc cgttgaggta gaattcgaat tagtcatcgg ggctcaccag ttaactacct
1441 ctattcaaaa tagtttgata atcaacgtta ctgacacagg taacgtttca tatgacttac
1501 ctctaaacta tgtttatctc gatgacgatc ctatttcttc tgataaattg ggttctataa
1561 acttattgga tgctccagac tgggtggcat tagataatgc taccatttcc gggtctgtcc
1621 cagatgaatt actcggtaag aactccaatc ctgccaattt ttctgtgtcc atttatgata
1681 cttatggtga tgtgatttat ttcaacttcg aagttgtctc cacaacggat ttgtttgcca
1741 ttagttctct tcccaatatt aacgctacaa ggggtgaatg gttctcctac tattttttgc
1801 cttctcagtt tacagactac gtgaatacaa acgtttcatt agagtttact aattcaagcc
1861 aagaccatga ctgggtgaaa ttccaatcat ctaatttaac attagctgga gaagtgccca
1921 agaatttcga caagctttca ttaggtttga aagcgaacca aggttcacaa tctcaagagc
1981 tatattttaa catcattggc atggattcaa agataactca ctcaaaccac agtgcgaatg
2041 caacgtccac aagaagttct caccactcca cctcaacaag ttcttacaca tcttctactt
2101 acactgcaaa aatttcttct acctccgctg ctgctacttc ttctgctcca gcagcgctgc
2161 cagcagccaa taaaacttca tctcacaata aaaaagcagt agcaattgcg tgcggtgttg
2221 ctatcccatt aggcgttatc ctagtagctc tcatttgctt cctaatattc tggagacgca
2281 gaagggaaaa tccagacgat gaaaacttac cgcatgctat tagtggacct gatttgaata
2341 atcctgcaaa taaaccaaat caagaaaacg ctacaccttt gaacaacccc tttgatgatg
2401 atgcttcctc gtacgatgat acttcaatag caagaagatt ggctgctttg aacactttga
2461 aattggataa ccactctgcc actgaatctg atatttccag cgtggatgaa aagagagatt
2521 ctctatcagg tatgaataca tacaatgatc agttccaatc ccaaagtaaa gaagaattat
2581 tagcaaaacc cccagtacag cctccagaga gcccgttctt tgacccacag aataggtctt
2641 cttctgtgta tatggatagt gaaccagcag taaataaatc ctggcgatat actggcaacc
2701 tgtcaccagt ctctgatatt gtcagagaca gttacggatc acaaaaaact gttgatacag
2761 aaaaactttt cgatttagaa gcaccagaga aggaaaaacg tacgtcaagg gatgtcacta
2821 tgtcttcact ggacccttgg aacagcaata ttagcccttc tcccgtaaga aaatcagtaa
2881 caccatcacc atataacgta acgaagcatc gtaaccgcca cttacaaaat attcaagact
2941 ctcaaagcgg taaaaacgga atcactccca caacaatgtc aacttcatct tctgacgatt
3001 ttgttccggt taaagatggt gaaaattttt gctgggtcca tagcatggaa ccagacagaa
3061 gaccaagtaa gaaaaggtta gtagattttt caaataagag taatgtcaat gttggtcaag
3121 ttaaggacat tcacggacgc atcccagaaa tgctgtgatt atacgcaacg atattttgct
3181 taattttatt ttcctgtttt attttttatt agtggtttac agatacccta tattttattt
3241 agtttttata cttagagaca tttaatttta attccattct tcaaatttca tttttgcact
3301 taaaacaaag atccaaaaat gctctcgccc tcttcatatt gagaatacac tccattcaaa
3361 attttgtcgt caccgctgat taatttttca ctaaactgat gaataatcaa aggccccacg
3421 tcagaaccga ctaaagaagt gagttttatt ttaggaggtt gaaaaccatt attgtctggt
3481 aaattttcat cttcttgaca tttaacccag tttgaatccc tttcaatttc tgctttttcc
3541 tccaaactat cgaccctcct gtttctgtcc aacttatgtc ctagttccaa ttcgatcgca
3601 ttaataactg cttcaaatgt tattgtgtca tcgttgactt taggtaattt ctccaaatgc
3661 ataatcaaac tatttaagga agatcggaat tcgtcgaaca cttcagtttc cgtaatgatc
3721 tgatcgtctt tatccacatg ttgtaattca ctaaaatcta aaacgtattt ttcaatgcat
3781 aaatcgttct ttttattaat aatgcagatg gaaaatctgt aaacgtgcgt taatttagaa
3841 agaacatcca gtataagttc ttctatatag tcaattaaag caggatgcct attaatggga
3901 acgaactgcg gcaagttgaa tgactggtaa gtagtgtagt cgaatgactg aggtgggtat
3961 acatttctat aaaataaaat caaattaatg tagcatttta agtataccct cagccacttc
4021 tctacccatc tattcataaa gctgacgcaa cgattactat tttttttttc ttcttggatc
4081 tcagtcgtcg caaaaacgta taccttcttt ttccgacctt ttttttagct ttctggaaaa
4141 gtttatatta gttaaacagg gtctagtctt agtgtgaaag ctagtggttt cgattgactg
4201 atattaagaa agtggaaatt aaattagtag tgtagacgta tatgcatatg tatttctcgc
4261 ctgtttatgt ttctacgtac ttttgattta tagcaagggg aaaagaaata catactattt
4321 tttggtaaag gtgaaagcat aatgtaaaag ctagaataaa atggacgaaa taaagagagg
4381 cttagttcat cttttttcca aaaagcaccc aatgataata actaaaatga aaaggatttg
4441 ccatctgtca gcaacatcag ttgtgtgagc aataataaaa tcatcacctc cgttgccttt
4501 agcgcgtttg tcgtttgtat cttccgtaat tttagtctta tcaatgggaa tcataaattt
4561 tccaatgaat tagcaatttc gtccaattct ttttgagctt cttcatattt gctttggaat
4621 tcttcgcact tcttttccca ttcatctctt tcttcttcca aagcaacgat ccttctaccc
4681 atttgctcag agttcaaatc ggcctctttc agtttatcca ttgcttcctt cagtttggct
4741 tcactgtctt ctagctgttg ttctagatcc tggtttttct tggtgtagtt ctcattatta
4801 gatctcaagt tattggagtc ttcagccaat tgctttgtat cagacaattg actctctaac
4861 ttctccactt cactgtcgag ttgctcgttt ttagcggaca aagatttaat ctcgttttct
4921 ttttcagtgt tagattgctc taattctttg agctgttctc tcagctcctc atatttttct
4981 tgccatgact cagattctaa ttttaagcta ttcaatttct ctttgatc
//"""
# GenBank format protein (aka GenPept) file from:
# http://www.molecularevolution.org/resources/fileformats/
gbk_example2 = \
"""LOCUS AAD51968 143 aa linear BCT 21-AUG-2001
DEFINITION transcriptional regulator RovA [Yersinia enterocolitica].
ACCESSION AAD51968
VERSION AAD51968.1 GI:5805369
DBSOURCE locus AF171097 accession AF171097.1
KEYWORDS .
SOURCE Yersinia enterocolitica
ORGANISM Yersinia enterocolitica
Bacteria; Proteobacteria; Gammaproteobacteria; Enterobacteriales;
Enterobacteriaceae; Yersinia.
REFERENCE 1 (residues 1 to 143)
AUTHORS Revell,P.A. and Miller,V.L.
TITLE A chromosomally encoded regulator is required for expression of the
Yersinia enterocolitica inv gene and for virulence
JOURNAL Mol. Microbiol. 35 (3), 677-685 (2000)
MEDLINE 20138369
PUBMED 10672189
REFERENCE 2 (residues 1 to 143)
AUTHORS Revell,P.A. and Miller,V.L.
TITLE Direct Submission
JOURNAL Submitted (22-JUL-1999) Molecular Microbiology, Washington
University School of Medicine, Campus Box 8230, 660 South Euclid,
St. Louis, MO 63110, USA
COMMENT Method: conceptual translation.
FEATURES Location/Qualifiers
source 1..143
/organism="Yersinia enterocolitica"
/mol_type="unassigned DNA"
/strain="JB580v"
/serotype="O:8"
/db_xref="taxon:630"
Protein 1..143
/product="transcriptional regulator RovA"
/name="regulates inv expression"
CDS 1..143
/gene="rovA"
/coded_by="AF171097.1:380..811"
/note="regulator of virulence"
/transl_table=11
ORIGIN
1 mestlgsdla rlvrvwrali dhrlkplelt qthwvtlhni nrlppeqsqi qlakaigieq
61 pslvrtldql eekglitrht candrrakri klteqsspii eqvdgvicst rkeilggisp
121 deiellsgli dklerniiql qsk
//
"""
embl_example="""ID X56734; SV 1; linear; mRNA; STD; PLN; 1859 BP.
XX
AC X56734; S46826;
XX
DT 12-SEP-1991 (Rel. 29, Created)
DT 25-NOV-2005 (Rel. 85, Last updated, Version 11)
XX
DE Trifolium repens mRNA for non-cyanogenic beta-glucosidase
XX
KW beta-glucosidase.
XX
OS Trifolium repens (white clover)
OC Eukaryota; Viridiplantae; Streptophyta; Embryophyta; Tracheophyta;
OC Spermatophyta; Magnoliophyta; eudicotyledons; core eudicotyledons; rosids;
OC eurosids I; Fabales; Fabaceae; Papilionoideae; Trifolieae; Trifolium.
XX
RN [5]
RP 1-1859
RX PUBMED; 1907511.
RA Oxtoby E., Dunn M.A., Pancoro A., Hughes M.A.;
RT "Nucleotide and derived amino acid sequence of the cyanogenic
RT beta-glucosidase (linamarase) from white clover (Trifolium repens L.)";
RL Plant Mol. Biol. 17(2):209-219(1991).
XX
RN [6]
RP 1-1859
RA Hughes M.A.;
RT ;
RL Submitted (19-NOV-1990) to the EMBL/GenBank/DDBJ databases.
RL Hughes M.A., University of Newcastle Upon Tyne, Medical School, Newcastle
RL Upon Tyne, NE2 4HH, UK
XX
FH Key Location/Qualifiers
FH
FT source 1..1859
FT /organism="Trifolium repens"
FT /mol_type="mRNA"
FT /clone_lib="lambda gt10"
FT /clone="TRE361"
FT /tissue_type="leaves"
FT /db_xref="taxon:3899"
FT CDS 14..1495
FT /product="beta-glucosidase"
FT /EC_number="3.2.1.21"
FT /note="non-cyanogenic"
FT /db_xref="GOA:P26204"
FT /db_xref="InterPro:IPR001360"
FT /db_xref="InterPro:IPR013781"
FT /db_xref="UniProtKB/Swiss-Prot:P26204"
FT /protein_id="CAA40058.1"
FT /translation="MDFIVAIFALFVISSFTITSTNAVEASTLLDIGNLSRSSFPRGFI
FT FGAGSSAYQFEGAVNEGGRGPSIWDTFTHKYPEKIRDGSNADITVDQYHRYKEDVGIMK
FT DQNMDSYRFSISWPRILPKGKLSGGINHEGIKYYNNLINELLANGIQPFVTLFHWDLPQ
FT VLEDEYGGFLNSGVINDFRDYTDLCFKEFGDRVRYWSTLNEPWVFSNSGYALGTNAPGR
FT CSASNVAKPGDSGTGPYIVTHNQILAHAEAVHVYKTKYQAYQKGKIGITLVSNWLMPLD
FT DNSIPDIKAAERSLDFQFGLFMEQLTTGDYSKSMRRIVKNRLPKFSKFESSLVNGSFDF
FT IGINYYSSSYISNAPSHGNAKPSYSTNPMTNISFEKHGIPLGPRAASIWIYVYPYMFIQ
FT EDFEIFCYILKINITILQFSITENGMNEFNDATLPVEEALLNTYRIDYYYRHLYYIRSA
FT IRAGSNVKGFYAWSFLDCNEWFAGFTVRFGLNFVD"
FT mRNA 1..1859
FT /experiment="experimental evidence, no additional details
FT recorded"
XX
SQ Sequence 1859 BP; 609 A; 314 C; 355 G; 581 T; 0 other;
aaacaaacca aatatggatt ttattgtagc catatttgct ctgtttgtta ttagctcatt 60
cacaattact tccacaaatg cagttgaagc ttctactctt cttgacatag gtaacctgag 120
tcggagcagt tttcctcgtg gcttcatctt tggtgctgga tcttcagcat accaatttga 180
aggtgcagta aacgaaggcg gtagaggacc aagtatttgg gataccttca cccataaata 240
tccagaaaaa ataagggatg gaagcaatgc agacatcacg gttgaccaat atcaccgcta 300
caaggaagat gttgggatta tgaaggatca aaatatggat tcgtatagat tctcaatctc 360
ttggccaaga atactcccaa agggaaagtt gagcggaggc ataaatcacg aaggaatcaa 420
atattacaac aaccttatca acgaactatt ggctaacggt atacaaccat ttgtaactct 480
ttttcattgg gatcttcccc aagtcttaga agatgagtat ggtggtttct taaactccgg 540
tgtaataaat gattttcgag actatacgga tctttgcttc aaggaatttg gagatagagt 600
gaggtattgg agtactctaa atgagccatg ggtgtttagc aattctggat atgcactagg 660
aacaaatgca ccaggtcgat gttcggcctc caacgtggcc aagcctggtg attctggaac 720
aggaccttat atagttacac acaatcaaat tcttgctcat gcagaagctg tacatgtgta 780
taagactaaa taccaggcat atcaaaaggg aaagataggc ataacgttgg tatctaactg 840
gttaatgcca cttgatgata atagcatacc agatataaag gctgccgaga gatcacttga 900
cttccaattt ggattgttta tggaacaatt aacaacagga gattattcta agagcatgcg 960
gcgtatagtt aaaaaccgat tacctaagtt ctcaaaattc gaatcaagcc tagtgaatgg 1020
ttcatttgat tttattggta taaactatta ctcttctagt tatattagca atgccccttc 1080
acatggcaat gccaaaccca gttactcaac aaatcctatg accaatattt catttgaaaa 1140
acatgggata cccttaggtc caagggctgc ttcaatttgg atatatgttt atccatatat 1200
gtttatccaa gaggacttcg agatcttttg ttacatatta aaaataaata taacaatcct 1260
gcaattttca atcactgaaa atggtatgaa tgaattcaac gatgcaacac ttccagtaga 1320
agaagctctt ttgaatactt acagaattga ttactattac cgtcacttat actacattcg 1380
ttctgcaatc agggctggct caaatgtgaa gggtttttac gcatggtcat ttttggactg 1440
taatgaatgg tttgcaggct ttactgttcg ttttggatta aactttgtag attagaaaga 1500
tggattaaaa aggtacccta agctttctgc ccaatggtac aagaactttc tcaaaagaaa 1560
ctagctagta ttattaaaag aactttgtag tagattacag tacatcgttt gaagttgagt 1620
tggtgcacct aattaaataa aagaggttac tcttaacata tttttaggcc attcgttgtg 1680
aagttgttag gctgttattt ctattatact atgttgtagt aataagtgca ttgttgtacc 1740
agaagctatg atcataacta taggttgatc cttcatgtat cagtttgatg ttgagaatac 1800
tttgaattaa aagtcttttt ttattttttt aaaaaaaaaa aaaaaaaaaa aaaaaaaaa 1859
//
"""
print "GenBank CDS Iteration"
print "====================="
g = GenBankScanner()
for record in g.parse_cds_features(StringIO(gbk_example)):
print record
g = GenBankScanner()
for record in g.parse_cds_features(StringIO(gbk_example2),
tags2id=('gene','locus_tag','product')):
print record
g = GenBankScanner()
for record in g.parse_cds_features(StringIO(gbk_example + "\n" + gbk_example2),
tags2id=('gene','locus_tag','product')):
print record
print
print "GenBank Iteration"
print "================="
g = GenBankScanner()
for record in g.parse_records(StringIO(gbk_example),do_features=False):
print record.id, record.name, record.description
print record.seq
g = GenBankScanner()
for record in g.parse_records(StringIO(gbk_example),do_features=True):
print record.id, record.name, record.description
print record.seq
g = GenBankScanner()
for record in g.parse_records(StringIO(gbk_example2),do_features=False):
print record.id, record.name, record.description
print record.seq
g = GenBankScanner()
for record in g.parse_records(StringIO(gbk_example2),do_features=True):
print record.id, record.name, record.description
print record.seq
print
print "EMBL CDS Iteration"
print "=================="
e = EmblScanner()
for record in e.parse_cds_features(StringIO(embl_example)):
print record
print
print "EMBL Iteration"
print "=============="
e = EmblScanner()
for record in e.parse_records(StringIO(embl_example),do_features=True):
print record.id, record.name, record.description
print record.seq
|
BlogomaticProject/Blogomatic
|
opt/blog-o-matic/usr/lib/python/Bio/GenBank/Scanner.py
|
Python
|
gpl-2.0
| 79,599
|
[
"Biopython"
] |
e447daa77575529463ac6f18fa33acb1b0a0fa9d2e4196ad2a2ababb7b3dd73e
|
#! test QC_JSON Schema for energy
import numpy as np
import psi4
import json
# Generate JSON data
json_data = {
"schema_name": "qcschema_input",
"schema_version": 1,
"molecule": {
"geometry": [
0.0,
0.0,
-0.1294769411935893,
0.0,
-1.494187339479985,
1.0274465079245698,
0.0,
1.494187339479985,
1.0274465079245698
],
"symbols": [
"O",
"H",
"H"
],
"connectivity" : [
(0, 1, 1.0),
(0, 2, 1.0)
]
},
"driver": "energy",
"model": {
"method": "MP2",
"basis": "cc-pVDZ"
},
"keywords": {"scf_type": "df",
"mp2_type": "df",
"scf_properties": ["mayer_indices"]}
}
# Write expected output
expected_return_result = -76.22831410222477
expected_properties = {
"calcinfo_nbasis": 24,
"calcinfo_nmo": 24,
"calcinfo_nalpha": 5,
"calcinfo_nbeta": 5,
"calcinfo_natom": 3,
"scf_one_electron_energy": -122.44529682915068,
"scf_two_electron_energy": 37.622437382517965,
"nuclear_repulsion_energy": 8.80146206062943,
"scf_total_energy": -76.02139738600329,
"mp2_same_spin_correlation_energy": -0.05202760538221721,
"mp2_opposite_spin_correlation_energy": -0.1548891108392641,
"mp2_singles_energy": 0.0,
"mp2_doubles_energy": -0.20691671622148142,
"mp2_total_correlation_energy": -0.20691671622148142,
"mp2_total_energy": -76.22831410222477,
"return_energy": expected_return_result
}
json_ret = psi4.json_wrapper.run_json(json_data)
# Expected output with exact MP2
expected_return_result = -76.2283674281634
expected_properties = {
"calcinfo_nbasis": 24,
"calcinfo_nmo": 24,
"calcinfo_nalpha": 5,
"calcinfo_nbeta": 5,
"calcinfo_natom": 3,
"scf_one_electron_energy": -122.44534537436829,
"scf_two_electron_energy": 37.62246494646352,
"nuclear_repulsion_energy": 8.80146206062943,
"scf_total_energy": -76.02141836727533,
"mp2_same_spin_correlation_energy": -0.051980792907589016,
"mp2_opposite_spin_correlation_energy": -0.1549682679804691,
"mp2_singles_energy": 0.0,
"mp2_doubles_energy": -0.2069490608880642,
"mp2_total_correlation_energy": -0.2069490608880642,
"mp2_total_energy": -76.2283674281634,
"return_energy": expected_return_result
}
# Switch run to exact MP2
json_data["keywords"]["scf_type"] = "pk"
json_data["keywords"]["mp2_type"] = "conv"
json_ret = psi4.json_wrapper.run_json(json_data)
# print(json.dumps(json_ret, indent=2))
|
CDSherrill/psi4
|
samples/json/schema-1-energy/input.py
|
Python
|
lgpl-3.0
| 2,453
|
[
"Psi4"
] |
084f9cdb0c57fe94e6693eaf6c5c9ed78fef21c638821f8f62d3741c01801942
|
# Audio Tools, a module and set of tools for manipulating audio data
# Copyright (C) 2007-2016 Brian Langenberger
# 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
"""a text strings module"""
DIV = u"\u2500"
# Utility usage
USAGE_TRACKCMP_CDIMAGE = u"<CD image> <track 1> <track 2> ..."
USAGE_TRACKCMP_FILES = u"<track 1> <track 2>"
# Utility Descriptions
DESCRIPTION_AT_CONFIG = \
"set default parameters"
DESCRIPTION_COVERDUMP = \
"extract embedded images from file"
DESCRIPTION_COVERBROWSE = \
"browse embedded cover art"
DESCRIPTION_CD2TRACK = \
"extract CD audio tracks to files"
DESCRIPTION_CDINFO = \
"display information about audio CD"
DESCRIPTION_CDPLAY = \
"play audio CD"
DESCRIPTION_COVERTAG = \
"set embedded file images"
DESCRIPTION_DVDA2TRACK = \
"extract DVA-A tracks to files"
DESCRIPTION_DVDAINFO = \
"display information about DVD-A"
DESCRIPTION_TRACKCMP = \
"compare two files or directories"
DESCRIPTION_TRACK2CD = \
"burn files to audio CD"
DESCRIPTION_TRACKCAT = \
"concatenate multiple files into a single file"
DESCRIPTION_TRACKINFO = \
"display information about a file"
DESCRIPTION_TRACKLENGTH = \
"summarize total file lengths, in seconds"
DESCRIPTION_TRACKLINT = \
"fix common file metadata problems"
DESCRIPTION_TRACKPLAY = \
"play files"
DESCRIPTION_TRACKRENAME = \
"rename files based on internal metadata"
DESCRIPTION_TRACKSPLIT = \
"split a single file into multiple files"
DESCRIPTION_TRACKTAG = \
"set file metadata attributes"
DESCRIPTION_TRACK2TRACK = \
"convert audio files from one format to another"
DESCRIPTION_TRACKVERIFY = \
"verify correctness of files"
# Utility Options
OPT_VERBOSE = u"the verbosity level to execute at"
OPT_VERBOSE_AT_CONFIG = u"the new default verbosity level"
OPT_INPUT_FILENAME = u"input filename"
OPT_INPUT_FILENAME_OR_DIR = u"input filename or directory"
OPT_INPUT_FILENAME_OR_IMAGE = u"input filename, directory or CD image filename"
OPT_TRACK_INDEX = u"track index number, starting from 1"
OPT_TYPE = u"the type of audio track to create"
OPT_TYPE_AT_CONFIG = u"the default audio type to use, " + \
u"or the type for a given default quality level"
OPT_TYPE_TRACKVERIFY = u"a type of audio to accept"
OPT_QUALITY = u"the quality to store audio tracks at"
OPT_QUALITY_AT_CONFIG = u"the default quality level for a given audio type"
OPT_DIR = u"the directory to store new audio tracks"
OPT_INITIAL_DIR = u"initial directory"
OPT_DIR_IMAGES = u"the directory to store extracted images"
OPT_FORMAT = u"the format string for new filenames"
OPT_METADATA_LOOKUP = u"perform metadata lookup"
OPT_NO_MUSICBRAINZ = u"do not query MusicBrainz for metadata"
OPT_NO_FREEDB = u"do not query FreeDB for metadata"
OPT_INTERACTIVE_METADATA = u"edit metadata interactively"
OPT_INTERACTIVE_OPTIONS = u"edit metadata and output options interactively"
OPT_INTERACTIVE_PLAY = u"play in interactive mode"
OPT_INTERACTIVE_AT_CONFIG = u"edit options interactively"
OPT_OUTPUT_PLAY = u"the system output to use"
OPT_OUTPUT_TRACK2TRACK = u"output filename to use, overriding default and -d"
OPT_OUTPUT_TRACKCAT = u"the output file"
OPT_DEFAULT = u"when multiple choices are available, " + \
u"select the first one automatically"
OPT_ALBUM_NUMBER = \
u"the album number of this disc, if it is one of a series of albums"
OPT_ALBUM_TOTAL = \
u"the total albums of this disc\'s set, if it is one of a series of albums"
OPT_REPLAY_GAIN = u"add ReplayGain metadata to newly created tracks"
OPT_REPLAY_GAIN_TRACKTAG = u"add ReplayGain metadata to tracks"
OPT_REMOVE_REPLAY_GAIN_TRACKTAG = u"remove ReplayGain metadata from tracks"
OPT_NO_REPLAY_GAIN = u"do not add ReplayGain metadata in newly created tracks"
OPT_PLAYBACK_TRACK_GAIN = u"apply track ReplayGain during playback, if present"
OPT_PLAYBACK_ALBUM_GAIN = u"apply album ReplayGain during playback, if present"
OPT_SHUFFLE = u"shuffle tracks"
OPT_PREFIX = u"add a prefix to the output image"
OPT_NO_GTK = u"don't use PyGTK for GUI"
OPT_NO_TKINTER = u"don't use Tkinter for GUI"
OPT_AUDIO_TS = u"location of AUDIO_TS directory"
OPT_DVDA_TITLE = u"DVD-Audio title number to extract tracks from"
OPT_TRACK_START = u"the starting track number of the title being extracted"
OPT_TRACK_TOTAL = \
u"the total number of tracks, if the extracted title is only a subset"
OPT_SPEED = u"the speed to burn the CD at"
OPT_CUESHEET_TRACK2CD = u"the cuesheet to use for writing tracks"
OPT_JOINT = u"the maximum number of processes to run at a time"
OPT_CUESHEET_TRACKCAT = u"a cuesheet to embed in the output file"
OPT_ADD_CUESHEET_TRACKCAT = u"create a cuesheet to embed in the output file"
OPT_CUESHEET_TRACKSPLIT = u"the cuesheet to use for splitting track"
OPT_CUESHEET_TRACKCMP = u"cuesheet to use for comparing disc image to tracks"
OPT_CUESHEET_TRACKVERIFY = \
u"the cuesheet to verify disc image with AccurateRip"
OPT_CUESHEET_CDDA2TRACK = \
u"cuesheet to generate from CD contents"
OPT_NO_SUMMARY = u"suppress summary output"
OPT_ACCURATERIP = u"verify tracks against those of AccurateRip database"
OPT_SAMPLE_RATE = u"sample rate of output files, in Hz"
OPT_CHANNELS = u"channel count of output files"
OPT_BPS = u"bits-per-sample of output files"
OPT_TRACKLINT_FIX = u"perform suggest fixes"
OPT_TRACKTAG_COMMENT_FILE = u"a file containing comment text"
OPT_TRACKTAG_REPLACE = u"completely replace all metadata"
OPT_TRACKTAG_CUESHEET = u"a cuesheet to import or get audio metadata from"
OPT_TRACKTAG_REMOVE_IMAGES = u"remove existing images prior to adding new ones"
OPT_TRACKTAG_FRONT_COVER = u"an image file of the front cover"
OPT_TRACKTAG_BACK_COVER = u"an image file of the back cover"
OPT_TRACKTAG_LEAFLET = u"an image file of a leaflet page"
OPT_TRACKTAG_MEDIA = u"an image file of the media"
OPT_TRACKTAG_OTHER_IMAGE = u"an image file related to the track"
OPT_AT_CONFIG_READ_OFFSET = u"the CD-ROM read offset to use"
OPT_AT_CONFIG_WRITE_OFFSET = u"the CD-ROM write offset to use"
OPT_AT_CONFIG_FS_ENCODING = u"the filesystem's text encoding"
OPT_AT_CONFIG_IO_ENCODING = u"the system's text encoding"
OPT_AT_CONFIG_ID3V2_VERSION = u"which ID3v2 version to use by default, if any"
OPT_AT_CONFIG_ID3V1_VERSION = u"which ID3v1 version to use by default, if any"
OPT_AT_CONFIG_ID3V2_PAD = \
u"whether or not to pad ID3v2 digit fields to 2 digits"
OPT_CAT_EXTRACTION = u"extraction arguments"
OPT_CAT_CD_LOOKUP = u"CD lookup arguments"
OPT_CAT_DVDA_LOOKUP = u"DVD-A lookup arguments"
OPT_CAT_METADATA = u"metadata arguments"
OPT_CAT_CONVERSION = u"conversion arguments"
OPT_CAT_OUTPUT_FORMAT = u"format arguments"
OPT_CAT_ENCODING = u"encoding arguments"
OPT_CAT_TEXT = u"text arguments"
OPT_CAT_IMAGE = u"image arguments"
OPT_CAT_REMOVAL = u"removal arguments"
OPT_CAT_SYSTEM = u"system arguments"
OPT_CAT_TRANSCODING = u"transcoding arguments"
OPT_CAT_ID3 = u"ID3 arguments"
OPT_CAT_REPLAYGAIN = u"ReplayGain Options"
OPT_CAT_BINARIES = u"binaries arguments"
# MetaData Fields
METADATA_TRACK_NAME = u"track name"
METADATA_TRACK_NUMBER = u"track number"
METADATA_TRACK_TOTAL = u"track total"
METADATA_ALBUM_NAME = u"album name"
METADATA_ARTIST_NAME = u"artist name"
METADATA_PERFORMER_NAME = u"performer name"
METADATA_COMPOSER_NAME = u"composer name"
METADATA_CONDUCTOR_NAME = u"conductor name"
METADATA_MEDIA = u"media"
METADATA_ISRC = u"ISRC"
METADATA_CATALOG = u"catalog number"
METADATA_COPYRIGHT = u"copyright"
METADATA_PUBLISHER = u"publisher"
METADATA_YEAR = u"release year"
METADATA_DATE = u"recording date"
METADATA_ALBUM_NUMBER = u"album number"
METADATA_ALBUM_TOTAL = u"album total"
METADATA_COMMENT = u"comment"
METADATA_COMPILATION = u"compilation part"
METADATA_TRUE = u"yes"
METADATA_FALSE = u"no"
# Derived MetaData Fields
METADATA_SUFFIX = u"file name suffix"
METADATA_ALBUM_TRACK_NUMBER = u"combined album and track number"
METADATA_BASENAME = u"file name without suffix"
# ReplayGain
RG_ADDING_REPLAYGAIN = u"Adding ReplayGain"
RG_APPLYING_REPLAYGAIN = u"Applying ReplayGain"
RG_ADDING_REPLAYGAIN_TO_ALBUM = u"Adding ReplayGain to album {:d}"
RG_ADDING_REPLAYGAIN_WAIT = \
u"Adding ReplayGain metadata. This may take some time."
RG_REPLAYGAIN_ADDED = u"ReplayGain added"
RG_REPLAYGAIN_REMOVED = u"ReplayGain removed"
RG_REPLAYGAIN_ADDED_TO_ALBUM = u"ReplayGain added to album {:d}"
RG_REPLAYGAIN_REMOVED_FROM_ALBUM = u"ReplayGain removed from album {:d}"
RG_REPLAYGAIN_REMOVED = u"ReplayGain removed"
RG_REPLAYGAIN_APPLIED = u"ReplayGain applied"
# Labels
LAB_ENCODE = u"{source} -> {destination}"
LAB_PICTURE = u"picture"
LAB_T_OPTIONS = u"Please use the -t option to specify {}"
LAB_AVAILABLE_COMPRESSION_TYPES = u"Available quality modes for \"{}\":"
LAB_AVAILABLE_FORMATS = u"Available output formats:"
LAB_OUTPUT_FORMATS = u"Output Formats"
LAB_OUTPUT_TYPE = u"type"
LAB_OUTPUT_QUALITY = u"quality"
LAB_OUTPUT_TYPE_DESCRIPTION = u"name"
LAB_OUTPUT_QUALITY_DESCRIPTION = u"description"
LAB_SUPPORTED_FIELDS = u"Supported fields are:"
LAB_CD2TRACK_PROGRESS = u"track {track_number:02d} -> {filename}"
LAB_CD2TRACK_LOG = u"Rip log : "
LAB_CD2TRACK_APPLY = u"extract tracks"
LAB_CDDA2TRACK_WROTE_CUESHEET = u"wrote cuesheet \"{}\""
LAB_ACCURATERIP_CHECKSUM = u"checksum"
LAB_ACCURATERIP_RESULT = u"AccurateRip result"
LAB_ACCURATERIP_NOT_FOUND = u"disc not in database"
LAB_ACCURATERIP_FOUND = u"found"
LAB_ACCURATERIP_CONFIDENCE = u"confidence {:d}"
LAB_ACCURATERIP_MISMATCH = u"no match in database"
LAB_TOTAL_TRACKS = u"Total Tracks"
LAB_TOTAL_LENGTH = u"Total Length"
LAB_TRACK_LENGTH = u"{:d}:{:02d}"
LAB_TRACK_LENGTH_FRAMES = u"{:2d}:{:02d} ({:d} frames)"
LAB_FREEDB_ID = u"FreeDB disc ID"
LAB_MUSICBRAINZ_ID = u"MusicBrainz disc ID"
LAB_ACCURATERIP_ID = u"AccurateRip disc ID"
LAB_CDINFO_LENGTH = u"Length"
LAB_CDINFO_FRAMES = u"Frames"
LAB_CDINFO_OFFSET = u"Offset"
LAB_PLAY_BUTTON = u"play"
LAB_PAUSE_BUTTON = u"pause"
LAB_NEXT_BUTTON = u"next"
LAB_PREVIOUS_BUTTON = u"prev"
LAB_ADJUST_OUTPUT = u"output"
LAB_VOLUME = u"volume"
LAB_DECREASE_VOLUME = u" - volume down"
LAB_INCREASE_VOLUME = u" - volume up"
LAB_APPLY_BUTTON = u"apply"
LAB_QUIT_BUTTON = u"quit"
LAB_CANCEL_BUTTON = u"cancel"
LAB_BROWSE_BUTTON = u"browse"
LAB_FIELDS_BUTTON = u"fields"
LAB_PLAY_STATUS = u"{count:d} tracks, {min:d}:{sec:02d} minutes"
LAB_PLAY_STATUS_1 = u"{count:d} track, {min:d}:{sec:02d} minutes"
LAB_PLAY_TRACK = u"track"
LAB_CLOSE = u"close"
LAB_TRACK = u"track"
LAB_ALBUM_NUMBER = u"disc"
LAB_X_OF_Y = u"{:d} / {:d}"
LAB_TRACK_X_OF_Y = u"track {:2d} / {:d}"
LAB_CHOOSE_FILE = u"Choose an audio file"
LAB_CHOOSE_DIRECTORY = u"Choose directory"
LAB_ADD_FIELD = u"Add field"
LAB_COVERVIEW_ABOUT = \
u"A viewer for displaying images embedded in audio files."
LAB_AUDIOTOOLS_URL = u"http://audiotools.sourceforge.net"
LAB_BYTE_SIZE = u"{:d} bytes"
LAB_DIMENSIONS = u"{:d} \u00D7 {:d}"
LAB_BITS_PER_PIXEL = u"{:d} bits"
LAB_SELECT_BEST_MATCH = u"Select Best Match"
LAB_TRACK_METADATA = u"Track Metadata"
LAB_DVDAINFO_TITLE = u"Title"
LAB_DVDAINFO_TRACK = u"Track"
LAB_DVDAINFO_LENGTH = u"Length"
LAB_DVDAINFO_PTS_LENGTH = u"PTS"
LAB_DVDAINFO_FIRST_SECTOR = u"Start Sector"
LAB_DVDAINFO_LAST_SECTOR = u"End Sector"
LAB_DVDAINFO_CODEC = u"Codec"
LAB_DVDAINFO_SAMPLE_RATE = u"Rate"
LAB_DVDAINFO_CHANNELS = u"Ch."
LAB_DVDAINFO_BITS_PER_SAMPLE = u"BPS"
LAB_DVDA2TRACK_APPLY = u"extract tracks"
LAB_DVDA_TRACK = u"title {title_number:d} - track {track_number:d}"
LAB_CONVERTING_FILE = u"Converting audio file"
LAB_CACHING_FILE = u"Caching audio file"
LAB_TRACK2TRACK_APPLY = u"convert tracks"
LAB_TRACK2TRACK_APPLY_1 = u"convert track"
LAB_TRACK2TRACK_NEXT = u"Next Album"
LAB_TRACK2CD_CONVERTED = u"converted \"{}\" for CD burning"
LAB_TRACKCAT_INPUT = u"{:d} tracks"
LAB_TRACKCAT_APPLY = u"concatenate tracks"
LAB_TRACKCMP_CMP = u"{file1} <> {file2}"
LAB_TRACKCMP_OK = u"OK"
LAB_TRACKCMP_PARAM_MISMATCH = u"stream parameters differ"
LAB_TRACKCMP_MISMATCH = u"differ at PCM frame {:d}"
LAB_TRACKCMP_TYPE_MISMATCH = u"must be either files or directories"
LAB_TRACKCMP_ERROR = u"error"
LAB_TRACKCMP_MISSING = u"\"{filename}\" missing from \"{directory}\""
LAB_TRACKCMP_RESULTS = u"Results:"
LAB_TRACKCMP_HEADER_SUCCESS = u"success"
LAB_TRACKCMP_HEADER_FAILURE = u"failure"
LAB_TRACKCMP_HEADER_TOTAL = u"total"
LAB_TRACKINFO_BITRATE = u"{bitrate:4d} kbps: {filename}"
LAB_TRACKINFO_PERCENTAGE = u"{percentage:.0%}: {filename}"
LAB_TRACKINFO_ATTRIBS = \
u"{minutes:2d}:{seconds:02d} " + \
u"{channels:d}ch {rate} {bits:d}-bit: {filename}"
LAB_TRACKINFO_REPLAYGAIN = u"ReplayGain:"
LAB_TRACKINFO_TRACK_GAIN = u"track gain"
LAB_TRACKINFO_TRACK_PEAK = u"track peak"
LAB_TRACKINFO_ALBUM_GAIN = u"album gain"
LAB_TRACKINFO_ALBUM_PEAK = u"album peak"
LAB_TRACKINFO_CUESHEET = u"Cuesheet:"
LAB_TRACKINFO_CUESHEET_TRACK = u" #"
LAB_TRACKINFO_CUESHEET_INDEX = u"index {:02d}"
LAB_TRACKINFO_CUESHEET_LENGTH = u"length"
LAB_TRACKINFO_CUESHEET_ISRC = u"ISRC"
LAB_TRACKINFO_CHANNELS = u"Assigned Channels:"
LAB_TRACKINFO_CHANNEL = u"channel {channel_number:d} - {channel_name}"
LAB_TRACKINFO_UNDEFINED = u"undefined"
LAB_TRACKLENGTH = u"{hours:d}:{minutes:02d}:{seconds:02d}"
LAB_TRACKLENGTH_FILE_FORMAT = u"format"
LAB_TRACKLENGTH_FILE_COUNT = u"count"
LAB_TRACKLENGTH_FILE_LENGTH = u"length"
LAB_TRACKLENGTH_FILE_SIZE = u"size"
LAB_TRACKLENGTH_FILE_TOTAL = u"total"
LAB_TRACKLINT_MESSAGE = u"* {filename}: {message}"
LAB_TRACKRENAME_RENAME = u"rename files"
LAB_TRACKSPLIT_APPLY = u"split track"
LAB_TRACKVERIFY_RESULTS = u"Results:"
LAB_TRACKVERIFY_RESULT_FORMAT = u"format"
LAB_TRACKVERIFY_RESULT_SUCCESS = u"success"
LAB_TRACKVERIFY_RESULT_FAILURE = u"failure"
LAB_TRACKVERIFY_RESULT_TOTAL = u"total"
LAB_TRACKVERIFY_ACCURATERIP_MATCH = u"match"
LAB_TRACKVERIFY_ACCURATERIP_MISMATCH = u"track not found"
LAB_TRACKVERIFY_ACCURATERIP_NOTFOUND = u"disc not found"
LAB_TRACKVERIFY_ACCURATERIP_ERROR = u"error"
LAB_TRACKVERIFY_RESULT = u"{path} : {result}"
LAB_TRACKVERIFY_SUMMARY = u"summary"
LAB_TRACKVERIFY_OK = u"OK"
LAB_TRACKVERIFY_AR_VERSION1 = u"AccurateRip V1"
LAB_TRACKVERIFY_AR_VERSION2 = u"AccurateRip V2"
LAB_TRACKVERIFY_AR_TRACK = u"Track"
LAB_TRACKVERIFY_AR_CHECKSUM = u"Checksum"
LAB_TRACKVERIFY_AR_OFFSET = u"Offset"
LAB_TRACKVERIFY_AR_CONFIDENCE = u"Confidence"
LAB_TRACKVERIFY_AR_CONF = u"Conf."
LAB_TRACKTAG_UPDATING = u"updating tracks"
LAB_TRACKTAG_APPLY = u"Apply"
LAB_KEY_NEXT = u" - next {}"
LAB_KEY_PREVIOUS = u" - previous {}"
LAB_KEY_SELECT = u" - select"
LAB_KEY_TOGGLE_OPEN = u" - toggle open"
LAB_KEY_CANCEL = u" - cancel"
LAB_KEY_CLEAR_FORMAT = u" - clear format"
LAB_KEY_DONE = u" - done"
LAB_TRACKTAG_UPDATE_TRACK_NAME = u"the name of the track"
LAB_TRACKTAG_UPDATE_ARTIST_NAME = u"the name of the artist"
LAB_TRACKTAG_UPDATE_PERFORMER_NAME = u"the name of the performer"
LAB_TRACKTAG_UPDATE_COMPOSER_NAME = u"the name of the composer"
LAB_TRACKTAG_UPDATE_CONDUCTOR_NAME = u"the name of the conductor"
LAB_TRACKTAG_UPDATE_ALBUM_NAME = u"the name of the album"
LAB_TRACKTAG_UPDATE_CATALOG = u"the catalog number of the album"
LAB_TRACKTAG_UPDATE_TRACK_NUMBER = u"the number of the track in the album"
LAB_TRACKTAG_UPDATE_TRACK_TOTAL = \
u"the total number of tracks in the album"
LAB_TRACKTAG_UPDATE_ALBUM_NUMBER = \
u"the number of the album in a set of albums"
LAB_TRACKTAG_UPDATE_ALBUM_TOTAL = \
u"the total number of albums in a set of albums"
LAB_TRACKTAG_UPDATE_ISRC = u"the ISRC of the track"
LAB_TRACKTAG_UPDATE_PUBLISHER = u"the publisher of the album"
LAB_TRACKTAG_UPDATE_MEDIA = u"the media type of the album, such as \"CD\""
LAB_TRACKTAG_UPDATE_YEAR = u"the year of release"
LAB_TRACKTAG_UPDATE_DATE = u"the date of recording"
LAB_TRACKTAG_UPDATE_COPYRIGHT = u"copyright information"
LAB_TRACKTAG_UPDATE_COMMENT = u"a text comment"
LAB_TRACKTAG_UPDATE_COMPILATION = u"whether the track is part of a compilation"
LAB_TRACKTAG_REMOVE_TRACK_NAME = u"remove track name"
LAB_TRACKTAG_REMOVE_ARTIST_NAME = u"remove track artist"
LAB_TRACKTAG_REMOVE_PERFORMER_NAME = u"remove track performer"
LAB_TRACKTAG_REMOVE_COMPOSER_NAME = u"remove track composer"
LAB_TRACKTAG_REMOVE_CONDUCTOR_NAME = u"remove track conductor"
LAB_TRACKTAG_REMOVE_ALBUM_NAME = u"remove album name"
LAB_TRACKTAG_REMOVE_CATALOG = u"remove catalog number"
LAB_TRACKTAG_REMOVE_TRACK_NUMBER = u"remove track number"
LAB_TRACKTAG_REMOVE_TRACK_TOTAL = u"remove total number of tracks"
LAB_TRACKTAG_REMOVE_ALBUM_NUMBER = u"remove album number"
LAB_TRACKTAG_REMOVE_ALBUM_TOTAL = u"remove total number of albums"
LAB_TRACKTAG_REMOVE_ISRC = u"remove ISRC"
LAB_TRACKTAG_REMOVE_PUBLISHER = u"remove publisher"
LAB_TRACKTAG_REMOVE_MEDIA = u"remove album's media type"
LAB_TRACKTAG_REMOVE_YEAR = u"remove release year"
LAB_TRACKTAG_REMOVE_DATE = u"remove recording date"
LAB_TRACKTAG_REMOVE_COPYRIGHT = u"remove copyright information"
LAB_TRACKTAG_REMOVE_COMMENT = u"remove text comment"
LAB_TRACKTAG_REMOVE_COMPILATION = u"remove compilation status"
LAB_AT_CONFIG_CD_BURNING = u"CD Burning via track2cd"
LAB_AT_CONFIG_WITHOUT_CUE = u"without cue"
LAB_AT_CONFIG_WITH_CUE = u"with cue"
LAB_AT_CONFIG_YES = u"yes"
LAB_AT_CONFIG_NO = u"no"
LAB_AT_CONFIG_SYS_CONFIG = u"System configuration:"
LAB_AT_CONFIG_USE_MUSICBRAINZ = u"Use MusicBrainz service"
LAB_AT_CONFIG_MUSICBRAINZ_SERVER = u"Default MusicBrainz server"
LAB_AT_CONFIG_MUSICBRAINZ_PORT = u"Default MusicBrainz port"
LAB_AT_CONFIG_USE_FREEDB = u"Use FreeDB service"
LAB_AT_CONFIG_FREEDB_SERVER = u"Default FreeDB server"
LAB_AT_CONFIG_FREEDB_PORT = u"Default FreeDB port"
LAB_AT_CONFIG_DEFAULT_CDROM = u"Default CD-ROM device"
LAB_AT_CONFIG_CDROM_READ_OFFSET = u"CD-ROM sample read offset"
LAB_AT_CONFIG_CDROM_WRITE_OFFSET = u"CD-ROM sample write offset"
LAB_AT_CONFIG_JOBS = u"Default simultaneous jobs"
LAB_AT_CONFIG_VERBOSITY = u"Default verbosity level"
LAB_AT_CONFIG_AUDIO_OUTPUT = u"Audio output"
LAB_AT_CONFIG_FS_ENCODING = u"Filesystem text encoding"
LAB_AT_CONFIG_IO_ENCODING = u"TTY text encoding"
LAB_AT_CONFIG_ID3V2_VERSION = u"ID3v2 tag version"
LAB_AT_CONFIG_ID3V2_ID3V22 = u"ID3v2.2"
LAB_AT_CONFIG_ID3V2_ID3V23 = u"ID3v2.3"
LAB_AT_CONFIG_ID3V2_ID3V24 = u"ID3v2.4"
LAB_AT_CONFIG_ID3V2_NONE = u"no ID3v2 tags"
LAB_AT_CONFIG_ID3V2_PADDING = u"ID3v2 digit padding"
LAB_AT_CONFIG_ID3V2_PADDING_YES = u"padded (\"01\", \"02\", \u2026)"
LAB_AT_CONFIG_ID3V2_PADDING_NO = u"not padded (\"1\", \"2\", \u2026)"
LAB_AT_CONFIG_ID3V1_VERSION = u"ID3v1 tag version"
LAB_AT_CONFIG_ID3V1_ID3V11 = u"ID3v1.1"
LAB_AT_CONFIG_ID3V1_NONE = u"no ID3v1 tags"
LAB_AT_CONFIG_ADD_REPLAY_GAIN = u"Add ReplayGain by default"
LAB_AT_CONFIG_FILE_WRITTEN = u"* \"{}\" written"
LAB_AT_CONFIG_FOUND = u"found"
LAB_AT_CONFIG_NOT_FOUND = u"not found"
LAB_AT_CONFIG_TYPE = u" type "
LAB_AT_CONFIG_BINARIES = u"Binaries"
LAB_AT_CONFIG_QUALITY = u" quality "
LAB_AT_CONFIG_REPLAY_GAIN = u" ReplayGain "
LAB_AT_CONFIG_DEFAULT = u"Default"
LAB_AT_CONFIG_TYPE = u"Type"
LAB_AT_CONFIG_DEFAULT_QUALITY = u"Default Quality"
LAB_OUTPUT_OPTIONS = u"Output Options"
LAB_OPTIONS_OUTPUT = u"Output"
LAB_OPTIONS_OUTPUT_DIRECTORY = u"Dir"
LAB_OPTIONS_FILENAME_FORMAT = u"Format"
LAB_OPTIONS_FILENAME_FORMAT_EXAMPLE = u"Example"
LAB_OPTIONS_AUDIO_CLASS = u"Type"
LAB_OPTIONS_AUDIO_QUALITY = u"Quality"
LAB_OPTIONS_OUTPUT_FILES = u"Output Files"
LAB_OPTIONS_OUTPUT_FILES_1 = u"Output File"
# Compression settings
COMP_FLAC_0 = u"least compresson, fastest compression speed"
COMP_FLAC_8 = u"most compression, slowest compression speed"
COMP_NERO_LOW = u"lowest quality, corresponds to neroAacEnc -q 0.4"
COMP_NERO_HIGH = u"highest quality, corresponds to neroAacEnc -q 1"
COMP_LAME_0 = u"high quality, larger files, corresponds to lame's -V0"
COMP_LAME_6 = u"lower quality, smaller files, corresponds to lame's -V6"
COMP_LAME_MEDIUM = u"corresponds to lame's --preset medium"
COMP_LAME_STANDARD = u"corresponds to lame's --preset standard"
COMP_LAME_EXTREME = u"corresponds to lame's --preset extreme"
COMP_LAME_INSANE = u"corresponds to lame's --preset insane"
COMP_TWOLAME_64 = u"total bitrate of 64kbps"
COMP_TWOLAME_384 = u"total bitrate of 384kbps"
COMP_VORBIS_0 = u"very low quality, corresponds to oggenc -q 0"
COMP_VORBIS_10 = u"very high quality, corresponds to oggenc -q 10"
COMP_WAVPACK_FAST = u"fastest encode/decode, worst compression"
COMP_WAVPACK_VERYHIGH = u"slowest encode/decode, best compression"
COMP_SPEEX_0 = u"corresponds to speexenc --quality 0"
COMP_SPEEX_10 = u"corresponds to speexenc --quality 10"
# Errors
ERR_1_FILE_REQUIRED = u"you must specify exactly 1 supported audio file"
ERR_FILES_REQUIRED = u"you must specify at least 1 supported audio file"
ERR_UNSUPPORTED_CHANNEL_MASK = \
u"unable to write \"{target_filename}\" " + \
u"with channel assignment \"{assignment}\""
ERR_UNSUPPORTED_BITS_PER_SAMPLE = \
u"unable to write \"{target_filename}\" " + \
u"with {bps:d} bits per sample"
ERR_UNSUPPORTED_CHANNEL_COUNT = \
u"unable to write \"{target_filename}\" " + \
u"with {channels:d} channel input"
ERR_DUPLICATE_FILE = u"file \"{}\" included more than once"
ERR_OUTPUT_IS_INPUT = u"\"{}\" cannot be both input and output file"
ERR_OPEN_IOERROR = u"unable to open \"{}\""
ERR_ENCODING_ERROR = u"unable to write \"{}\""
ERR_READ_ERROR = u"read error"
ERR_UNSUPPORTED_AUDIO_TYPE = u"unsupported audio type \"{}\""
ERR_UNSUPPORTED_FILE = u"unsupported file '{}'"
ERR_UNSUPPORTED_TO_PCM = \
u"\"{filename}\": unable to read file type \"{type}\""
ERR_UNSUPPORTED_FROM_PCM = \
u"unable to encode to file type \"{}\""
ERR_INVALID_FILE = u"invalid file '{}'"
ERR_INVALID_SAMPLE_RATE = u"invalid sample rate"
ERR_INVALID_CHANNEL_COUNT = u"invalid channel count"
ERR_INVALID_BITS_PER_SAMPLE = u"invalid bits-per-sample"
ERR_TOTAL_PCM_FRAMES_MISMATCH = u"total_pcm_frames mismatch"
ERR_AMBIGUOUS_AUDIO_TYPE = u"ambiguous suffix type \"{}\""
ERR_CHANNEL_COUNT_MASK_MISMATCH = u"channel count and channel mask mismatch"
ERR_NO_PCMREADERS = u"you must have at least 1 PCMReader"
ERR_PICTURES_UNSUPPORTED = u"this MetaData type does not support images"
ERR_UNKNOWN_FIELD = u"unknown field \"{}\" in file format"
ERR_INVALID_FILENAME_FORMAT = u"invalid filename format string"
ERR_FOREIGN_METADATA = u"metadata not from audio file"
ERR_NEGATIVE_SEEK = u"cannot seek to negative value"
ERR_AIFF_NOT_AIFF = u"not an AIFF file"
ERR_AIFF_INVALID_AIFF = u"invalid AIFF file"
ERR_AIFF_INVALID_CHUNK_ID = u"invalid AIFF chunk ID"
ERR_AIFF_INVALID_CHUNK = u"invalid AIFF chunk"
ERR_AIFF_MULTIPLE_COMM_CHUNKS = u"multiple COMM chunks found"
ERR_AIFF_PREMATURE_SSND_CHUNK = u"SSND chunk found before fmt"
ERR_AIFF_MULTIPLE_SSND_CHUNKS = u"multiple SSND chunks found"
ERR_AIFF_NO_COMM_CHUNK = u"COMM chunk not found"
ERR_AIFF_NO_SSND_CHUNK = u"SSND chunk not found"
ERR_AIFF_HEADER_EXTRA_SSND = u"extra data after SSND chunk header"
ERR_AIFF_HEADER_MISSING_SSND = u"missing data in SSND chunk header"
ERR_AIFF_HEADER_IOERROR = u"I/O error reading header data"
ERR_AIFF_FOOTER_IOERROR = u"I/O error reading footer data"
ERR_AIFF_TRUNCATED_SSND_CHUNK = u"premature end of SSND chunk"
ERR_AIFF_INVALID_SIZE = u"total aiff file size mismatch"
ERR_APE_INVALID_HEADER = u"invalid Monkey's Audio header"
ERR_AU_INVALID_HEADER = u"invalid Sun AU header"
ERR_AU_UNSUPPORTED_FORMAT = u"unsupported Sun AU format"
ERR_AU_TRUNCATED_DATA = u"truncated data block"
ERR_CUE_SYNTAX_ERROR = u"syntax error at line {:d}"
ERR_CUE_IOERROR = u"unable to read cuesheet"
ERR_CUE_INVALID_FORMAT = u"cuesheet not formatted for disc images"
ERR_CUE_INSUFFICIENT_TRACKS = u"insufficient tracks in cuesheet"
ERR_CUE_LENGTH_MISMATCH = \
u"cuesheet track length mismatch in track {:d}"
ERR_DVDA_IOERROR_AUDIO_TS = u"unable to open AUDIO_TS.IFO"
ERR_DVDA_INVALID_TITLE = u"invalid title"
ERR_DVDA_INVALID_TRACK = u"invalid track"
ERR_DVDA_INVALID_AUDIO_TS = u"invalid AUDIO_TS.IFO"
ERR_DVDA_INVALID_SECTOR_POINTER = u"invalid sector pointer"
ERR_DVDA_NO_TRACK_SECTOR = u"unable to find track sector in AOB files"
ERR_DVDA_INVALID_AOB_SYNC = u"invalid AOB sync bytes"
ERR_DVDA_INVALID_AOB_MARKER = u"invalid AOB marker bits"
ERR_DVDA_INVALID_AOB_START = u"invalid AOB packet start code"
ERR_FLAC_RESERVED_BLOCK = u"reserved metadata block type {:d}"
ERR_FLAC_INVALID_BLOCK = u"invalid metadata block type"
ERR_FLAC_INVALID_FILE = u"Invalid FLAC file"
ERR_OGG_INVALID_MAGIC_NUMBER = u"invalid Ogg magic number"
ERR_OGG_INVALID_VERSION = u"invalid Ogg version"
ERR_OGG_CHECKSUM_MISMATCH = u"Ogg page checksum mismatch"
ERR_OGGFLAC_INVALID_PACKET_BYTE = u"invalid packet byte"
ERR_OGGFLAC_INVALID_OGG_SIGNATURE = u"invalid Ogg signature"
ERR_OGGFLAC_INVALID_MAJOR_VERSION = u"invalid major version"
ERR_OGGFLAC_INVALID_MINOR_VERSION = u"invalid minor version"
ERR_OGGFLAC_VALID_FLAC_SIGNATURE = u"invalid FLAC signature"
ERR_IMAGE_UNKNOWN_TYPE = u"unknown image type"
ERR_IMAGE_INVALID_JPEG_MARKER = u"invalid JPEG segment marker"
ERR_IMAGE_IOERROR_JPEG = "I/O error reading JPEG data"
ERR_IMAGE_INVALID_PNG = u"invalid PNG"
ERR_IMAGE_IOERROR_PNG = "I/O error reading PNG data"
ERR_IMAGE_INVALID_PLTE = u"invalid PLTE chunk length"
ERR_IMAGE_INVALID_BMP = u"invalid BMP"
ERR_IMAGE_IOERROR_BMP = "I/O error reading BMP data"
ERR_IMAGE_INVALID_TIFF = u"invalid TIFF"
ERR_IMAGE_IOERROR_TIFF = u"I/O error reading TIFF data"
ERR_IMAGE_INVALID_GIF = u"invalid GIF"
ERR_IMAGE_IOERROR_GIF = u"I/O error reading GIF data"
ERR_M4A_IOERROR = u"I/O error opening M4A file"
ERR_M4A_MISSING_MDIA = u"required mdia atom not found"
ERR_M4A_MISSING_STSD = u"required stsd atom not found"
ERR_M4A_INVALID_MP4A = u"invalid mp4a atom"
ERR_M4A_MISSING_MDHD = u"required mdhd atom not found"
ERR_M4A_UNSUPPORTED_MDHD = u"unsupported mdhd version"
ERR_M4A_INVALID_MDHD = u"invalid mdhd atom"
ERR_M4A_INVALID_LEAF_ATOMS = u"leaf atoms must be a list"
ERR_ALAC_IOERROR = u"I/O error opening ALAC file"
ERR_ALAC_INVALID_ALAC = u"invalid alac atom"
ERR_MP3_FRAME_NOT_FOUND = u"MP3 frame not found"
ERR_MP3_INVALID_SAMPLE_RATE = u"invalid sample rate"
ERR_MP3_INVALID_BIT_RATE = u"invalid bit rate"
ERR_TOC_NO_HEADER = u"no CD_DA TOC header found"
ERR_TTA_INVALID_SIGNATURE = u"invalid TTA signature"
ERR_TTA_INVALID_FORMAT = u"unsupported TTA format"
ERR_VORBIS_INVALID_TYPE = u"invalid Vorbis type"
ERR_VORBIS_INVALID_HEADER = u"invalid Vorbis header"
ERR_VORBIS_INVALID_VERSION = u"invalid Vorbis version"
ERR_VORBIS_INVALID_FRAMING_BIT = u"invalid framing bit"
ERR_OPUS_INVALID_TYPE = u"invalid Opus header"
ERR_OPUS_INVALID_VERSION = u"invalid Opus version"
ERR_OPUS_INVALID_CHANNELS = u"invalid Open channel count"
ERR_WAV_NOT_WAVE = u"not a RIFF WAVE file"
ERR_WAV_INVALID_WAVE = u"invalid RIFF WAVE file"
ERR_WAV_NO_DATA_CHUNK = u"data chunk not found"
ERR_WAV_INVALID_CHUNK = u"invalid RIFF WAVE chunk ID"
ERR_WAV_MULTIPLE_FMT = u"multiple fmt chunks found"
ERR_WAV_PREMATURE_DATA = u"data chunk found before fmt"
ERR_WAV_MULTIPLE_DATA = u"multiple data chunks found"
ERR_WAV_NO_FMT_CHUNK = u"fmt chunk not found"
ERR_WAV_HEADER_EXTRA_DATA = u"{:d} bytes found after data chunk header"
ERR_WAV_HEADER_IOERROR = u"I/O error reading header data"
ERR_WAV_FOOTER_IOERROR = u"I/O error reading footer data"
ERR_WAV_TRUNCATED_DATA_CHUNK = u"premature end of data chunk"
ERR_WAV_INVALID_SIZE = u"total wave file size mismatch"
ERR_WAVPACK_INVALID_HEADER = u"WavPack header ID invalid"
ERR_WAVPACK_UNSUPPORTED_FMT = u"unsupported FMT compression"
ERR_WAVPACK_INVALID_FMT = u"invalid FMT chunk"
ERR_WAVPACK_NO_FMT = u"FMT chunk not found in WavPack"
ERR_MPC_INVALID_ID = u"invalid Musepack stream ID"
ERR_MPC_INVALID_VERSION = u"invalid Musepack version"
ERR_NO_COMPRESSION_MODES = u"Audio type \"{}\" has no quality modes"
ERR_UNSUPPORTED_COMPRESSION_MODE = \
u"\"{quality}\" is not a supported compression mode " + \
u"for type \"{type}\""
ERR_INVALID_CDDA = u". Is that an audio cd?"
ERR_NO_CDDA = u"no CD in drive"
ERR_NO_EMPTY_CDDA = u"no audio tracks found on CD"
ERR_NO_OUTPUT_FILE = u"you must specify an output file"
ERR_DUPLICATE_OUTPUT_FILE = u"output file \"{}\" occurs more than once"
ERR_URWID_REQUIRED = u"Urwid 1.0 or better is required for interactive mode"
ERR_GET_URWID1 = \
u"Please download and install urwid from http://excess.org/urwid/"
ERR_GET_URWID2 = u"or your system's package manager."
ERR_TERMIOS_ERROR = u"unable to get tty settings"
ERR_TERMIOS_SUGGESTION = \
u"if piping arguments via xargs(1), try:"
ERR_NO_GUI = u"neither PyGTK nor Tkinter is available"
ERR_NO_AUDIO_TS = \
u"you must specify the DVD-Audio's AUDIO_TS directory with -A"
ERR_INVALID_TITLE_NUMBER = u"title number must be greater than 0"
ERR_INVALID_JOINT = u"you must run at least 1 process at a time"
ERR_NO_CDRDAO = u"unable to find \"cdrdao\" executable"
ERR_GET_CDRDAO = u"please install \"cdrdao\" to burn CDs"
ERR_NO_CDRECORD = u"unable to find \"cdrecord\" executable"
ERR_GET_CDRECORD = u"please install \"cdrecord\" to burn CDs"
ERR_SAMPLE_RATE_MISMATCH = u"all audio files must have the same sample rate"
ERR_CHANNEL_COUNT_MISMATCH = \
u"all audio files must have the same channel count"
ERR_CHANNEL_MASK_MISMATCH = \
u"all audio files must have the same channel assignment"
ERR_BPS_MISMATCH = u"all audio files must have the same bits per sample"
ERR_TRACK2CD_INVALIDFILE = u"not all files are valid. Unable to write CD"
ERR_TRACK2TRACK_O_AND_D = u"-o and -d options are not compatible"
ERR_TRACK2TRACK_O_AND_D_SUGGESTION = \
u"please specify either -o or -d but not both"
ERR_TRACK2TRACK_O_AND_FORMAT = u"--format has no effect when used with -o"
ERR_TRACK2TRACK_O_AND_MULTIPLE = \
u"you may specify only 1 input file for use with -o"
ERR_TRACKCMP_TYPE_MISMATCH = u"both files to be compared must be audio files"
ERR_TRACKSPLIT_NO_CUESHEET = u"you must specify a cuesheet to split audio file"
ERR_TRACKSPLIT_OVERLONG_CUESHEET = u"cuesheet too long for track being split"
ERR_TRACKVERIFY = u"not from a CD"
ERR_RENAME = u"unable to rename \"{source}\" to \"{target}\""
ERR_TRACKTAG_COMMENT_NOT_UTF8 = \
u"comment file \"{}\" does not appear to be UTF-8 text"
ERR_TRACKTAG_COMMENT_IOERROR = u"unable to open comment file \"{}\""
ERR_OUTPUT_DUPLICATE_NAME = u"all output tracks must have different names"
ERR_OUTPUT_OUTPUTS_ARE_INPUT = \
u"output tracks must have different names than input tracks"
ERR_OUTPUT_INVALID_FORMAT = u"output tracks must have valid format string"
ERR_CANCELLED = u"cancelled"
ERR_TOO_MANY_CUESHEET_FILES = u"too many files for cuesheet"
# Cleaning messages
CLEAN_REMOVE_DUPLICATE_TAG = u"removed duplicate tag {}"
CLEAN_REMOVE_TRAILING_WHITESPACE = \
u"removed trailing whitespace from {}"
CLEAN_REMOVE_LEADING_WHITESPACE = u"removed leading whitespace from {}"
CLEAN_REMOVE_LEADING_WHITESPACE_ZEROES = \
u"removed leading whitespace/zeroes from {}"
CLEAN_REMOVE_LEADING_ZEROES = u"removed leading zeroes from {}"
CLEAN_REMOVE_DUPLICATE_ID3V2 = u"remove duplicate ID3v2 tag"
CLEAN_ADD_LEADING_ZEROES = u"added leading zeroes to {}"
CLEAN_REMOVE_EMPTY_TAG = u"removed empty field {}"
CLEAN_FIX_TAG_FORMATTING = u"fixed formatting for {}"
CLEAN_FIX_IMAGE_FIELDS = u"fixed embedded image metadata fields"
CLEAN_AIFF_MULTIPLE_COMM_CHUNKS = u"removed duplicate COMM chunk"
CLEAN_AIFF_REORDERED_SSND_CHUNK = u"moved COMM chunk after SSND chunk"
CLEAN_AIFF_MULTIPLE_SSND_CHUNKS = u"removed duplicate SSND chunk"
CLEAN_FLAC_REORDERED_STREAMINFO = u"moved STREAMINFO to first block"
CLEAN_FLAC_MULITPLE_STREAMINFO = u"removed redundant STREAMINFO block"
CLEAN_FLAC_MULTIPLE_VORBISCOMMENT = u"removed redundant VORBIS_COMMENT block"
CLEAN_FLAC_MULTIPLE_SEEKTABLE = u"removed redundant SEEKTABLE block"
CLEAN_FLAC_MULTIPLE_CUESHEET = u"removed redundant CUESHEET block"
CLEAN_FLAC_UNDEFINED_BLOCK = u"removed undefined block"
CLEAN_FLAC_REMOVE_SEEKPOINTS = u"removed empty seekpoints from seektable"
CLEAN_FLAC_REORDER_SEEKPOINTS = u"reordered seektable to be in ascending order"
CLEAN_FLAC_REMOVE_ID3V2 = u"removed ID3v2 tag"
CLEAN_FLAC_REMOVE_ID3V1 = u"removed ID3v1 tag"
CLEAN_FLAC_POPULATE_MD5 = u"populated empty MD5SUM"
CLEAN_FLAC_ADD_CHANNELMASK = u"added WAVEFORMATEXTENSIBLE_CHANNEL_MASK"
CLEAN_FLAC_FIX_SEEKTABLE = u"fixed invalid SEEKTABLE"
CLEAN_FLAC_ADD_SEEKTABLE = u"added SEEKTABLE"
CLEAN_WAV_MULTIPLE_FMT_CHUNKS = u"removed duplicate fmt chunk"
CLEAN_WAV_REORDERED_DATA_CHUNK = u"moved data chunk after fmt chunk"
CLEAN_WAV_MULTIPLE_DATA_CHUNKS = u"removed multiple data chunk"
# Channel names
MASK_FRONT_LEFT = u"front left"
MASK_FRONT_RIGHT = u"front right"
MASK_FRONT_CENTER = u"front center"
MASK_LFE = u"low frequency"
MASK_BACK_LEFT = u"back left"
MASK_BACK_RIGHT = u"back right"
MASK_FRONT_RIGHT_OF_CENTER = u"front right of center"
MASK_FRONT_LEFT_OF_CENTER = u"front left of center"
MASK_BACK_CENTER = u"back center"
MASK_SIDE_LEFT = u"side left"
MASK_SIDE_RIGHT = u"side right"
MASK_TOP_CENTER = u"top center"
MASK_TOP_FRONT_LEFT = u"top front left"
MASK_TOP_FRONT_CENTER = u"top front center"
MASK_TOP_FRONT_RIGHT = u"top front right"
MASK_TOP_BACK_LEFT = u"top back left"
MASK_TOP_BACK_CENTER = u"top back center"
MASK_TOP_BACK_RIGHT = u"top back right"
|
tuffy/python-audio-tools
|
audiotools/text.py
|
Python
|
gpl-2.0
| 33,671
|
[
"Brian"
] |
17f1846f6bdb46a3bdbbb769a4945bd2fe797c856d0e177c13c8cdc3eef6ae3e
|
#! /usr/bin/env python
"""Print names of all methods defined in module
This script demonstrates use of the visitor interface of the compiler
package.
"""
import compiler
class MethodFinder:
"""Print the names of all the methods
Each visit method takes two arguments, the node and its current
scope. The scope is the name of the current class or None.
"""
def visitClass(self, node, scope=None):
self.visit(node.code, node.name)
def visitFunction(self, node, scope=None):
if scope is not None:
print "%s.%s" % (scope, node.name)
self.visit(node.code, None)
def main(files):
mf = MethodFinder()
for file in files:
f = open(file)
buf = f.read()
f.close()
ast = compiler.parse(buf)
compiler.walk(ast, mf)
if __name__ == "__main__":
import sys
main(sys.argv[1:])
|
kidmaple/CoolWall
|
user/python/Tools/compiler/demo.py
|
Python
|
gpl-2.0
| 905
|
[
"VisIt"
] |
2bcded20bf1037866cebbf1bb06d3e1ea09a4b30d10a10395fa954cf15072f4a
|
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'gui.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from .icons_rc import *
class Ui_AboutDialog(object):
def setupUi(self, AboutDialog):
if not AboutDialog.objectName():
AboutDialog.setObjectName(u"AboutDialog")
AboutDialog.resize(462, 367)
icon = QIcon()
icon.addFile(u":/Icons/icons/GridCal_icon.svg", QSize(), QIcon.Normal, QIcon.Off)
AboutDialog.setWindowIcon(icon)
self.verticalLayout_2 = QVBoxLayout(AboutDialog)
self.verticalLayout_2.setObjectName(u"verticalLayout_2")
self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
self.tabWidget = QTabWidget(AboutDialog)
self.tabWidget.setObjectName(u"tabWidget")
self.tab = QWidget()
self.tab.setObjectName(u"tab")
self.gridLayout = QGridLayout(self.tab)
self.gridLayout.setObjectName(u"gridLayout")
self.mainLabel = QLabel(self.tab)
self.mainLabel.setObjectName(u"mainLabel")
self.mainLabel.setLayoutDirection(Qt.LeftToRight)
self.mainLabel.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignTop)
self.mainLabel.setWordWrap(True)
self.mainLabel.setOpenExternalLinks(True)
self.mainLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)
self.gridLayout.addWidget(self.mainLabel, 0, 1, 2, 2)
self.verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
self.gridLayout.addItem(self.verticalSpacer, 1, 0, 1, 1)
self.label = QLabel(self.tab)
self.label.setObjectName(u"label")
self.label.setMinimumSize(QSize(48, 48))
self.label.setMaximumSize(QSize(48, 48))
self.label.setPixmap(QPixmap(u":/Icons/icons/GridCal_icon.svg"))
self.label.setScaledContents(True)
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.versionLabel = QLabel(self.tab)
self.versionLabel.setObjectName(u"versionLabel")
self.versionLabel.setOpenExternalLinks(True)
self.versionLabel.setTextInteractionFlags(Qt.LinksAccessibleByMouse|Qt.TextSelectableByMouse)
self.gridLayout.addWidget(self.versionLabel, 3, 1, 1, 1)
self.copyrightLabel = QLabel(self.tab)
self.copyrightLabel.setObjectName(u"copyrightLabel")
self.copyrightLabel.setOpenExternalLinks(True)
self.copyrightLabel.setTextInteractionFlags(Qt.LinksAccessibleByMouse|Qt.TextSelectableByMouse)
self.gridLayout.addWidget(self.copyrightLabel, 4, 1, 1, 1)
self.tabWidget.addTab(self.tab, "")
self.tab_2 = QWidget()
self.tab_2.setObjectName(u"tab_2")
self.verticalLayout = QVBoxLayout(self.tab_2)
self.verticalLayout.setObjectName(u"verticalLayout")
self.contributorsLabel = QLabel(self.tab_2)
self.contributorsLabel.setObjectName(u"contributorsLabel")
self.contributorsLabel.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignTop)
self.verticalLayout.addWidget(self.contributorsLabel)
self.tabWidget.addTab(self.tab_2, "")
self.tab_3 = QWidget()
self.tab_3.setObjectName(u"tab_3")
self.gridLayout_2 = QGridLayout(self.tab_3)
self.gridLayout_2.setObjectName(u"gridLayout_2")
self.updateLabel = QLabel(self.tab_3)
self.updateLabel.setObjectName(u"updateLabel")
self.updateLabel.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignVCenter)
self.updateLabel.setWordWrap(True)
self.updateLabel.setTextInteractionFlags(Qt.LinksAccessibleByMouse|Qt.TextSelectableByMouse)
self.gridLayout_2.addWidget(self.updateLabel, 0, 1, 1, 1)
self.updateButton = QPushButton(self.tab_3)
self.updateButton.setObjectName(u"updateButton")
self.updateButton.setMaximumSize(QSize(80, 16777215))
self.gridLayout_2.addWidget(self.updateButton, 0, 0, 1, 1)
self.verticalSpacer_2 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
self.gridLayout_2.addItem(self.verticalSpacer_2, 1, 0, 1, 1)
self.tabWidget.addTab(self.tab_3, "")
self.tab_4 = QWidget()
self.tab_4.setObjectName(u"tab_4")
self.verticalLayout_3 = QVBoxLayout(self.tab_4)
self.verticalLayout_3.setObjectName(u"verticalLayout_3")
self.licenseTextEdit = QTextEdit(self.tab_4)
self.licenseTextEdit.setObjectName(u"licenseTextEdit")
self.verticalLayout_3.addWidget(self.licenseTextEdit)
self.tabWidget.addTab(self.tab_4, "")
self.verticalLayout_2.addWidget(self.tabWidget)
self.retranslateUi(AboutDialog)
self.tabWidget.setCurrentIndex(0)
QMetaObject.connectSlotsByName(AboutDialog)
# setupUi
def retranslateUi(self, AboutDialog):
AboutDialog.setWindowTitle(QCoreApplication.translate("AboutDialog", u"About GridCal", None))
self.mainLabel.setText(QCoreApplication.translate("AboutDialog", u"<html><head/><body><p align=\"justify\"><span style=\" font-weight:600;\">GridCal</span> has been carefully crafted since 2015 to serve as a platform for research and consultancy. </p><p align=\"justify\">Visit <a href=\"https://gridcal.org\"><span style=\" text-decoration: underline; color:#0000ff;\">https://gridcal.org</span></a> for more details.</p><p align=\"justify\">This program comes with absolutelly no warranty. This is free software, and you are welcome to redistribute it under the conditions set by the license. GridCal is licensed under the GNU general public license version 3. See the license file for more details.</p><p align=\"justify\">The source of GridCal can be found at: <a href=\"https://github.com/SanPen/GridCal\"><span style=\" text-decoration: underline; color:#0000ff;\">https://github.com/SanPen/GridCal</span></a></p></body></html>", None))
self.label.setText("")
self.versionLabel.setText(QCoreApplication.translate("AboutDialog", u"version", None))
self.copyrightLabel.setText(QCoreApplication.translate("AboutDialog", u"Copyright", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QCoreApplication.translate("AboutDialog", u"About", None))
self.contributorsLabel.setText(QCoreApplication.translate("AboutDialog", u"TextLabel", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QCoreApplication.translate("AboutDialog", u"Contributors", None))
self.updateLabel.setText(QCoreApplication.translate("AboutDialog", u"TextLabel", None))
self.updateButton.setText(QCoreApplication.translate("AboutDialog", u"Update", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), QCoreApplication.translate("AboutDialog", u"Update", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), QCoreApplication.translate("AboutDialog", u"License", None))
# retranslateUi
|
SanPen/GridCal
|
src/GridCal/Gui/AboutDialogue/gui.py
|
Python
|
lgpl-3.0
| 7,302
|
[
"VisIt"
] |
f3792da821040782121ac854efcf1eed21569bf78b1dafcc54df968c6c4fe919
|
# ======================================================================================
# File : refresh_files.py
# Author : Wu Jie
# Last Change : 01/08/2010 | 18:20:03 PM | Friday,January
# Description :
# ======================================================================================
#/////////////////////////////////////////////////////////////////////////////
# refresh file by write it again with nothing changes
#/////////////////////////////////////////////////////////////////////////////
import sys, os
# ------------------------------------------------------------------
# Desc:
# ------------------------------------------------------------------
def main():
target = "."
if len(sys.argv) > 1:
target = sys.argv[1]
if os.path.isfile(target):
do_refresh(target)
else:
# walk through the path
for root, dirs, files in os.walk( target, topdown=True ):
# don't visit .git directories
if '.git' in dirs:
dirs.remove('.git')
# write files
for name in files:
full_filename = os.path.join( root, name )
do_refresh(full_filename)
# ------------------------------------------------------------------
# Desc:
# ------------------------------------------------------------------
def do_refresh( _filename ):
if os.path.isdir(_filename):
print _filename, "directory!"
return
data = open(_filename, "rb").read()
if '\0' in data:
print _filename, "binary!"
return
try:
f = open(_filename, "wb")
except IOError:
print _filename, "error to write!"
return
f.write(data)
f.close()
print _filename, "wrote!"
# ------------------------------------------------------------------
# Desc:
# ------------------------------------------------------------------
if __name__ == '__main__':
main()
|
exdev/exutility
|
all/bin/renew.py
|
Python
|
lgpl-3.0
| 1,968
|
[
"VisIt"
] |
afe4532751fd90a12c0f0d951fb90778059f1432d3eb22c5a8eff6a45a59d9de
|
"""
Copyright (c) 2014, Al Sweigart
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import contextlib
import ctypes
import os
import platform
import subprocess
import sys
import time
from ctypes import c_size_t, sizeof, c_wchar_p, get_errno, c_wchar
EXCEPT_MSG = """
Pyperclip could not find a copy/paste mechanism for your system.
For more information, please visit https://pyperclip.readthedocs.org """
PY2 = sys.version_info[0] == 2
text_type = unicode if PY2 else str
class PyperclipException(RuntimeError):
pass
class PyperclipWindowsException(PyperclipException):
def __init__(self, message):
message += " (%s)" % ctypes.WinError()
super(PyperclipWindowsException, self).__init__(message)
def init_osx_clipboard():
def copy_osx(text):
p = subprocess.Popen(['pbcopy', 'w'],
stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=text)
def paste_osx():
p = subprocess.Popen(['pbpaste', 'r'],
stdout=subprocess.PIPE, close_fds=True)
stdout, stderr = p.communicate()
return stdout.decode()
return copy_osx, paste_osx
def init_gtk_clipboard():
import gtk
def copy_gtk(text):
global cb
cb = gtk.Clipboard()
cb.set_text(text)
cb.store()
def paste_gtk():
clipboardContents = gtk.Clipboard().wait_for_text()
# for python 2, returns None if the clipboard is blank.
if clipboardContents is None:
return ''
else:
return clipboardContents
return copy_gtk, paste_gtk
def init_qt_clipboard():
# $DISPLAY should exist
from PyQt4.QtGui import QApplication
app = QApplication([])
def copy_qt(text):
cb = app.clipboard()
cb.setText(text)
def paste_qt():
cb = app.clipboard()
return text_type(cb.text())
return copy_qt, paste_qt
def init_xclip_clipboard():
def copy_xclip(text):
p = subprocess.Popen(['xclip', '-selection', 'c'],
stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=text)
def paste_xclip():
p = subprocess.Popen(['xclip', '-selection', 'c', '-o'],
stdout=subprocess.PIPE, close_fds=True)
stdout, stderr = p.communicate()
return stdout.decode()
return copy_xclip, paste_xclip
def init_xsel_clipboard():
def copy_xsel(text):
p = subprocess.Popen(['xsel', '-b', '-i'],
stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=text)
def paste_xsel():
p = subprocess.Popen(['xsel', '-b', '-o'],
stdout=subprocess.PIPE, close_fds=True)
stdout, stderr = p.communicate()
return stdout.decode()
return copy_xsel, paste_xsel
def init_klipper_clipboard():
def copy_klipper(text):
p = subprocess.Popen(
['qdbus', 'org.kde.klipper', '/klipper', 'setClipboardContents',
text],
stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=None)
def paste_klipper():
p = subprocess.Popen(
['qdbus', 'org.kde.klipper', '/klipper', 'getClipboardContents'],
stdout=subprocess.PIPE, close_fds=True)
stdout, stderr = p.communicate()
# Workaround for https://bugs.kde.org/show_bug.cgi?id=342874
# TODO: https://github.com/asweigart/pyperclip/issues/43
clipboardContents = stdout.decode()
# even if blank, Klipper will append a newline at the end
assert len(clipboardContents) > 0
# make sure that newline is there
assert clipboardContents.endswith('\n')
if clipboardContents.endswith('\n'):
clipboardContents = clipboardContents[:-1]
return clipboardContents
return copy_klipper, paste_klipper
def init_no_clipboard():
class ClipboardUnavailable(object):
def __call__(self, *args, **kwargs):
raise PyperclipException(EXCEPT_MSG)
if PY2:
def __nonzero__(self):
return False
else:
def __bool__(self):
return False
return ClipboardUnavailable(), ClipboardUnavailable()
class CheckedCall(object):
def __init__(self, f):
super(CheckedCall, self).__setattr__("f", f)
def __call__(self, *args):
ret = self.f(*args)
if not ret and get_errno():
raise PyperclipWindowsException("Error calling " + self.f.__name__)
return ret
def __setattr__(self, key, value):
setattr(self.f, key, value)
def init_windows_clipboard():
from ctypes.wintypes import (HGLOBAL, LPVOID, DWORD, LPCSTR, INT, HWND,
HINSTANCE, HMENU, BOOL, UINT, HANDLE)
windll = ctypes.windll
safeCreateWindowExA = CheckedCall(windll.user32.CreateWindowExA)
safeCreateWindowExA.argtypes = [DWORD, LPCSTR, LPCSTR, DWORD, INT, INT,
INT, INT, HWND, HMENU, HINSTANCE, LPVOID]
safeCreateWindowExA.restype = HWND
safeDestroyWindow = CheckedCall(windll.user32.DestroyWindow)
safeDestroyWindow.argtypes = [HWND]
safeDestroyWindow.restype = BOOL
OpenClipboard = windll.user32.OpenClipboard
OpenClipboard.argtypes = [HWND]
OpenClipboard.restype = BOOL
safeCloseClipboard = CheckedCall(windll.user32.CloseClipboard)
safeCloseClipboard.argtypes = []
safeCloseClipboard.restype = BOOL
safeEmptyClipboard = CheckedCall(windll.user32.EmptyClipboard)
safeEmptyClipboard.argtypes = []
safeEmptyClipboard.restype = BOOL
safeGetClipboardData = CheckedCall(windll.user32.GetClipboardData)
safeGetClipboardData.argtypes = [UINT]
safeGetClipboardData.restype = HANDLE
safeSetClipboardData = CheckedCall(windll.user32.SetClipboardData)
safeSetClipboardData.argtypes = [UINT, HANDLE]
safeSetClipboardData.restype = HANDLE
safeGlobalAlloc = CheckedCall(windll.kernel32.GlobalAlloc)
safeGlobalAlloc.argtypes = [UINT, c_size_t]
safeGlobalAlloc.restype = HGLOBAL
safeGlobalLock = CheckedCall(windll.kernel32.GlobalLock)
safeGlobalLock.argtypes = [HGLOBAL]
safeGlobalLock.restype = LPVOID
safeGlobalUnlock = CheckedCall(windll.kernel32.GlobalUnlock)
safeGlobalUnlock.argtypes = [HGLOBAL]
safeGlobalUnlock.restype = BOOL
GMEM_MOVEABLE = 0x0002
CF_UNICODETEXT = 13
@contextlib.contextmanager
def window():
"""
Context that provides a valid Windows hwnd.
"""
# we really just need the hwnd, so setting "STATIC"
# as predefined lpClass is just fine.
hwnd = safeCreateWindowExA(0, b"STATIC", None, 0, 0, 0, 0, 0,
None, None, None, None)
try:
yield hwnd
finally:
safeDestroyWindow(hwnd)
@contextlib.contextmanager
def clipboard(hwnd):
"""
Context manager that opens the clipboard and prevents
other applications from modifying the clipboard content.
"""
# We may not get the clipboard handle immediately because
# some other application is accessing it (?)
# We try for at least 500ms to get the clipboard.
t = time.time() + 0.5
success = False
while time.time() < t:
success = OpenClipboard(hwnd)
if success:
break
time.sleep(0.01)
if not success:
raise PyperclipWindowsException("Error calling OpenClipboard")
try:
yield
finally:
safeCloseClipboard()
def copy_windows(text):
# This function is heavily based on
# http://msdn.com/ms649016#_win32_Copying_Information_to_the_Clipboard
with window() as hwnd:
# http://msdn.com/ms649048
# If an application calls OpenClipboard with hwnd set to NULL,
# EmptyClipboard sets the clipboard owner to NULL;
# this causes SetClipboardData to fail.
# => We need a valid hwnd to copy something.
with clipboard(hwnd):
safeEmptyClipboard()
if text:
# http://msdn.com/ms649051
# If the hMem parameter identifies a memory object,
# the object must have been allocated using the
# function with the GMEM_MOVEABLE flag.
count = len(text) + 1
handle = safeGlobalAlloc(GMEM_MOVEABLE,
count * sizeof(c_wchar))
locked_handle = safeGlobalLock(handle)
ctypes.memmove(c_wchar_p(locked_handle), c_wchar_p(text), count * sizeof(c_wchar))
safeGlobalUnlock(handle)
safeSetClipboardData(CF_UNICODETEXT, handle)
def paste_windows():
with clipboard(None):
handle = safeGetClipboardData(CF_UNICODETEXT)
if not handle:
# GetClipboardData may return NULL with errno == NO_ERROR
# if the clipboard is empty.
# (Also, it may return a handle to an empty buffer,
# but technically that's not empty)
return ""
return c_wchar_p(handle).value
return copy_windows, paste_windows
# `import PyQt4` sys.exit()s if DISPLAY is not in the environment.
# Thus, we need to detect the presence of $DISPLAY manually
# and not load PyQt4 if it is absent.
HAS_DISPLAY = os.getenv("DISPLAY", False)
CHECK_CMD = "where" if platform.system() == "Windows" else "which"
def _executable_exists(name):
return subprocess.call([CHECK_CMD, name],
stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
def determine_clipboard():
# Determine the OS/platform and set
# the copy() and paste() functions accordingly.
if 'cygwin' in platform.system().lower():
# FIXME: pyperclip currently does not support Cygwin,
# see https://github.com/asweigart/pyperclip/issues/55
pass
elif os.name == 'nt' or platform.system() == 'Windows':
return init_windows_clipboard()
if os.name == 'mac' or platform.system() == 'Darwin':
return init_osx_clipboard()
if HAS_DISPLAY:
# Determine which command/module is installed, if any.
try:
import gtk # check if gtk is installed
except ImportError:
pass
else:
return init_gtk_clipboard()
try:
import PyQt4 # check if PyQt4 is installed
except ImportError:
pass
else:
return init_qt_clipboard()
if _executable_exists("xclip"):
return init_xclip_clipboard()
if _executable_exists("xsel"):
return init_xsel_clipboard()
if _executable_exists("klipper") and _executable_exists("qdbus"):
return init_klipper_clipboard()
return init_no_clipboard()
def set_clipboard(clipboard):
global copy, paste
clipboard_types = {'osx': init_osx_clipboard,
'gtk': init_gtk_clipboard,
'qt': init_qt_clipboard,
'xclip': init_xclip_clipboard,
'xsel': init_xsel_clipboard,
'klipper': init_klipper_clipboard,
'windows': init_windows_clipboard,
'no': init_no_clipboard}
copy, paste = clipboard_types[clipboard]()
copy, paste = determine_clipboard()
|
roglew/pappy-proxy
|
pappyproxy/clip.py
|
Python
|
mit
| 13,104
|
[
"VisIt"
] |
b70e80da0a7020aa58e2bbecf43f778cd35459ddb61637daddb6414668d27755
|
import operator
from jmespath import functions
from jmespath.compat import string_type
from numbers import Number
def _equals(x, y):
if _is_special_integer_case(x, y):
return False
else:
return x == y
def _is_special_integer_case(x, y):
# We need to special case comparing 0 or 1 to
# True/False. While normally comparing any
# integer other than 0/1 to True/False will always
# return False. However 0/1 have this:
# >>> 0 == True
# False
# >>> 0 == False
# True
# >>> 1 == True
# True
# >>> 1 == False
# False
#
# Also need to consider that:
# >>> 0 in [True, False]
# True
if x is 0 or x is 1:
return y is True or y is False
elif y is 0 or y is 1:
return x is True or x is False
def _is_comparable(x):
# The spec doesn't officially support string types yet,
# but enough people are relying on this behavior that
# it's been added back. This should eventually become
# part of the official spec.
return _is_actual_number(x) or isinstance(x, string_type)
def _is_actual_number(x):
# We need to handle python's quirkiness with booleans,
# specifically:
#
# >>> isinstance(False, int)
# True
# >>> isinstance(True, int)
# True
if x is True or x is False:
return False
return isinstance(x, Number)
class Options(object):
"""Options to control how a JMESPath function is evaluated."""
def __init__(self, dict_cls=None, custom_functions=None):
#: The class to use when creating a dict. The interpreter
# may create dictionaries during the evaluation of a JMESPath
# expression. For example, a multi-select hash will
# create a dictionary. By default we use a dict() type.
# You can set this value to change what dict type is used.
# The most common reason you would change this is if you
# want to set a collections.OrderedDict so that you can
# have predictable key ordering.
self.dict_cls = dict_cls
self.custom_functions = custom_functions
class _Expression(object):
def __init__(self, expression, interpreter):
self.expression = expression
self.interpreter = interpreter
def visit(self, node, *args, **kwargs):
return self.interpreter.visit(node, *args, **kwargs)
class Visitor(object):
def __init__(self):
self._method_cache = {}
def visit(self, node, *args, **kwargs):
node_type = node['type']
method = self._method_cache.get(node_type)
if method is None:
method = getattr(
self, 'visit_%s' % node['type'], self.default_visit)
self._method_cache[node_type] = method
return method(node, *args, **kwargs)
def default_visit(self, node, *args, **kwargs):
raise NotImplementedError("default_visit")
class TreeInterpreter(Visitor):
COMPARATOR_FUNC = {
'eq': _equals,
'ne': lambda x, y: not _equals(x, y),
'lt': operator.lt,
'gt': operator.gt,
'lte': operator.le,
'gte': operator.ge
}
_EQUALITY_OPS = ['eq', 'ne']
MAP_TYPE = dict
def __init__(self, options=None):
super(TreeInterpreter, self).__init__()
self._dict_cls = self.MAP_TYPE
if options is None:
options = Options()
self._options = options
if options.dict_cls is not None:
self._dict_cls = self._options.dict_cls
if options.custom_functions is not None:
self._functions = self._options.custom_functions
else:
self._functions = functions.Functions()
def default_visit(self, node, *args, **kwargs):
raise NotImplementedError(node['type'])
def visit_subexpression(self, node, value):
result = value
for node in node['children']:
result = self.visit(node, result)
return result
def visit_field(self, node, value):
try:
return value.get(node['value'])
except AttributeError:
return None
def visit_comparator(self, node, value):
# Common case: comparator is == or !=
comparator_func = self.COMPARATOR_FUNC[node['value']]
if node['value'] in self._EQUALITY_OPS:
return comparator_func(
self.visit(node['children'][0], value),
self.visit(node['children'][1], value)
)
else:
# Ordering operators are only valid for numbers.
# Evaluating any other type with a comparison operator
# will yield a None value.
left = self.visit(node['children'][0], value)
right = self.visit(node['children'][1], value)
num_types = (int, float)
if not (_is_comparable(left) and
_is_comparable(right)):
return None
return comparator_func(left, right)
def visit_current(self, node, value):
return value
def visit_expref(self, node, value):
return _Expression(node['children'][0], self)
def visit_function_expression(self, node, value):
resolved_args = []
for child in node['children']:
current = self.visit(child, value)
resolved_args.append(current)
return self._functions.call_function(node['value'], resolved_args)
def visit_filter_projection(self, node, value):
base = self.visit(node['children'][0], value)
if not isinstance(base, list):
return None
comparator_node = node['children'][2]
collected = []
for element in base:
if self._is_true(self.visit(comparator_node, element)):
current = self.visit(node['children'][1], element)
if current is not None:
collected.append(current)
return collected
def visit_flatten(self, node, value):
base = self.visit(node['children'][0], value)
if not isinstance(base, list):
# Can't flatten the object if it's not a list.
return None
merged_list = []
for element in base:
if isinstance(element, list):
merged_list.extend(element)
else:
merged_list.append(element)
return merged_list
def visit_identity(self, node, value):
return value
def visit_index(self, node, value):
# Even though we can index strings, we don't
# want to support that.
if not isinstance(value, list):
return None
try:
return value[node['value']]
except IndexError:
return None
def visit_index_expression(self, node, value):
result = value
for node in node['children']:
result = self.visit(node, result)
return result
def visit_slice(self, node, value):
if not isinstance(value, list):
return None
s = slice(*node['children'])
return value[s]
def visit_key_val_pair(self, node, value):
return self.visit(node['children'][0], value)
def visit_literal(self, node, value):
return node['value']
def visit_multi_select_dict(self, node, value):
if value is None:
return None
collected = self._dict_cls()
for child in node['children']:
collected[child['value']] = self.visit(child, value)
return collected
def visit_multi_select_list(self, node, value):
if value is None:
return None
collected = []
for child in node['children']:
collected.append(self.visit(child, value))
return collected
def visit_or_expression(self, node, value):
matched = self.visit(node['children'][0], value)
if self._is_false(matched):
matched = self.visit(node['children'][1], value)
return matched
def visit_and_expression(self, node, value):
matched = self.visit(node['children'][0], value)
if self._is_false(matched):
return matched
return self.visit(node['children'][1], value)
def visit_not_expression(self, node, value):
original_result = self.visit(node['children'][0], value)
if original_result is 0:
# Special case for 0, !0 should be false, not true.
# 0 is not a special cased integer in jmespath.
return False
return not original_result
def visit_pipe(self, node, value):
result = value
for node in node['children']:
result = self.visit(node, result)
return result
def visit_projection(self, node, value):
base = self.visit(node['children'][0], value)
if not isinstance(base, list):
return None
collected = []
for element in base:
current = self.visit(node['children'][1], element)
if current is not None:
collected.append(current)
return collected
def visit_value_projection(self, node, value):
base = self.visit(node['children'][0], value)
try:
base = base.values()
except AttributeError:
return None
collected = []
for element in base:
current = self.visit(node['children'][1], element)
if current is not None:
collected.append(current)
return collected
def _is_false(self, value):
# This looks weird, but we're explicitly using equality checks
# because the truth/false values are different between
# python and jmespath.
return (value == '' or value == [] or value == {} or value is None or
value is False)
def _is_true(self, value):
return not self._is_false(value)
class GraphvizVisitor(Visitor):
def __init__(self):
super(GraphvizVisitor, self).__init__()
self._lines = []
self._count = 1
def visit(self, node, *args, **kwargs):
self._lines.append('digraph AST {')
current = '%s%s' % (node['type'], self._count)
self._count += 1
self._visit(node, current)
self._lines.append('}')
return '\n'.join(self._lines)
def _visit(self, node, current):
self._lines.append('%s [label="%s(%s)"]' % (
current, node['type'], node.get('value', '')))
for child in node.get('children', []):
child_name = '%s%s' % (child['type'], self._count)
self._count += 1
self._lines.append(' %s -> %s' % (current, child_name))
self._visit(child, child_name)
|
ctrlaltdel/neutrinator
|
vendor/jmespath/visitor.py
|
Python
|
gpl-3.0
| 10,769
|
[
"VisIt"
] |
2e3e1ae59d41e60d9d48310964e0da9f8674fe2bdc444e21a8dc1c2874dccf6c
|
# -*- encoding:utf-8 -*-
import sys, textwrap
from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc
from numpydoc.docscrape_sphinx import SphinxDocString, SphinxClassDoc
from nose.tools import *
if sys.version_info[0] >= 3:
sixu = lambda s: s
else:
sixu = lambda s: str(s, 'unicode_escape')
doc_txt = '''\
numpy.multivariate_normal(mean, cov, shape=None, spam=None)
Draw values from a multivariate normal distribution with specified
mean and covariance.
The multivariate normal or Gaussian distribution is a generalisation
of the one-dimensional normal distribution to higher dimensions.
Parameters
----------
mean : (N,) ndarray
Mean of the N-dimensional distribution.
.. math::
(1+2+3)/3
cov : (N, N) ndarray
Covariance matrix of the distribution.
shape : tuple of ints
Given a shape of, for example, (m,n,k), m*n*k samples are
generated, and packed in an m-by-n-by-k arrangement. Because
each sample is N-dimensional, the output shape is (m,n,k,N).
Returns
-------
out : ndarray
The drawn samples, arranged according to `shape`. If the
shape given is (m,n,...), then the shape of `out` is is
(m,n,...,N).
In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
value drawn from the distribution.
list of str
This is not a real return value. It exists to test
anonymous return values.
Other Parameters
----------------
spam : parrot
A parrot off its mortal coil.
Raises
------
RuntimeError
Some error
Warns
-----
RuntimeWarning
Some warning
Warnings
--------
Certain warnings apply.
Notes
-----
Instead of specifying the full covariance matrix, popular
approximations include:
- Spherical covariance (`cov` is a multiple of the identity matrix)
- Diagonal covariance (`cov` has non-negative elements only on the diagonal)
This geometrical property can be seen in two dimensions by plotting
generated data-points:
>>> mean = [0,0]
>>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis
>>> x,y = multivariate_normal(mean,cov,5000).T
>>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()
Note that the covariance matrix must be symmetric and non-negative
definite.
References
----------
.. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
Processes," 3rd ed., McGraw-Hill Companies, 1991
.. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
2nd ed., Wiley, 2001.
See Also
--------
some, other, funcs
otherfunc : relationship
Examples
--------
>>> mean = (1,2)
>>> cov = [[1,0],[1,0]]
>>> x = multivariate_normal(mean,cov,(3,3))
>>> print x.shape
(3, 3, 2)
The following is probably true, given that 0.6 is roughly twice the
standard deviation:
>>> print list( (x[0,0,:] - mean) < 0.6 )
[True, True]
.. index:: random
:refguide: random;distributions, random;gauss
'''
doc = NumpyDocString(doc_txt)
def test_signature():
assert doc['Signature'].startswith('numpy.multivariate_normal(')
assert doc['Signature'].endswith('spam=None)')
def test_summary():
assert doc['Summary'][0].startswith('Draw values')
assert doc['Summary'][-1].endswith('covariance.')
def test_extended_summary():
assert doc['Extended Summary'][0].startswith('The multivariate normal')
def test_parameters():
assert_equal(len(doc['Parameters']), 3)
assert_equal([n for n,_,_ in doc['Parameters']], ['mean','cov','shape'])
arg, arg_type, desc = doc['Parameters'][1]
assert_equal(arg_type, '(N, N) ndarray')
assert desc[0].startswith('Covariance matrix')
assert doc['Parameters'][0][-1][-2] == ' (1+2+3)/3'
def test_other_parameters():
assert_equal(len(doc['Other Parameters']), 1)
assert_equal([n for n,_,_ in doc['Other Parameters']], ['spam'])
arg, arg_type, desc = doc['Other Parameters'][0]
assert_equal(arg_type, 'parrot')
assert desc[0].startswith('A parrot off its mortal coil')
def test_returns():
assert_equal(len(doc['Returns']), 2)
arg, arg_type, desc = doc['Returns'][0]
assert_equal(arg, 'out')
assert_equal(arg_type, 'ndarray')
assert desc[0].startswith('The drawn samples')
assert desc[-1].endswith('distribution.')
arg, arg_type, desc = doc['Returns'][1]
assert_equal(arg, 'list of str')
assert_equal(arg_type, '')
assert desc[0].startswith('This is not a real')
assert desc[-1].endswith('anonymous return values.')
def test_notes():
assert doc['Notes'][0].startswith('Instead')
assert doc['Notes'][-1].endswith('definite.')
assert_equal(len(doc['Notes']), 17)
def test_references():
assert doc['References'][0].startswith('..')
assert doc['References'][-1].endswith('2001.')
def test_examples():
assert doc['Examples'][0].startswith('>>>')
assert doc['Examples'][-1].endswith('True]')
def test_index():
assert_equal(doc['index']['default'], 'random')
assert_equal(len(doc['index']), 2)
assert_equal(len(doc['index']['refguide']), 2)
def non_blank_line_by_line_compare(a,b):
a = textwrap.dedent(a)
b = textwrap.dedent(b)
a = [l.rstrip() for l in a.split('\n') if l.strip()]
b = [l.rstrip() for l in b.split('\n') if l.strip()]
for n,line in enumerate(a):
if not line == b[n]:
raise AssertionError("Lines %s of a and b differ: "
"\n>>> %s\n<<< %s\n" %
(n,line,b[n]))
def test_str():
non_blank_line_by_line_compare(str(doc),
"""numpy.multivariate_normal(mean, cov, shape=None, spam=None)
Draw values from a multivariate normal distribution with specified
mean and covariance.
The multivariate normal or Gaussian distribution is a generalisation
of the one-dimensional normal distribution to higher dimensions.
Parameters
----------
mean : (N,) ndarray
Mean of the N-dimensional distribution.
.. math::
(1+2+3)/3
cov : (N, N) ndarray
Covariance matrix of the distribution.
shape : tuple of ints
Given a shape of, for example, (m,n,k), m*n*k samples are
generated, and packed in an m-by-n-by-k arrangement. Because
each sample is N-dimensional, the output shape is (m,n,k,N).
Returns
-------
out : ndarray
The drawn samples, arranged according to `shape`. If the
shape given is (m,n,...), then the shape of `out` is is
(m,n,...,N).
In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
value drawn from the distribution.
list of str
This is not a real return value. It exists to test
anonymous return values.
Other Parameters
----------------
spam : parrot
A parrot off its mortal coil.
Raises
------
RuntimeError
Some error
Warns
-----
RuntimeWarning
Some warning
Warnings
--------
Certain warnings apply.
See Also
--------
`some`_, `other`_, `funcs`_
`otherfunc`_
relationship
Notes
-----
Instead of specifying the full covariance matrix, popular
approximations include:
- Spherical covariance (`cov` is a multiple of the identity matrix)
- Diagonal covariance (`cov` has non-negative elements only on the diagonal)
This geometrical property can be seen in two dimensions by plotting
generated data-points:
>>> mean = [0,0]
>>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis
>>> x,y = multivariate_normal(mean,cov,5000).T
>>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()
Note that the covariance matrix must be symmetric and non-negative
definite.
References
----------
.. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
Processes," 3rd ed., McGraw-Hill Companies, 1991
.. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
2nd ed., Wiley, 2001.
Examples
--------
>>> mean = (1,2)
>>> cov = [[1,0],[1,0]]
>>> x = multivariate_normal(mean,cov,(3,3))
>>> print x.shape
(3, 3, 2)
The following is probably true, given that 0.6 is roughly twice the
standard deviation:
>>> print list( (x[0,0,:] - mean) < 0.6 )
[True, True]
.. index:: random
:refguide: random;distributions, random;gauss""")
def test_sphinx_str():
sphinx_doc = SphinxDocString(doc_txt)
non_blank_line_by_line_compare(str(sphinx_doc),
"""
.. index:: random
single: random;distributions, random;gauss
Draw values from a multivariate normal distribution with specified
mean and covariance.
The multivariate normal or Gaussian distribution is a generalisation
of the one-dimensional normal distribution to higher dimensions.
:Parameters:
**mean** : (N,) ndarray
Mean of the N-dimensional distribution.
.. math::
(1+2+3)/3
**cov** : (N, N) ndarray
Covariance matrix of the distribution.
**shape** : tuple of ints
Given a shape of, for example, (m,n,k), m*n*k samples are
generated, and packed in an m-by-n-by-k arrangement. Because
each sample is N-dimensional, the output shape is (m,n,k,N).
:Returns:
**out** : ndarray
The drawn samples, arranged according to `shape`. If the
shape given is (m,n,...), then the shape of `out` is is
(m,n,...,N).
In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
value drawn from the distribution.
list of str
This is not a real return value. It exists to test
anonymous return values.
:Other Parameters:
**spam** : parrot
A parrot off its mortal coil.
:Raises:
**RuntimeError**
Some error
:Warns:
**RuntimeWarning**
Some warning
.. warning::
Certain warnings apply.
.. seealso::
:obj:`some`, :obj:`other`, :obj:`funcs`
:obj:`otherfunc`
relationship
.. rubric:: Notes
Instead of specifying the full covariance matrix, popular
approximations include:
- Spherical covariance (`cov` is a multiple of the identity matrix)
- Diagonal covariance (`cov` has non-negative elements only on the diagonal)
This geometrical property can be seen in two dimensions by plotting
generated data-points:
>>> mean = [0,0]
>>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis
>>> x,y = multivariate_normal(mean,cov,5000).T
>>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()
Note that the covariance matrix must be symmetric and non-negative
definite.
.. rubric:: References
.. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
Processes," 3rd ed., McGraw-Hill Companies, 1991
.. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
2nd ed., Wiley, 2001.
.. only:: latex
[1]_, [2]_
.. rubric:: Examples
>>> mean = (1,2)
>>> cov = [[1,0],[1,0]]
>>> x = multivariate_normal(mean,cov,(3,3))
>>> print x.shape
(3, 3, 2)
The following is probably true, given that 0.6 is roughly twice the
standard deviation:
>>> print list( (x[0,0,:] - mean) < 0.6 )
[True, True]
""")
doc2 = NumpyDocString("""
Returns array of indices of the maximum values of along the given axis.
Parameters
----------
a : {array_like}
Array to look in.
axis : {None, integer}
If None, the index is into the flattened array, otherwise along
the specified axis""")
def test_parameters_without_extended_description():
assert_equal(len(doc2['Parameters']), 2)
doc3 = NumpyDocString("""
my_signature(*params, **kwds)
Return this and that.
""")
def test_escape_stars():
signature = str(doc3).split('\n')[0]
assert_equal(signature, 'my_signature(\*params, \*\*kwds)')
doc4 = NumpyDocString(
"""a.conj()
Return an array with all complex-valued elements conjugated.""")
def test_empty_extended_summary():
assert_equal(doc4['Extended Summary'], [])
doc5 = NumpyDocString(
"""
a.something()
Raises
------
LinAlgException
If array is singular.
Warns
-----
SomeWarning
If needed
""")
def test_raises():
assert_equal(len(doc5['Raises']), 1)
name,_,desc = doc5['Raises'][0]
assert_equal(name,'LinAlgException')
assert_equal(desc,['If array is singular.'])
def test_warns():
assert_equal(len(doc5['Warns']), 1)
name,_,desc = doc5['Warns'][0]
assert_equal(name,'SomeWarning')
assert_equal(desc,['If needed'])
def test_see_also():
doc6 = NumpyDocString(
"""
z(x,theta)
See Also
--------
func_a, func_b, func_c
func_d : some equivalent func
foo.func_e : some other func over
multiple lines
func_f, func_g, :meth:`func_h`, func_j,
func_k
:obj:`baz.obj_q`
:class:`class_j`: fubar
foobar
""")
assert len(doc6['See Also']) == 12
for func, desc, role in doc6['See Also']:
if func in ('func_a', 'func_b', 'func_c', 'func_f',
'func_g', 'func_h', 'func_j', 'func_k', 'baz.obj_q'):
assert(not desc)
else:
assert(desc)
if func == 'func_h':
assert role == 'meth'
elif func == 'baz.obj_q':
assert role == 'obj'
elif func == 'class_j':
assert role == 'class'
else:
assert role is None
if func == 'func_d':
assert desc == ['some equivalent func']
elif func == 'foo.func_e':
assert desc == ['some other func over', 'multiple lines']
elif func == 'class_j':
assert desc == ['fubar', 'foobar']
def test_see_also_print():
class Dummy(object):
"""
See Also
--------
func_a, func_b
func_c : some relationship
goes here
func_d
"""
pass
obj = Dummy()
s = str(FunctionDoc(obj, role='func'))
assert(':func:`func_a`, :func:`func_b`' in s)
assert(' some relationship' in s)
assert(':func:`func_d`' in s)
doc7 = NumpyDocString("""
Doc starts on second line.
""")
def test_empty_first_line():
assert doc7['Summary'][0].startswith('Doc starts')
def test_no_summary():
str(SphinxDocString("""
Parameters
----------"""))
def test_unicode():
doc = SphinxDocString("""
öäöäöäöäöåååå
öäöäöäööäååå
Parameters
----------
ååå : äää
ööö
Returns
-------
ååå : ööö
äää
""")
assert isinstance(doc['Summary'][0], str)
assert doc['Summary'][0] == 'öäöäöäöäöåååå'
def test_plot_examples():
cfg = dict(use_plots=True)
doc = SphinxDocString("""
Examples
--------
>>> import matplotlib.pyplot as plt
>>> plt.plot([1,2,3],[4,5,6])
>>> plt.show()
""", config=cfg)
assert 'plot::' in str(doc), str(doc)
doc = SphinxDocString("""
Examples
--------
.. plot::
import matplotlib.pyplot as plt
plt.plot([1,2,3],[4,5,6])
plt.show()
""", config=cfg)
assert str(doc).count('plot::') == 1, str(doc)
def test_class_members():
class Dummy(object):
"""
Dummy class.
"""
def spam(self, a, b):
"""Spam\n\nSpam spam."""
pass
def ham(self, c, d):
"""Cheese\n\nNo cheese."""
pass
@property
def spammity(self):
"""Spammity index"""
return 0.95
class Ignorable(object):
"""local class, to be ignored"""
pass
for cls in (ClassDoc, SphinxClassDoc):
doc = cls(Dummy, config=dict(show_class_members=False))
assert 'Methods' not in str(doc), (cls, str(doc))
assert 'spam' not in str(doc), (cls, str(doc))
assert 'ham' not in str(doc), (cls, str(doc))
assert 'spammity' not in str(doc), (cls, str(doc))
assert 'Spammity index' not in str(doc), (cls, str(doc))
doc = cls(Dummy, config=dict(show_class_members=True))
assert 'Methods' in str(doc), (cls, str(doc))
assert 'spam' in str(doc), (cls, str(doc))
assert 'ham' in str(doc), (cls, str(doc))
assert 'spammity' in str(doc), (cls, str(doc))
if cls is SphinxClassDoc:
assert '.. autosummary::' in str(doc), str(doc)
else:
assert 'Spammity index' in str(doc), str(doc)
class SubDummy(Dummy):
"""
Subclass of Dummy class.
"""
def ham(self, c, d):
"""Cheese\n\nNo cheese.\nOverloaded Dummy.ham"""
pass
def bar(self, a, b):
"""Bar\n\nNo bar"""
pass
for cls in (ClassDoc, SphinxClassDoc):
doc = cls(SubDummy, config=dict(show_class_members=True,
show_inherited_class_members=False))
assert 'Methods' in str(doc), (cls, str(doc))
assert 'spam' not in str(doc), (cls, str(doc))
assert 'ham' in str(doc), (cls, str(doc))
assert 'bar' in str(doc), (cls, str(doc))
assert 'spammity' not in str(doc), (cls, str(doc))
if cls is SphinxClassDoc:
assert '.. autosummary::' in str(doc), str(doc)
else:
assert 'Spammity index' not in str(doc), str(doc)
doc = cls(SubDummy, config=dict(show_class_members=True,
show_inherited_class_members=True))
assert 'Methods' in str(doc), (cls, str(doc))
assert 'spam' in str(doc), (cls, str(doc))
assert 'ham' in str(doc), (cls, str(doc))
assert 'bar' in str(doc), (cls, str(doc))
assert 'spammity' in str(doc), (cls, str(doc))
if cls is SphinxClassDoc:
assert '.. autosummary::' in str(doc), str(doc)
else:
assert 'Spammity index' in str(doc), str(doc)
def test_duplicate_signature():
# Duplicate function signatures occur e.g. in ufuncs, when the
# automatic mechanism adds one, and a more detailed comes from the
# docstring itself.
doc = NumpyDocString(
"""
z(x1, x2)
z(a, theta)
""")
assert doc['Signature'].strip() == 'z(a, theta)'
class_doc_txt = """
Foo
Parameters
----------
f : callable ``f(t, y, *f_args)``
Aaa.
jac : callable ``jac(t, y, *jac_args)``
Bbb.
Attributes
----------
t : float
Current time.
y : ndarray
Current variable values.
Methods
-------
a
b
c
Examples
--------
For usage examples, see `ode`.
"""
def test_class_members_doc():
doc = ClassDoc(None, class_doc_txt)
non_blank_line_by_line_compare(str(doc),
"""
Foo
Parameters
----------
f : callable ``f(t, y, *f_args)``
Aaa.
jac : callable ``jac(t, y, *jac_args)``
Bbb.
Examples
--------
For usage examples, see `ode`.
Attributes
----------
t : float
Current time.
y : ndarray
Current variable values.
Methods
-------
a
b
c
.. index::
""")
def test_class_members_doc_sphinx():
doc = SphinxClassDoc(None, class_doc_txt)
non_blank_line_by_line_compare(str(doc),
"""
Foo
:Parameters:
**f** : callable ``f(t, y, *f_args)``
Aaa.
**jac** : callable ``jac(t, y, *jac_args)``
Bbb.
.. rubric:: Examples
For usage examples, see `ode`.
.. rubric:: Attributes
=== ==========
t (float) Current time.
y (ndarray) Current variable values.
=== ==========
.. rubric:: Methods
=== ==========
a
b
c
=== ==========
""")
if __name__ == "__main__":
import nose
nose.run()
|
loli/medpy
|
doc/numpydoc/numpydoc/tests/test_docscrape.py
|
Python
|
gpl-3.0
| 19,724
|
[
"Gaussian"
] |
90c994fa6782c2055a6b21e691405a71ec865989d5119436c9c3f2028c3d9952
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from builtins import zip
from builtins import range
from builtins import object
import numpy as np
from . import crystal
def bijk_to_coord(prim,bijk,sd=(True,True,True)):
"""Convert the bijk index into an atomic coordinate,
given the primitive structure
Parameters
----------
prim : Crystal
bijk : (int,int,int,int)
Returns
-------
SelectiveAtomCoord
"""
cart=np.dot(prim.lattice().column_lattice(),bijk[1::])+prim.cart()[bijk[0]]
name=prim.basis()[0].name()
return crystal.SelectiveAtomCoord(cart[0],cart[1],cart[2],name,sd)
def stamp_site(jumbo,site,tol):
"""
Find the closest matching site in the superstructure, if the dot
product between the distance is within the tolerance, replace
the site with the new one.
Parameters
----------
jumbo : Crystal
site : SelectiveAtomCoord
tol : float
Returns
-------
Crystal
"""
ix=crystal.argsort_periodic_coord_match(jumbo.basis(),[site],jumbo.lattice())[0]
dot=crystal.shortest_periodic_coord_distance(site,jumbo.basis()[ix],jumbo.lattice())
if dot>tol:
raise ValueError("You're coordinates don't match. What do.")
jumbo._basis[ix]=site
return jumbo
def stamp_bijk(jumbo,prim,bijk,name,trans=(0,0,0),tol=0.00001):
"""
Find the closest matching site in the superstructure, if the dot
product between the distance is within the tolerance, replace
the site with the new one. The site is specified in terms of
primitive vectors.
Parameters
----------
jumbo : Crystal
prim : Crystal
bijk : [int,int,int,int]
names : str
tol : float, optional
Returns
-------
Crystal
"""
bijk=[i for i in bijk]
bijk[1]+=trans[0]
bijk[2]+=trans[1]
bijk[3]+=trans[2]
stamp=bijk_to_coord(prim,bijk)
stamp._name=name
stamp_site(jumbo,stamp,0.00001)
return jumbo
|
goirijo/thermoplotting
|
thermoplotting/xtals/clusters.py
|
Python
|
mit
| 2,033
|
[
"CRYSTAL"
] |
09458884fcf3e04df9482561cc405de3371a198f93a03d460f5b0d4fc4fd5790
|
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""The freesurfer module provides basic functions for interfacing with
freesurfer tools.
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data'))
>>> os.chdir(datadir)
"""
__docformat__ = 'restructuredtext'
import os
from ..freesurfer.base import FSCommand, FSTraitedSpec
from ..base import (TraitedSpec, File, traits, InputMultiPath,
OutputMultiPath, Directory, isdefined)
from ...utils.filemanip import fname_presuffix, split_filename
from ..freesurfer.utils import copy2subjdir
class MRISPreprocInputSpec(FSTraitedSpec):
out_file = File(argstr='--out %s', genfile=True,
desc='output filename')
target = traits.Str(argstr='--target %s', mandatory=True,
desc='target subject name')
hemi = traits.Enum('lh', 'rh', argstr='--hemi %s',
mandatory=True,
desc='hemisphere for source and target')
surf_measure = traits.Str(argstr='--meas %s',
xor=('surf_measure', 'surf_measure_file', 'surf_area'),
desc='Use subject/surf/hemi.surf_measure as input')
surf_area = traits.Str(argstr='--area %s',
xor=('surf_measure', 'surf_measure_file', 'surf_area'),
desc='Extract vertex area from subject/surf/hemi.surfname to use as input.')
subjects = traits.List(argstr='--s %s...',
xor=('subjects', 'fsgd_file', 'subject_file'),
desc='subjects from who measures are calculated')
fsgd_file = File(exists=True, argstr='--fsgd %s',
xor=('subjects', 'fsgd_file', 'subject_file'),
desc='specify subjects using fsgd file')
subject_file = File(exists=True, argstr='--f %s',
xor=('subjects', 'fsgd_file', 'subject_file'),
desc='file specifying subjects separated by white space')
surf_measure_file = InputMultiPath(File(exists=True), argstr='--is %s...',
xor=('surf_measure', 'surf_measure_file', 'surf_area'),
desc='file alternative to surfmeas, still requires list of subjects')
source_format = traits.Str(argstr='--srcfmt %s', desc='source format')
surf_dir = traits.Str(argstr='--surfdir %s',
desc='alternative directory (instead of surf)')
vol_measure_file = InputMultiPath(traits.Tuple(File(exists=True),
File(exists=True)),
argstr='--iv %s %s...',
desc='list of volume measure and reg file tuples')
proj_frac = traits.Float(argstr='--projfrac %s',
desc='projection fraction for vol2surf')
fwhm = traits.Float(argstr='--fwhm %f',
xor=['num_iters'],
desc='smooth by fwhm mm on the target surface')
num_iters = traits.Int(argstr='--niters %d',
xor=['fwhm'],
desc='niters : smooth by niters on the target surface')
fwhm_source = traits.Float(argstr='--fwhm-src %f',
xor=['num_iters_source'],
desc='smooth by fwhm mm on the source surface')
num_iters_source = traits.Int(argstr='--niterssrc %d',
xor=['fwhm_source'],
desc='niters : smooth by niters on the source surface')
smooth_cortex_only = traits.Bool(argstr='--smooth-cortex-only',
desc='only smooth cortex (ie, exclude medial wall)')
class MRISPreprocOutputSpec(TraitedSpec):
out_file = File(desc='preprocessed output file')
class MRISPreproc(FSCommand):
"""Use FreeSurfer mris_preproc to prepare a group of contrasts for
a second level analysis
Examples
--------
>>> preproc = MRISPreproc()
>>> preproc.inputs.target = 'fsaverage'
>>> preproc.inputs.hemi = 'lh'
>>> preproc.inputs.vol_measure_file = [('cont1.nii', 'register.dat'), \
('cont1a.nii', 'register.dat')]
>>> preproc.inputs.out_file = 'concatenated_file.mgz'
>>> preproc.cmdline
'mris_preproc --hemi lh --out concatenated_file.mgz --target fsaverage --iv cont1.nii register.dat --iv cont1a.nii register.dat'
"""
_cmd = 'mris_preproc'
input_spec = MRISPreprocInputSpec
output_spec = MRISPreprocOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
outfile = self.inputs.out_file
outputs['out_file'] = outfile
if not isdefined(outfile):
outputs['out_file'] = os.path.join(os.getcwd(),
'concat_%s_%s.mgz' % (self.inputs.hemi,
self.inputs.target))
return outputs
def _gen_filename(self, name):
if name == 'out_file':
return self._list_outputs()[name]
return None
class MRISPreprocReconAllInputSpec(MRISPreprocInputSpec):
surf_measure_file = File(exists=True, argstr='--meas %s',
xor=('surf_measure',
'surf_measure_file', 'surf_area'),
desc='file necessary for surfmeas')
surfreg_files = InputMultiPath(File(exists=True), argstr="--surfreg %s",
requires=['lh_surfreg_target', 'rh_surfreg_target'],
desc="lh and rh input surface registration files")
lh_surfreg_target = File(desc="Implicit target surface registration file",
requires=['surfreg_files'])
rh_surfreg_target = File(desc="Implicit target surface registration file",
requires=['surfreg_files'])
subject_id = traits.String('subject_id', argstr='--s %s', usedefault=True,
xor=('subjects', 'fsgd_file',
'subject_file', 'subject_id'),
desc='subject from whom measures are calculated')
copy_inputs = traits.Bool(desc="If running as a node, set this to True " +
"this will copy some implicit inputs to the " +
"node directory.")
class MRISPreprocReconAll(MRISPreproc):
"""Extends MRISPreproc to allow it to be used in a recon-all workflow
Examples
========
>>> preproc = MRISPreprocReconAll()
>>> preproc.inputs.target = 'fsaverage'
>>> preproc.inputs.hemi = 'lh'
>>> preproc.inputs.vol_measure_file = [('cont1.nii', 'register.dat'), \
('cont1a.nii', 'register.dat')]
>>> preproc.inputs.out_file = 'concatenated_file.mgz'
>>> preproc.cmdline
'mris_preproc --hemi lh --out concatenated_file.mgz --s subject_id --target fsaverage --iv cont1.nii register.dat --iv cont1a.nii register.dat'
"""
input_spec = MRISPreprocReconAllInputSpec
def run(self, **inputs):
if self.inputs.copy_inputs:
self.inputs.subjects_dir = os.getcwd()
if 'subjects_dir' in inputs:
inputs['subjects_dir'] = self.inputs.subjects_dir
if isdefined(self.inputs.surf_dir):
folder = self.inputs.surf_dir
else:
folder = 'surf'
if isdefined(self.inputs.surfreg_files):
for surfreg in self.inputs.surfreg_files:
basename = os.path.basename(surfreg)
copy2subjdir(self, surfreg, folder, basename)
if basename.startswith('lh.'):
copy2subjdir(self, self.inputs.lh_surfreg_target,
folder, basename,
subject_id=self.inputs.target)
else:
copy2subjdir(self, self.inputs.rh_surfreg_target,
folder, basename,
subject_id=self.inputs.target)
if isdefined(self.inputs.surf_measure_file):
copy2subjdir(self, self.inputs.surf_measure_file, folder)
return super(MRISPreprocReconAll, self).run(**inputs)
def _format_arg(self, name, spec, value):
# mris_preproc looks for these files in the surf dir
if name == 'surfreg_files':
basename = os.path.basename(value[0])
return spec.argstr % basename.lstrip('rh.').lstrip('lh.')
if name == "surf_measure_file":
basename = os.path.basename(value)
return spec.argstr % basename.lstrip('rh.').lstrip('lh.')
return super(MRISPreprocReconAll, self)._format_arg(name, spec, value)
class GLMFitInputSpec(FSTraitedSpec):
glm_dir = traits.Str(argstr='--glmdir %s', desc='save outputs to dir',
genfile=True)
in_file = File(desc='input 4D file', argstr='--y %s', mandatory=True,
copyfile=False)
_design_xor = ('fsgd', 'design', 'one_sample')
fsgd = traits.Tuple(File(exists=True), traits.Enum('doss', 'dods'),
argstr='--fsgd %s %s', xor=_design_xor,
desc='freesurfer descriptor file')
design = File(exists=True, argstr='--X %s', xor=_design_xor,
desc='design matrix file')
contrast = InputMultiPath(File(exists=True), argstr='--C %s...',
desc='contrast file')
one_sample = traits.Bool(argstr='--osgm',
xor=('one_sample', 'fsgd', 'design', 'contrast'),
desc='construct X and C as a one-sample group mean')
no_contrast_ok = traits.Bool(argstr='--no-contrasts-ok',
desc='do not fail if no contrasts specified')
per_voxel_reg = InputMultiPath(File(exists=True), argstr='--pvr %s...',
desc='per-voxel regressors')
self_reg = traits.Tuple(traits.Int, traits.Int, traits.Int,
argstr='--selfreg %d %d %d',
desc='self-regressor from index col row slice')
weighted_ls = File(exists=True, argstr='--wls %s',
xor=('weight_file', 'weight_inv', 'weight_sqrt'),
desc='weighted least squares')
fixed_fx_var = File(exists=True, argstr='--yffxvar %s',
desc='for fixed effects analysis')
fixed_fx_dof = traits.Int(argstr='--ffxdof %d',
xor=['fixed_fx_dof_file'],
desc='dof for fixed effects analysis')
fixed_fx_dof_file = File(argstr='--ffxdofdat %d',
xor=['fixed_fx_dof'],
desc='text file with dof for fixed effects analysis')
weight_file = File(exists=True, xor=['weighted_ls'],
desc='weight for each input at each voxel')
weight_inv = traits.Bool(argstr='--w-inv', desc='invert weights',
xor=['weighted_ls'])
weight_sqrt = traits.Bool(argstr='--w-sqrt', desc='sqrt of weights',
xor=['weighted_ls'])
fwhm = traits.Range(low=0.0, argstr='--fwhm %f',
desc='smooth input by fwhm')
var_fwhm = traits.Range(low=0.0, argstr='--var-fwhm %f',
desc='smooth variance by fwhm')
no_mask_smooth = traits.Bool(argstr='--no-mask-smooth',
desc='do not mask when smoothing')
no_est_fwhm = traits.Bool(argstr='--no-est-fwhm',
desc='turn off FWHM output estimation')
mask_file = File(exists=True, argstr='--mask %s', desc='binary mask')
label_file = File(exists=True, argstr='--label %s',
xor=['cortex'],
desc='use label as mask, surfaces only')
cortex = traits.Bool(argstr='--cortex',
xor=['label_file'],
desc='use subjects ?h.cortex.label as label')
invert_mask = traits.Bool(argstr='--mask-inv',
desc='invert mask')
prune = traits.Bool(argstr='--prune',
desc='remove voxels that do not have a non-zero value at each frame (def)')
no_prune = traits.Bool(argstr='--no-prune',
xor=['prunethresh'],
desc='do not prune')
prune_thresh = traits.Float(argstr='--prune_thr %f',
xor=['noprune'],
desc='prune threshold. Default is FLT_MIN')
compute_log_y = traits.Bool(argstr='--logy',
desc='compute natural log of y prior to analysis')
save_estimate = traits.Bool(argstr='--yhat-save',
desc='save signal estimate (yhat)')
save_residual = traits.Bool(argstr='--eres-save',
desc='save residual error (eres)')
save_res_corr_mtx = traits.Bool(argstr='--eres-scm',
desc='save residual error spatial correlation matrix (eres.scm). Big!')
surf = traits.Bool(argstr="--surf %s %s %s",
requires=["subject_id", "hemi"],
desc="analysis is on a surface mesh")
subject_id = traits.Str(desc="subject id for surface geometry")
hemi = traits.Enum("lh", "rh", desc="surface hemisphere")
surf_geo = traits.Str("white", usedefault=True,
desc="surface geometry name (e.g. white, pial)")
simulation = traits.Tuple(traits.Enum('perm', 'mc-full', 'mc-z'),
traits.Int(min=1), traits.Float, traits.Str,
argstr='--sim %s %d %f %s',
desc='nulltype nsim thresh csdbasename')
sim_sign = traits.Enum('abs', 'pos', 'neg', argstr='--sim-sign %s',
desc='abs, pos, or neg')
uniform = traits.Tuple(traits.Float, traits.Float,
argstr='--uniform %f %f',
desc='use uniform distribution instead of gaussian')
pca = traits.Bool(argstr='--pca',
desc='perform pca/svd analysis on residual')
calc_AR1 = traits.Bool(argstr='--tar1',
desc='compute and save temporal AR1 of residual')
save_cond = traits.Bool(argstr='--save-cond',
desc='flag to save design matrix condition at each voxel')
vox_dump = traits.Tuple(traits.Int, traits.Int, traits.Int,
argstr='--voxdump %d %d %d',
desc='dump voxel GLM and exit')
seed = traits.Int(argstr='--seed %d', desc='used for synthesizing noise')
synth = traits.Bool(argstr='--synth', desc='replace input with gaussian')
resynth_test = traits.Int(argstr='--resynthtest %d', desc='test GLM by resynthsis')
profile = traits.Int(argstr='--profile %d', desc='niters : test speed')
force_perm = traits.Bool(argstr='--perm-force',
desc='force perumtation test, even when design matrix is not orthog')
diag = traits.Int('--diag %d', desc='Gdiag_no : set diagnositc level')
diag_cluster = traits.Bool(argstr='--diag-cluster',
desc='save sig volume and exit from first sim loop')
debug = traits.Bool(argstr='--debug', desc='turn on debugging')
check_opts = traits.Bool(argstr='--checkopts',
desc="don't run anything, just check options and exit")
allow_repeated_subjects = traits.Bool(argstr='--allowsubjrep',
desc='allow subject names to repeat in the fsgd file (must appear before --fsgd')
allow_ill_cond = traits.Bool(argstr='--illcond',
desc='allow ill-conditioned design matrices')
sim_done_file = File(argstr='--sim-done %s',
desc='create file when simulation finished')
class GLMFitOutputSpec(TraitedSpec):
glm_dir = Directory(exists=True, desc="output directory")
beta_file = File(exists=True, desc="map of regression coefficients")
error_file = File(desc="map of residual error")
error_var_file = File(desc="map of residual error variance")
error_stddev_file = File(desc="map of residual error standard deviation")
estimate_file = File(desc="map of the estimated Y values")
mask_file = File(desc="map of the mask used in the analysis")
fwhm_file = File(desc="text file with estimated smoothness")
dof_file = File(desc="text file with effective degrees-of-freedom for the analysis")
gamma_file = OutputMultiPath(desc="map of contrast of regression coefficients")
gamma_var_file = OutputMultiPath(desc="map of regression contrast variance")
sig_file = OutputMultiPath(desc="map of F-test significance (in -log10p)")
ftest_file = OutputMultiPath(desc="map of test statistic values")
spatial_eigenvectors = File(desc="map of spatial eigenvectors from residual PCA")
frame_eigenvectors = File(desc="matrix of frame eigenvectors from residual PCA")
singular_values = File(desc="matrix singular values from residual PCA")
svd_stats_file = File(desc="text file summarizing the residual PCA")
class GLMFit(FSCommand):
"""Use FreeSurfer's mri_glmfit to specify and estimate a general linear model.
Examples
--------
>>> glmfit = GLMFit()
>>> glmfit.inputs.in_file = 'functional.nii'
>>> glmfit.inputs.one_sample = True
>>> glmfit.cmdline == 'mri_glmfit --glmdir %s --y functional.nii --osgm'%os.getcwd()
True
"""
_cmd = 'mri_glmfit'
input_spec = GLMFitInputSpec
output_spec = GLMFitOutputSpec
def _format_arg(self, name, spec, value):
if name == "surf":
_si = self.inputs
return spec.argstr % (_si.subject_id, _si.hemi, _si.surf_geo)
return super(GLMFit, self)._format_arg(name, spec, value)
def _list_outputs(self):
outputs = self.output_spec().get()
# Get the top-level output directory
if not isdefined(self.inputs.glm_dir):
glmdir = os.getcwd()
else:
glmdir = os.path.abspath(self.inputs.glm_dir)
outputs["glm_dir"] = glmdir
# Assign the output files that always get created
outputs["beta_file"] = os.path.join(glmdir, "beta.mgh")
outputs["error_var_file"] = os.path.join(glmdir, "rvar.mgh")
outputs["error_stddev_file"] = os.path.join(glmdir, "rstd.mgh")
outputs["mask_file"] = os.path.join(glmdir, "mask.mgh")
outputs["fwhm_file"] = os.path.join(glmdir, "fwhm.dat")
outputs["dof_file"] = os.path.join(glmdir, "dof.dat")
# Assign the conditional outputs
if isdefined(self.inputs.save_residual) and self.inputs.save_residual:
outputs["error_file"] = os.path.join(glmdir, "eres.mgh")
if isdefined(self.inputs.save_estimate) and self.inputs.save_estimate:
outputs["estimate_file"] = os.path.join(glmdir, "yhat.mgh")
# Get the contrast directory name(s)
if isdefined(self.inputs.contrast):
contrasts = []
for c in self.inputs.contrast:
if split_filename(c)[2] in [".mat", ".dat", ".mtx", ".con"]:
contrasts.append(split_filename(c)[1])
else:
contrasts.append(os.path.split(c)[1])
elif isdefined(self.inputs.one_sample) and self.inputs.one_sample:
contrasts = ["osgm"]
# Add in the contrast images
outputs["sig_file"] = [os.path.join(glmdir, c, "sig.mgh") for c in contrasts]
outputs["ftest_file"] = [os.path.join(glmdir, c, "F.mgh") for c in contrasts]
outputs["gamma_file"] = [os.path.join(glmdir, c, "gamma.mgh") for c in contrasts]
outputs["gamma_var_file"] = [os.path.join(glmdir, c, "gammavar.mgh") for c in contrasts]
# Add in the PCA results, if relevant
if isdefined(self.inputs.pca) and self.inputs.pca:
pcadir = os.path.join(glmdir, "pca-eres")
outputs["spatial_eigenvectors"] = os.path.join(pcadir, "v.mgh")
outputs["frame_eigenvectors"] = os.path.join(pcadir, "u.mtx")
outputs["singluar_values"] = os.path.join(pcadir, "sdiag.mat")
outputs["svd_stats_file"] = os.path.join(pcadir, "stats.dat")
return outputs
def _gen_filename(self, name):
if name == 'glm_dir':
return os.getcwd()
return None
class OneSampleTTest(GLMFit):
def __init__(self, **kwargs):
super(OneSampleTTest, self).__init__(**kwargs)
self.inputs.one_sample = True
class BinarizeInputSpec(FSTraitedSpec):
in_file = File(exists=True, argstr='--i %s', mandatory=True,
copyfile=False, desc='input volume')
min = traits.Float(argstr='--min %f', xor=['wm_ven_csf'],
desc='min thresh')
max = traits.Float(argstr='--max %f', xor=['wm_ven_csf'],
desc='max thresh')
rmin = traits.Float(argstr='--rmin %f',
desc='compute min based on rmin*globalmean')
rmax = traits.Float(argstr='--rmax %f',
desc='compute max based on rmax*globalmean')
match = traits.List(traits.Int, argstr='--match %d...',
desc='match instead of threshold')
wm = traits.Bool(argstr='--wm',
desc='set match vals to 2 and 41 (aseg for cerebral WM)')
ventricles = traits.Bool(argstr='--ventricles',
desc='set match vals those for aseg ventricles+choroid (not 4th)')
wm_ven_csf = traits.Bool(argstr='--wm+vcsf', xor=['min', 'max'],
desc='WM and ventricular CSF, including choroid (not 4th)')
binary_file = File(argstr='--o %s', genfile=True,
desc='binary output volume')
out_type = traits.Enum('nii', 'nii.gz', 'mgz', argstr='',
desc='output file type')
count_file = traits.Either(traits.Bool, File,
argstr='--count %s',
desc='save number of hits in ascii file (hits, ntotvox, pct)')
bin_val = traits.Int(argstr='--binval %d',
desc='set vox within thresh to val (default is 1)')
bin_val_not = traits.Int(argstr='--binvalnot %d',
desc='set vox outside range to val (default is 0)')
invert = traits.Bool(argstr='--inv',
desc='set binval=0, binvalnot=1')
frame_no = traits.Int(argstr='--frame %s',
desc='use 0-based frame of input (default is 0)')
merge_file = File(exists=True, argstr='--merge %s',
desc='merge with mergevol')
mask_file = File(exists=True, argstr='--mask maskvol',
desc='must be within mask')
mask_thresh = traits.Float(argstr='--mask-thresh %f',
desc='set thresh for mask')
abs = traits.Bool(argstr='--abs',
desc='take abs of invol first (ie, make unsigned)')
bin_col_num = traits.Bool(argstr='--bincol',
desc='set binarized voxel value to its column number')
zero_edges = traits.Bool(argstr='--zero-edges',
desc='zero the edge voxels')
zero_slice_edge = traits.Bool(argstr='--zero-slice-edges',
desc='zero the edge slice voxels')
dilate = traits.Int(argstr='--dilate %d',
desc='niters: dilate binarization in 3D')
erode = traits.Int(argstr='--erode %d',
desc='nerode: erode binarization in 3D (after any dilation)')
erode2d = traits.Int(argstr='--erode2d %d',
desc='nerode2d: erode binarization in 2D (after any 3D erosion)')
class BinarizeOutputSpec(TraitedSpec):
binary_file = File(exists=True, desc='binarized output volume')
count_file = File(desc='ascii file containing number of hits')
class Binarize(FSCommand):
"""Use FreeSurfer mri_binarize to threshold an input volume
Examples
--------
>>> binvol = Binarize(in_file='structural.nii', min=10, binary_file='foo_out.nii')
>>> binvol.cmdline
'mri_binarize --o foo_out.nii --i structural.nii --min 10.000000'
"""
_cmd = 'mri_binarize'
input_spec = BinarizeInputSpec
output_spec = BinarizeOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
outfile = self.inputs.binary_file
if not isdefined(outfile):
if isdefined(self.inputs.out_type):
outfile = fname_presuffix(self.inputs.in_file,
newpath=os.getcwd(),
suffix='.'.join(('_thresh',
self.inputs.out_type)),
use_ext=False)
else:
outfile = fname_presuffix(self.inputs.in_file,
newpath=os.getcwd(),
suffix='_thresh')
outputs['binary_file'] = os.path.abspath(outfile)
value = self.inputs.count_file
if isdefined(value):
if isinstance(value, bool):
if value:
outputs['count_file'] = fname_presuffix(self.inputs.in_file,
suffix='_count.txt',
newpath=os.getcwd(),
use_ext=False)
else:
outputs['count_file'] = value
return outputs
def _format_arg(self, name, spec, value):
if name == 'count_file':
if isinstance(value, bool):
fname = self._list_outputs()[name]
else:
fname = value
return spec.argstr % fname
if name == 'out_type':
return ''
return super(Binarize, self)._format_arg(name, spec, value)
def _gen_filename(self, name):
if name == 'binary_file':
return self._list_outputs()[name]
return None
class ConcatenateInputSpec(FSTraitedSpec):
in_files = InputMultiPath(File(exists=True),
desc='Individual volumes to be concatenated',
argstr='--i %s...', mandatory=True)
concatenated_file = File(desc='Output volume', argstr='--o %s',
genfile=True)
sign = traits.Enum('abs', 'pos', 'neg', argstr='--%s',
desc='Take only pos or neg voxles from input, or take abs')
stats = traits.Enum('sum', 'var', 'std', 'max', 'min', 'mean', argstr='--%s',
desc='Compute the sum, var, std, max, min or mean of the input volumes')
paired_stats = traits.Enum('sum', 'avg', 'diff', 'diff-norm', 'diff-norm1',
'diff-norm2', argstr='--paired-%s',
desc='Compute paired sum, avg, or diff')
gmean = traits.Int(argstr='--gmean %d',
desc='create matrix to average Ng groups, Nper=Ntot/Ng')
mean_div_n = traits.Bool(argstr='--mean-div-n',
desc='compute mean/nframes (good for var)')
multiply_by = traits.Float(argstr='--mul %f',
desc='Multiply input volume by some amount')
add_val = traits.Float(argstr='--add %f',
desc='Add some amount to the input volume')
multiply_matrix_file = File(exists=True, argstr='--mtx %s',
desc='Multiply input by an ascii matrix in file')
combine = traits.Bool(argstr='--combine',
desc='Combine non-zero values into single frame volume')
keep_dtype = traits.Bool(argstr='--keep-datatype',
desc='Keep voxelwise precision type (default is float')
max_bonfcor = traits.Bool(argstr='--max-bonfcor',
desc='Compute max and bonferroni correct (assumes -log10(ps))')
max_index = traits.Bool(argstr='--max-index',
desc='Compute the index of max voxel in concatenated volumes')
mask_file = File(exists=True, argstr='--mask %s', desc='Mask input with a volume')
vote = traits.Bool(argstr='--vote',
desc='Most frequent value at each voxel and fraction of occurances')
sort = traits.Bool(argstr='--sort',
desc='Sort each voxel by ascending frame value')
class ConcatenateOutputSpec(TraitedSpec):
concatenated_file = File(exists=True,
desc='Path/name of the output volume')
class Concatenate(FSCommand):
"""Use Freesurfer mri_concat to combine several input volumes
into one output volume. Can concatenate by frames, or compute
a variety of statistics on the input volumes.
Examples
--------
Combine two input volumes into one volume with two frames
>>> concat = Concatenate()
>>> concat.inputs.in_files = ['cont1.nii', 'cont2.nii']
>>> concat.inputs.concatenated_file = 'bar.nii'
>>> concat.cmdline
'mri_concat --o bar.nii --i cont1.nii --i cont2.nii'
"""
_cmd = 'mri_concat'
input_spec = ConcatenateInputSpec
output_spec = ConcatenateOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
fname = self.inputs.concatenated_file
if not isdefined(fname):
fname = 'concat_output.nii.gz'
outputs['concatenated_file'] = os.path.join(os.getcwd(), fname)
return outputs
def _gen_filename(self, name):
if name == 'concatenated_file':
return self._list_outputs()[name]
return None
class SegStatsInputSpec(FSTraitedSpec):
_xor_inputs = ('segmentation_file', 'annot', 'surf_label')
segmentation_file = File(exists=True, argstr='--seg %s', xor=_xor_inputs,
mandatory=True, desc='segmentation volume path')
annot = traits.Tuple(traits.Str, traits.Enum('lh', 'rh'), traits.Str,
argstr='--annot %s %s %s', xor=_xor_inputs,
mandatory=True,
desc='subject hemi parc : use surface parcellation')
surf_label = traits.Tuple(traits.Str, traits.Enum('lh', 'rh'), traits.Str,
argstr='--slabel %s %s %s', xor=_xor_inputs,
mandatory=True,
desc='subject hemi label : use surface label')
summary_file = File(argstr='--sum %s', genfile=True, position=-1,
desc='Segmentation stats summary table file')
partial_volume_file = File(exists=True, argstr='--pv %s',
desc='Compensate for partial voluming')
in_file = File(exists=True, argstr='--i %s',
desc='Use the segmentation to report stats on this volume')
frame = traits.Int(argstr='--frame %d',
desc='Report stats on nth frame of input volume')
multiply = traits.Float(argstr='--mul %f', desc='multiply input by val')
calc_snr = traits.Bool(argstr='--snr', desc='save mean/std as extra column in output table')
calc_power = traits.Enum('sqr', 'sqrt', argstr='--%s',
desc='Compute either the sqr or the sqrt of the input')
_ctab_inputs = ('color_table_file', 'default_color_table', 'gca_color_table')
color_table_file = File(exists=True, argstr='--ctab %s', xor=_ctab_inputs,
desc='color table file with seg id names')
default_color_table = traits.Bool(argstr='--ctab-default', xor=_ctab_inputs,
desc='use $FREESURFER_HOME/FreeSurferColorLUT.txt')
gca_color_table = File(exists=True, argstr='--ctab-gca %s', xor=_ctab_inputs,
desc='get color table from GCA (CMA)')
segment_id = traits.List(argstr='--id %s...', desc='Manually specify segmentation ids')
exclude_id = traits.Int(argstr='--excludeid %d', desc='Exclude seg id from report')
exclude_ctx_gm_wm = traits.Bool(argstr='--excl-ctxgmwm',
desc='exclude cortical gray and white matter')
wm_vol_from_surf = traits.Bool(argstr='--surf-wm-vol', desc='Compute wm volume from surf')
cortex_vol_from_surf = traits.Bool(argstr='--surf-ctx-vol', desc='Compute cortex volume from surf')
non_empty_only = traits.Bool(argstr='--nonempty', desc='Only report nonempty segmentations')
empty = traits.Bool(argstr="--empty",
desc="Report on segmentations listed in the color table")
mask_file = File(exists=True, argstr='--mask %s',
desc='Mask volume (same size as seg')
mask_thresh = traits.Float(argstr='--maskthresh %f',
desc='binarize mask with this threshold <0.5>')
mask_sign = traits.Enum('abs', 'pos', 'neg', '--masksign %s',
desc='Sign for mask threshold: pos, neg, or abs')
mask_frame = traits.Int('--maskframe %d',
requires=['mask_file'],
desc='Mask with this (0 based) frame of the mask volume')
mask_invert = traits.Bool(argstr='--maskinvert', desc='Invert binarized mask volume')
mask_erode = traits.Int(argstr='--maskerode %d', desc='Erode mask by some amount')
brain_vol = traits.Enum('brain-vol-from-seg', 'brainmask', argstr='--%s',
desc='Compute brain volume either with ``brainmask`` or ``brain-vol-from-seg``')
brainmask_file = File(argstr="--brainmask %s", exists=True,
desc="Load brain mask and compute the volume of the brain as the non-zero voxels in this volume")
etiv = traits.Bool(argstr='--etiv', desc='Compute ICV from talairach transform')
etiv_only = traits.Enum('etiv', 'old-etiv', '--%s-only',
desc='Compute etiv and exit. Use ``etiv`` or ``old-etiv``')
avgwf_txt_file = traits.Either(traits.Bool, File, argstr='--avgwf %s',
desc='Save average waveform into file (bool or filename)')
avgwf_file = traits.Either(traits.Bool, File, argstr='--avgwfvol %s',
desc='Save as binary volume (bool or filename)')
sf_avg_file = traits.Either(traits.Bool, File, argstr='--sfavg %s',
desc='Save mean across space and time')
vox = traits.List(traits.Int, argstr='--vox %s',
desc='Replace seg with all 0s except at C R S (three int inputs)')
supratent = traits.Bool(argstr="--supratent",
desc="Undocumented input flag")
subcort_gm = traits.Bool(argstr="--subcortgray",
desc="Compute volume of subcortical gray matter")
total_gray = traits.Bool(argstr="--totalgray",
desc="Compute volume of total gray matter")
euler = traits.Bool(argstr="--euler",
desc="Write out number of defect holes in orig.nofix based on the euler number")
in_intensity = File(argstr="--in %s --in-intensity-name %s",
desc="Undocumented input norm.mgz file")
intensity_units = traits.Enum('MR', argstr="--in-intensity-units %s",
requires=["in_intensity"], desc="Intensity units")
class SegStatsOutputSpec(TraitedSpec):
summary_file = File(exists=True, desc='Segmentation summary statistics table')
avgwf_txt_file = File(desc='Text file with functional statistics averaged over segs')
avgwf_file = File(desc='Volume with functional statistics averaged over segs')
sf_avg_file = File(desc='Text file with func statistics averaged over segs and framss')
class SegStats(FSCommand):
"""Use FreeSurfer mri_segstats for ROI analysis
Examples
--------
>>> import nipype.interfaces.freesurfer as fs
>>> ss = fs.SegStats()
>>> ss.inputs.annot = ('PWS04', 'lh', 'aparc')
>>> ss.inputs.in_file = 'functional.nii'
>>> ss.inputs.subjects_dir = '.'
>>> ss.inputs.avgwf_txt_file = 'avgwf.txt'
>>> ss.inputs.summary_file = 'summary.stats'
>>> ss.cmdline
'mri_segstats --annot PWS04 lh aparc --avgwf ./avgwf.txt --i functional.nii --sum ./summary.stats'
"""
_cmd = 'mri_segstats'
input_spec = SegStatsInputSpec
output_spec = SegStatsOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
if isdefined(self.inputs.summary_file):
outputs['summary_file'] = os.path.abspath(self.inputs.summary_file)
else:
outputs['summary_file'] = os.path.join(os.getcwd(), 'summary.stats')
suffices = dict(avgwf_txt_file='_avgwf.txt', avgwf_file='_avgwf.nii.gz',
sf_avg_file='sfavg.txt')
if isdefined(self.inputs.segmentation_file):
_, src = os.path.split(self.inputs.segmentation_file)
if isdefined(self.inputs.annot):
src = '_'.join(self.inputs.annot)
if isdefined(self.inputs.surf_label):
src = '_'.join(self.inputs.surf_label)
for name, suffix in list(suffices.items()):
value = getattr(self.inputs, name)
if isdefined(value):
if isinstance(value, bool):
outputs[name] = fname_presuffix(src, suffix=suffix,
newpath=os.getcwd(),
use_ext=False)
else:
outputs[name] = os.path.abspath(value)
return outputs
def _format_arg(self, name, spec, value):
if name in ('summary_file', 'avgwf_txt_file'):
if not isinstance(value, bool):
if not os.path.isabs(value):
value = os.path.join('.', value)
if name in ['avgwf_txt_file', 'avgwf_file', 'sf_avg_file']:
if isinstance(value, bool):
fname = self._list_outputs()[name]
else:
fname = value
return spec.argstr % fname
elif name == 'in_intensity':
intensity_name = os.path.basename(self.inputs.in_intensity).replace('.mgz', '')
return spec.argstr % (value, intensity_name)
return super(SegStats, self)._format_arg(name, spec, value)
def _gen_filename(self, name):
if name == 'summary_file':
return self._list_outputs()[name]
return None
class SegStatsReconAllInputSpec(SegStatsInputSpec):
# recon-all input requirements
subject_id = traits.String('subject_id', usedefault=True,
argstr="--subject %s", mandatory=True,
desc="Subject id being processed")
# implicit
ribbon = traits.File(mandatory=True, exists=True,
desc="Input file mri/ribbon.mgz")
presurf_seg = File(exists=True,
desc="Input segmentation volume")
transform = File(mandatory=True, exists=True,
desc="Input transform file")
lh_orig_nofix = File(mandatory=True, exists=True,
desc="Input lh.orig.nofix")
rh_orig_nofix = File(mandatory=True, exists=True,
desc="Input rh.orig.nofix")
lh_white = File(mandatory=True, exists=True,
desc="Input file must be <subject_id>/surf/lh.white")
rh_white = File(mandatory=True, exists=True,
desc="Input file must be <subject_id>/surf/rh.white")
lh_pial = File(mandatory=True, exists=True,
desc="Input file must be <subject_id>/surf/lh.pial")
rh_pial = File(mandatory=True, exists=True,
desc="Input file must be <subject_id>/surf/rh.pial")
aseg = File(exists=True,
desc="Mandatory implicit input in 5.3")
copy_inputs = traits.Bool(desc="If running as a node, set this to True " +
"otherwise, this will copy the implicit inputs " +
"to the node directory.")
class SegStatsReconAll(SegStats):
"""
This class inherits SegStats and modifies it for use in a recon-all workflow.
This implementation mandates implicit inputs that SegStats.
To ensure backwards compatability of SegStats, this class was created.
Examples
========
>>> from nipype.interfaces.freesurfer import SegStatsReconAll
>>> segstatsreconall = SegStatsReconAll()
>>> segstatsreconall.inputs.annot = ('PWS04', 'lh', 'aparc')
>>> segstatsreconall.inputs.avgwf_txt_file = 'avgwf.txt'
>>> segstatsreconall.inputs.summary_file = 'summary.stats'
>>> segstatsreconall.inputs.subject_id = '10335'
>>> segstatsreconall.inputs.ribbon = 'wm.mgz'
>>> segstatsreconall.inputs.transform = 'trans.mat'
>>> segstatsreconall.inputs.presurf_seg = 'wm.mgz'
>>> segstatsreconall.inputs.lh_orig_nofix = 'lh.pial'
>>> segstatsreconall.inputs.rh_orig_nofix = 'lh.pial'
>>> segstatsreconall.inputs.lh_pial = 'lh.pial'
>>> segstatsreconall.inputs.rh_pial = 'lh.pial'
>>> segstatsreconall.inputs.lh_white = 'lh.pial'
>>> segstatsreconall.inputs.rh_white = 'lh.pial'
>>> segstatsreconall.inputs.empty = True
>>> segstatsreconall.inputs.brain_vol = 'brain-vol-from-seg'
>>> segstatsreconall.inputs.exclude_ctx_gm_wm = True
>>> segstatsreconall.inputs.supratent = True
>>> segstatsreconall.inputs.subcort_gm = True
>>> segstatsreconall.inputs.etiv = True
>>> segstatsreconall.inputs.wm_vol_from_surf = True
>>> segstatsreconall.inputs.cortex_vol_from_surf = True
>>> segstatsreconall.inputs.total_gray = True
>>> segstatsreconall.inputs.euler = True
>>> segstatsreconall.inputs.exclude_id = 0
>>> segstatsreconall.cmdline
'mri_segstats --annot PWS04 lh aparc --avgwf ./avgwf.txt --brain-vol-from-seg --surf-ctx-vol --empty --etiv --euler --excl-ctxgmwm --excludeid 0 --subcortgray --subject 10335 --supratent --totalgray --surf-wm-vol --sum ./summary.stats'
"""
input_spec = SegStatsReconAllInputSpec
output_spec = SegStatsOutputSpec
def _format_arg(self, name, spec, value):
if name == 'brainmask_file':
return spec.argstr % os.path.basename(value)
return super(SegStatsReconAll, self)._format_arg(name, spec, value)
def run(self, **inputs):
if self.inputs.copy_inputs:
self.inputs.subjects_dir = os.getcwd()
if 'subjects_dir' in inputs:
inputs['subjects_dir'] = self.inputs.subjects_dir
copy2subjdir(self, self.inputs.lh_orig_nofix,
'surf', 'lh.orig.nofix')
copy2subjdir(self, self.inputs.rh_orig_nofix,
'surf', 'rh.orig.nofix')
copy2subjdir(self, self.inputs.lh_white,
'surf', 'lh.white')
copy2subjdir(self, self.inputs.rh_white,
'surf', 'rh.white')
copy2subjdir(self, self.inputs.lh_pial,
'surf', 'lh.pial')
copy2subjdir(self, self.inputs.rh_pial,
'surf', 'rh.pial')
copy2subjdir(self, self.inputs.ribbon,
'mri', 'ribbon.mgz')
copy2subjdir(self, self.inputs.presurf_seg,
'mri', 'aseg.presurf.mgz')
copy2subjdir(self, self.inputs.aseg,
'mri', 'aseg.mgz')
copy2subjdir(self, self.inputs.transform,
os.path.join('mri', 'transforms'),
'talairach.xfm')
copy2subjdir(self, self.inputs.in_intensity, 'mri')
copy2subjdir(self, self.inputs.brainmask_file, 'mri')
return super(SegStatsReconAll, self).run(**inputs)
class Label2VolInputSpec(FSTraitedSpec):
label_file = InputMultiPath(File(exists=True), argstr='--label %s...',
xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'),
copyfile=False,
mandatory=True,
desc='list of label files')
annot_file = File(exists=True, argstr='--annot %s',
xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'),
requires=('subject_id', 'hemi'),
mandatory=True,
copyfile=False,
desc='surface annotation file')
seg_file = File(exists=True, argstr='--seg %s',
xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'),
mandatory=True,
copyfile=False,
desc='segmentation file')
aparc_aseg = traits.Bool(argstr='--aparc+aseg',
xor=('label_file', 'annot_file', 'seg_file', 'aparc_aseg'),
mandatory=True,
desc='use aparc+aseg.mgz in subjectdir as seg')
template_file = File(exists=True, argstr='--temp %s', mandatory=True,
desc='output template volume')
reg_file = File(exists=True, argstr='--reg %s',
xor=('reg_file', 'reg_header', 'identity'),
desc='tkregister style matrix VolXYZ = R*LabelXYZ')
reg_header = File(exists=True, argstr='--regheader %s',
xor=('reg_file', 'reg_header', 'identity'),
desc='label template volume')
identity = traits.Bool(argstr='--identity',
xor=('reg_file', 'reg_header', 'identity'),
desc='set R=I')
invert_mtx = traits.Bool(argstr='--invertmtx',
desc='Invert the registration matrix')
fill_thresh = traits.Range(0., 1., argstr='--fillthresh %.f',
desc='thresh : between 0 and 1')
label_voxel_volume = traits.Float(argstr='--labvoxvol %f',
desc='volume of each label point (def 1mm3)')
proj = traits.Tuple(traits.Enum('abs', 'frac'), traits.Float,
traits.Float, traits.Float,
argstr='--proj %s %f %f %f',
requires=('subject_id', 'hemi'),
desc='project along surface normal')
subject_id = traits.Str(argstr='--subject %s',
desc='subject id')
hemi = traits.Enum('lh', 'rh', argstr='--hemi %s',
desc='hemisphere to use lh or rh')
surface = traits.Str(argstr='--surf %s',
desc='use surface instead of white')
vol_label_file = File(argstr='--o %s', genfile=True,
desc='output volume')
label_hit_file = File(argstr='--hits %s',
desc='file with each frame is nhits for a label')
map_label_stat = File(argstr='--label-stat %s',
desc='map the label stats field into the vol')
native_vox2ras = traits.Bool(argstr='--native-vox2ras',
desc='use native vox2ras xform instead of tkregister-style')
class Label2VolOutputSpec(TraitedSpec):
vol_label_file = File(exists=True, desc='output volume')
class Label2Vol(FSCommand):
"""Make a binary volume from a Freesurfer label
Examples
--------
>>> binvol = Label2Vol(label_file='cortex.label', template_file='structural.nii', reg_file='register.dat', fill_thresh=0.5, vol_label_file='foo_out.nii')
>>> binvol.cmdline
'mri_label2vol --fillthresh 0 --label cortex.label --reg register.dat --temp structural.nii --o foo_out.nii'
"""
_cmd = 'mri_label2vol'
input_spec = Label2VolInputSpec
output_spec = Label2VolOutputSpec
def _list_outputs(self):
outputs = self.output_spec().get()
outfile = self.inputs.vol_label_file
if not isdefined(outfile):
for key in ['label_file', 'annot_file', 'seg_file']:
if isdefined(getattr(self.inputs, key)):
path = getattr(self.inputs, key)
if isinstance(path, list):
path = path[0]
_, src = os.path.split(path)
if isdefined(self.inputs.aparc_aseg):
src = 'aparc+aseg.mgz'
outfile = fname_presuffix(src, suffix='_vol.nii.gz',
newpath=os.getcwd(),
use_ext=False)
outputs['vol_label_file'] = outfile
return outputs
def _gen_filename(self, name):
if name == 'vol_label_file':
return self._list_outputs()[name]
return None
class MS_LDAInputSpec(FSTraitedSpec):
lda_labels = traits.List(traits.Int(), argstr='-lda %s', mandatory=True,
minlen=2, maxlen=2, sep=' ',
desc='pair of class labels to optimize')
weight_file = traits.File(argstr='-weight %s', mandatory=True,
desc='filename for the LDA weights (input or output)')
vol_synth_file = traits.File(exists=False, argstr='-synth %s',
mandatory=True,
desc=('filename for the synthesized output '
'volume'))
label_file = traits.File(exists=True, argstr='-label %s',
desc='filename of the label volume')
mask_file = traits.File(exists=True, argstr='-mask %s',
desc='filename of the brain mask volume')
shift = traits.Int(argstr='-shift %d',
desc='shift all values equal to the given value to zero')
conform = traits.Bool(argstr='-conform',
desc=('Conform the input volumes (brain mask '
'typically already conformed)'))
use_weights = traits.Bool(argstr='-W',
desc=('Use the weights from a previously '
'generated weight file'))
images = InputMultiPath(File(exists=True), argstr='%s', mandatory=True,
copyfile=False, desc='list of input FLASH images',
position=-1)
class MS_LDAOutputSpec(TraitedSpec):
weight_file = File(exists=True, desc='')
vol_synth_file = File(exists=True, desc='')
class MS_LDA(FSCommand):
"""Perform LDA reduction on the intensity space of an arbitrary # of FLASH images
Examples
--------
>>> grey_label = 2
>>> white_label = 3
>>> zero_value = 1
>>> optimalWeights = MS_LDA(lda_labels=[grey_label, white_label], \
label_file='label.mgz', weight_file='weights.txt', \
shift=zero_value, vol_synth_file='synth_out.mgz', \
conform=True, use_weights=True, \
images=['FLASH1.mgz', 'FLASH2.mgz', 'FLASH3.mgz'])
>>> optimalWeights.cmdline
'mri_ms_LDA -conform -label label.mgz -lda 2 3 -shift 1 -W -synth synth_out.mgz -weight weights.txt FLASH1.mgz FLASH2.mgz FLASH3.mgz'
"""
_cmd = 'mri_ms_LDA'
input_spec = MS_LDAInputSpec
output_spec = MS_LDAOutputSpec
def _list_outputs(self):
outputs = self._outputs().get()
if isdefined(self.inputs.output_synth):
outputs['vol_synth_file'] = os.path.abspath(self.inputs.output_synth)
else:
outputs['vol_synth_file'] = os.path.abspath(self.inputs.vol_synth_file)
if not isdefined(self.inputs.use_weights) or self.inputs.use_weights is False:
outputs['weight_file'] = os.path.abspath(self.inputs.weight_file)
return outputs
def _verify_weights_file_exists(self):
if not os.path.exists(os.path.abspath(self.inputs.weight_file)):
raise traits.TraitError("MS_LDA: use_weights must accompany an existing weights file")
def _format_arg(self, name, spec, value):
if name is 'use_weights':
if self.inputs.use_weights is True:
self._verify_weights_file_exists()
else:
return ''
# TODO: Fix bug when boolean values are set explicitly to false
return super(MS_LDA, self)._format_arg(name, spec, value)
def _gen_filename(self, name):
pass
class Label2LabelInputSpec(FSTraitedSpec):
hemisphere = traits.Enum('lh', 'rh', argstr="--hemi %s", mandatory=True,
desc="Input hemisphere")
subject_id = traits.String('subject_id', usedefault=True,
argstr="--trgsubject %s", mandatory=True,
desc="Target subject")
sphere_reg = File(mandatory=True, exists=True,
desc="Implicit input <hemisphere>.sphere.reg")
white = File(mandatory=True, exists=True,
desc="Implicit input <hemisphere>.white")
source_sphere_reg = File(mandatory=True, exists=True,
desc="Implicit input <hemisphere>.sphere.reg")
source_white = File(mandatory=True, exists=True,
desc="Implicit input <hemisphere>.white")
source_label = File(argstr="--srclabel %s", mandatory=True, exists=True,
desc="Source label")
source_subject = traits.String(argstr="--srcsubject %s", mandatory=True,
desc="Source subject name")
# optional
out_file = File(argstr="--trglabel %s",
name_source=['source_label'], name_template='%s_converted',
hash_files=False, keep_extension=True,
desc="Target label")
registration_method = traits.Enum('surface', 'volume', usedefault=True,
argstr="--regmethod %s", desc="Registration method")
copy_inputs = traits.Bool(desc="If running as a node, set this to True." +
"This will copy the input files to the node " +
"directory.")
class Label2LabelOutputSpec(TraitedSpec):
out_file = File(exists=True, desc='Output label')
class Label2Label(FSCommand):
"""
Converts a label in one subject's space to a label
in another subject's space using either talairach or spherical
as an intermediate registration space.
If a source mask is used, then the input label must have been
created from a surface (ie, the vertex numbers are valid). The
format can be anything supported by mri_convert or curv or paint.
Vertices in the source label that do not meet threshold in the
mask will be removed from the label.
Examples
--------
>>> from nipype.interfaces.freesurfer import Label2Label
>>> l2l = Label2Label()
>>> l2l.inputs.hemisphere = 'lh'
>>> l2l.inputs.subject_id = '10335'
>>> l2l.inputs.sphere_reg = 'lh.pial'
>>> l2l.inputs.white = 'lh.pial'
>>> l2l.inputs.source_subject = 'fsaverage'
>>> l2l.inputs.source_label = 'lh-pial.stl'
>>> l2l.inputs.source_white = 'lh.pial'
>>> l2l.inputs.source_sphere_reg = 'lh.pial'
>>> l2l.cmdline
'mri_label2label --hemi lh --trglabel lh-pial_converted.stl --regmethod surface --srclabel lh-pial.stl --srcsubject fsaverage --trgsubject 10335'
"""
_cmd = 'mri_label2label'
input_spec = Label2LabelInputSpec
output_spec = Label2LabelOutputSpec
def _list_outputs(self):
outputs = self._outputs().get()
outputs['out_file'] = os.path.join(self.inputs.subjects_dir,
self.inputs.subject_id,
'label',
self.inputs.out_file)
return outputs
def run(self, **inputs):
if self.inputs.copy_inputs:
self.inputs.subjects_dir = os.getcwd()
if 'subjects_dir' in inputs:
inputs['subjects_dir'] = self.inputs.subjects_dir
hemi = self.inputs.hemisphere
copy2subjdir(self, self.inputs.sphere_reg, 'surf',
'{0}.sphere.reg'.format(hemi))
copy2subjdir(self, self.inputs.white, 'surf',
'{0}.white'.format(hemi))
copy2subjdir(self, self.inputs.source_sphere_reg, 'surf',
'{0}.sphere.reg'.format(hemi),
subject_id=self.inputs.source_subject)
copy2subjdir(self, self.inputs.source_white, 'surf',
'{0}.white'.format(hemi),
subject_id=self.inputs.source_subject)
# label dir must exist in order for output file to be written
label_dir = os.path.join(self.inputs.subjects_dir,
self.inputs.subject_id,
'label')
if not os.path.isdir(label_dir):
os.makedirs(label_dir)
return super(Label2Label, self).run(**inputs)
class Label2AnnotInputSpec(FSTraitedSpec):
# required
hemisphere = traits.Enum('lh', 'rh',
argstr="--hemi %s", mandatory=True,
desc="Input hemisphere")
subject_id = traits.String('subject_id', usedefault=True,
argstr="--s %s", mandatory=True,
desc="Subject name/ID")
in_labels = traits.List(argstr="--l %s...", mandatory=True,
desc="List of input label files")
out_annot = traits.String(argstr="--a %s", mandatory=True,
desc="Name of the annotation to create")
orig = File(exists=True, mandatory=True,
desc="implicit {hemisphere}.orig")
# optional
keep_max = traits.Bool(argstr="--maxstatwinner",
desc="Keep label with highest 'stat' value")
verbose_off = traits.Bool(argstr="--noverbose",
desc="Turn off overlap and stat override messages")
color_table = File(argstr="--ctab %s", exists=True,
desc="File that defines the structure names, their indices, and their color")
copy_inputs = traits.Bool(desc="copy implicit inputs and create a temp subjects_dir")
class Label2AnnotOutputSpec(TraitedSpec):
out_file = File(exists=True, desc='Output annotation file')
class Label2Annot(FSCommand):
"""
Converts a set of surface labels to an annotation file
Examples
--------
>>> from nipype.interfaces.freesurfer import Label2Annot
>>> l2a = Label2Annot()
>>> l2a.inputs.hemisphere = 'lh'
>>> l2a.inputs.subject_id = '10335'
>>> l2a.inputs.in_labels = ['lh.aparc.label']
>>> l2a.inputs.orig = 'lh.pial'
>>> l2a.inputs.out_annot = 'test'
>>> l2a.cmdline
'mris_label2annot --hemi lh --l lh.aparc.label --a test --s 10335'
"""
_cmd = 'mris_label2annot'
input_spec = Label2AnnotInputSpec
output_spec = Label2AnnotOutputSpec
def run(self, **inputs):
if self.inputs.copy_inputs:
self.inputs.subjects_dir = os.getcwd()
if 'subjects_dir' in inputs:
inputs['subjects_dir'] = self.inputs.subjects_dir
copy2subjdir(self, self.inputs.orig,
folder='surf',
basename='{0}.orig'.format(self.inputs.hemisphere))
# label dir must exist in order for output file to be written
label_dir = os.path.join(self.inputs.subjects_dir,
self.inputs.subject_id,
'label')
if not os.path.isdir(label_dir):
os.makedirs(label_dir)
return super(Label2Annot, self).run(**inputs)
def _list_outputs(self):
outputs = self._outputs().get()
outputs["out_file"] = os.path.join(str(self.inputs.subjects_dir),
str(self.inputs.subject_id),
'label',
str(self.inputs.hemisphere) + '.' + str(self.inputs.out_annot) + '.annot')
return outputs
class SphericalAverageInputSpec(FSTraitedSpec):
out_file = File(argstr="%s", genfile=True, exists=False,
position=-1, desc="Output filename")
in_average = traits.Directory(argstr="%s", exists=True, genfile=True,
position=-2, desc="Average subject")
in_surf = File(argstr="%s", mandatory=True, exists=True,
position=-3, desc="Input surface file")
hemisphere = traits.Enum('lh', 'rh', argstr="%s", mandatory=True,
position=-4, desc="Input hemisphere")
fname = traits.String(argstr="%s", mandatory=True, position=-5,
desc="""Filename from the average subject directory.
Example: to use rh.entorhinal.label as the input label
filename, set fname to 'rh.entorhinal' and which to
'label'. The program will then search for
'{in_average}/label/rh.entorhinal.label'
""")
which = traits.Enum('coords', 'label', 'vals', 'curv', 'area',
argstr="%s", mandatory=True, position=-6, desc="No documentation")
subject_id = traits.String(
argstr="-o %s", mandatory=True, desc="Output subject id")
# optional
erode = traits.Int(argstr="-erode %d", desc="Undocumented")
in_orig = File(argstr="-orig %s", exists=True,
desc="Original surface filename")
threshold = traits.Float(argstr="-t %.1f", desc="Undocumented")
class SphericalAverageOutputSpec(TraitedSpec):
out_file = File(exists=False, desc='Output label')
class SphericalAverage(FSCommand):
"""
This program will add a template into an average surface.
Examples
--------
>>> from nipype.interfaces.freesurfer import SphericalAverage
>>> sphericalavg = SphericalAverage()
>>> sphericalavg.inputs.out_file = 'test.out'
>>> sphericalavg.inputs.in_average = '.'
>>> sphericalavg.inputs.in_surf = 'lh.pial'
>>> sphericalavg.inputs.hemisphere = 'lh'
>>> sphericalavg.inputs.fname = 'lh.entorhinal'
>>> sphericalavg.inputs.which = 'label'
>>> sphericalavg.inputs.subject_id = '10335'
>>> sphericalavg.inputs.erode = 2
>>> sphericalavg.inputs.threshold = 5
>>> sphericalavg.cmdline
'mris_spherical_average -erode 2 -o 10335 -t 5.0 label lh.entorhinal lh pial . test.out'
"""
_cmd = 'mris_spherical_average'
input_spec = SphericalAverageInputSpec
output_spec = SphericalAverageOutputSpec
def _format_arg(self, name, spec, value):
if name == 'in_orig' or name == 'in_surf':
surf = os.path.basename(value)
for item in ['lh.', 'rh.']:
surf = surf.replace(item, '')
return spec.argstr % surf
return super(SphericalAverage, self)._format_arg(name, spec, value)
def _gen_filename(self, name):
if name == 'in_average':
avg_subject = str(self.inputs.hemisphere) + '.EC_average'
avg_directory = os.path.join(self.inputs.subjects_dir, avg_subject)
if not os.path.isdir(avg_directory):
fs_home = os.path.abspath(os.environ.get('FREESURFER_HOME'))
avg_home = os.path.join(fs_home, 'subjects', 'fsaverage')
return avg_subject
elif name == 'out_file':
return self._list_outputs()[name]
else:
return None
def _list_outputs(self):
outputs = self._outputs().get()
if isdefined(self.inputs.out_file):
outputs['out_file'] = os.path.abspath(self.inputs.out_file)
else:
out_dir = os.path.join(
self.inputs.subjects_dir, self.inputs.subject_id, 'label')
if isdefined(self.inputs.in_average):
basename = os.path.basename(self.inputs.in_average)
basename = basename.replace('_', '_exvivo_') + '.label'
else:
basename = str(self.inputs.hemisphere) + '.EC_exvivo_average.label'
outputs['out_file'] = os.path.join(out_dir, basename)
return outputs
|
FCP-INDI/nipype
|
nipype/interfaces/freesurfer/model.py
|
Python
|
bsd-3-clause
| 65,410
|
[
"Gaussian"
] |
921ddce9d271106103a302bd8ca3b0a299243465377a6a28b4c879c098314d89
|
"""
.. _pyvista_demo_ref:
3D Visualization with PyVista
=============================
The example demonstrates the how to use the VTK interface via the
`pyvista library <http://docs.pyvista.org>`__ .
To run this example, you will need to `install pyvista <http://docs.pyvista.org/getting-started/installation.html>`__ .
- contributed by `@banesullivan <https://github.com/banesullivan>`_
Using the inversion result from the example notebook
`plot_laguna_del_maule_inversion.ipynb <http://docs.simpeg.xyz/content/examples/20-published/plot_laguna_del_maule_inversion.html>`_
"""
# sphinx_gallery_thumbnail_number = 2
import os
import tarfile
import discretize
import pyvista as pv
import numpy as np
# Set a documentation friendly plotting theme
pv.set_plot_theme("document")
print("PyVista Version: {}".format(pv.__version__))
###############################################################################
# Download and load data
# ----------------------
#
# In the following we load the :code:`mesh` and :code:`Lpout` that you would
# get from running the laguna-del-maule inversion notebook as well as some of
# the raw data for the topography surface and gravity observations.
# Download Topography and Observed gravity data
url = "https://storage.googleapis.com/simpeg/Chile_GRAV_4_Miller/Chile_GRAV_4_Miller.tar.gz"
downloads = discretize.utils.download(url, overwrite=True)
basePath = downloads.split(".")[0]
# unzip the tarfile
tar = tarfile.open(downloads, "r")
tar.extractall()
tar.close()
# Download the inverted model
f = discretize.utils.download(
"https://storage.googleapis.com/simpeg/laguna_del_maule_slicer.tar.gz",
overwrite=True,
)
tar = tarfile.open(f, "r")
tar.extractall()
tar.close()
# Load the mesh/data
mesh = discretize.load_mesh(os.path.join("laguna_del_maule_slicer", "mesh.json"))
models = {"Lpout": np.load(os.path.join("laguna_del_maule_slicer", "Lpout.npy"))}
###############################################################################
# Create PyVista data objects
# ---------------------------
#
# Here we start making PyVista data objects of all the spatially referenced
# data.
# Get the PyVista dataset of the inverted model
dataset = mesh.to_vtk(models)
dataset.set_active_scalars('Lpout')
###############################################################################
# Load topography points from text file as XYZ numpy array
topo_pts = np.loadtxt("Chile_GRAV_4_Miller/LdM_topo.topo", skiprows=1)
# Create the topography points and apply an elevation filter
topo = pv.PolyData(topo_pts).delaunay_2d().elevation()
###############################################################################
# Load the gravity data from text file as XYZ+attributes numpy array
grav_data = np.loadtxt("Chile_GRAV_4_Miller/LdM_grav_obs.grv", skiprows=1)
print("gravity file shape: ", grav_data.shape)
# Use the points to create PolyData
grav = pv.PolyData(grav_data[:, 0:3])
# Add the data arrays
grav.point_data["comp-1"] = grav_data[:, 3]
grav.point_data["comp-2"] = grav_data[:, 4]
grav.set_active_scalars('comp-1')
###############################################################################
# Plot the topographic surface and the gravity data
p = pv.Plotter()
p.add_mesh(topo, color="grey")
p.add_mesh(
grav, point_size=15, render_points_as_spheres=True,
scalar_bar_args={"title": "Observed Gravtiy Data"}
)
# Use a non-phot-realistic shading technique to show topographic relief
p.enable_eye_dome_lighting()
p.show(window_size=[1024, 768])
###############################################################################
# Visualize Using PyVista
# -----------------------
#
# Here we visualize all the data in 3D!
# Create display parameters for inverted model
dparams = dict(
show_edges=False,
cmap="bwr",
clim=[-0.6, 0.6],
)
# Apply a threshold filter to remove topography
# no arguments will remove the NaN values
dataset_t = dataset.threshold()
# Extract volumetric threshold
threshed = dataset_t.threshold(-0.2, invert=True)
# Create the rendering scene
p = pv.Plotter()
# add a grid axes
p.show_grid()
# Add spatially referenced data to the scene
p.add_mesh(dataset_t.slice("x"), **dparams)
p.add_mesh(dataset_t.slice("y"), **dparams)
p.add_mesh(threshed, **dparams)
p.add_mesh(
topo,
opacity=0.75,
color="grey",
# cmap='gist_earth', clim=[1.7e+03, 3.104e+03],
)
p.add_mesh(grav, cmap="viridis", point_size=15, render_points_as_spheres=True)
# Here is a nice camera position we manually found:
cpos = [
(395020.7332989303, 6039949.0452080015, 20387.583125699253),
(364528.3152860675, 6008839.363092581, -3776.318305935185),
(-0.3423732500124074, -0.34364514928896667, 0.8744647328772646),
]
p.camera_position = cpos
# Render the scene!
p.show(window_size=[1024, 768])
|
simpeg/discretize
|
examples/plot_pyvista_laguna.py
|
Python
|
mit
| 4,800
|
[
"VTK"
] |
ee3023976fae14a728f8a393f77a77e35ad90e5aa0be799c87ffaeb785386eab
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the object filter functions."""
import unittest
from plaso.lib import objectfilter
class DummyObject(object):
def __init__(self, key, value):
setattr(self, key, value)
class HashObject(object):
def __init__(self, hash_value=None):
self.value = hash_value
@property
def md5(self):
return self.value
def __eq__(self, y):
return self.value == y
def __lt__(self, y):
return self.value < y
class Dll(object):
def __init__(self, name, imported_functions=None, exported_functions=None):
self.name = name
self._imported_functions = imported_functions or []
self.num_imported_functions = len(self._imported_functions)
self.exported_functions = exported_functions or []
self.num_exported_functions = len(self.exported_functions)
@property
def imported_functions(self):
for fn in self._imported_functions:
yield fn
class DummyFile(object):
_FILENAME = 'boot.ini'
ATTR1 = 'Backup'
ATTR2 = 'Archive'
HASH1 = '123abc'
HASH2 = '456def'
non_callable_leaf = 'yoda'
def __init__(self):
self.non_callable = HashObject(self.HASH1)
self.non_callable_repeated = [
DummyObject('desmond', ['brotha', 'brotha']),
DummyObject('desmond', ['brotha', 'sista'])]
self.imported_dll1 = Dll('a.dll', ['FindWindow', 'CreateFileA'])
self.imported_dll2 = Dll('b.dll', ['RegQueryValueEx'])
@property
def name(self):
return self._FILENAME
@property
def attributes(self):
return [self.ATTR1, self.ATTR2]
@property
def hash(self):
return [HashObject(self.HASH1), HashObject(self.HASH2)]
@property
def size(self):
return 10
@property
def deferred_values(self):
for v in ['a', 'b']:
yield v
@property
def novalues(self):
return []
@property
def imported_dlls(self):
return [self.imported_dll1, self.imported_dll2]
def Callable(self):
raise RuntimeError(u'This can not be called.')
@property
def float(self):
return 123.9823
class ObjectFilterTest(unittest.TestCase):
def setUp(self):
self.file = DummyFile()
self.filter_imp = objectfilter.LowercaseAttributeFilterImplementation
self.value_expander = self.filter_imp.FILTERS['ValueExpander']
operator_tests = {
objectfilter.Less: [
(True, ['size', 1000]),
(True, ['size', 11]),
(False, ['size', 10]),
(False, ['size', 0]),
(False, ['float', 1.0]),
(True, ['float', 123.9824])],
objectfilter.LessEqual: [
(True, ['size', 1000]),
(True, ['size', 11]),
(True, ['size', 10]),
(False, ['size', 9]),
(False, ['float', 1.0]),
(True, ['float', 123.9823])],
objectfilter.Greater: [
(True, ['size', 1]),
(True, ['size', 9.23]),
(False, ['size', 10]),
(False, ['size', 1000]),
(True, ['float', 122]),
(True, ['float', 1.0])],
objectfilter.GreaterEqual: [
(False, ['size', 1000]),
(False, ['size', 11]),
(True, ['size', 10]),
(True, ['size', 0]),
# Floats work fine too.
(True, ['float', 122]),
(True, ['float', 123.9823]),
# Comparisons works with strings, although it might be a bit silly.
(True, ['name', 'aoot.ini'])],
objectfilter.Contains: [
# Contains works with strings.
(True, ['name', 'boot.ini']),
(True, ['name', 'boot']),
(False, ['name', 'meh']),
# Works with generators.
(True, ['imported_dlls.imported_functions', 'FindWindow']),
# But not with numbers.
(False, ['size', 12])],
objectfilter.Equals: [
(True, ['name', 'boot.ini']),
(False, ['name', 'foobar']),
(True, ['float', 123.9823])],
objectfilter.NotEquals: [
(False, ['name', 'boot.ini']),
(True, ['name', 'foobar']),
(True, ['float', 25])],
objectfilter.InSet: [
(True, ['name', ['boot.ini', 'autoexec.bat']]),
(True, ['name', 'boot.ini']),
(False, ['name', 'NOPE']),
# All values of attributes are within these.
(True, ['attributes', ['Archive', 'Backup', 'Nonexisting']]),
# Not all values of attributes are within these.
(False, ['attributes', ['Executable', 'Sparse']])],
objectfilter.Regexp: [
(True, ['name', '^boot.ini$']),
(True, ['name', 'boot.ini']),
(False, ['name', '^$']),
(True, ['attributes', 'Archive']),
# One can regexp numbers if he's inclined to.
(True, ['size', 0]),
# But regexp doesn't work with lists or generators for the moment.
(False, ['imported_dlls.imported_functions', 'FindWindow'])],
}
def testBinaryOperators(self):
for operator, test_data in self.operator_tests.items():
for test_unit in test_data:
kwargs = {'arguments': test_unit[1],
'value_expander': self.value_expander}
ops = operator(**kwargs)
self.assertEqual(test_unit[0], ops.Matches(self.file))
if hasattr(ops, 'FlipBool'):
ops.FlipBool()
self.assertEqual(not test_unit[0], ops.Matches(self.file))
def testExpand(self):
# Case insensitivity.
values_lowercase = self.value_expander().Expand(self.file, 'size')
values_uppercase = self.value_expander().Expand(self.file, 'Size')
self.assertListEqual(list(values_lowercase), list(values_uppercase))
# Existing, non-repeated, leaf is a value.
values = self.value_expander().Expand(self.file, 'size')
self.assertListEqual(list(values), [10])
# Existing, non-repeated, leaf is iterable.
values = self.value_expander().Expand(self.file, 'attributes')
self.assertListEqual(list(values), [[DummyFile.ATTR1, DummyFile.ATTR2]])
# Existing, repeated, leaf is value.
values = self.value_expander().Expand(self.file, 'hash.md5')
self.assertListEqual(list(values), [DummyFile.HASH1, DummyFile.HASH2])
# Existing, repeated, leaf is iterable.
values = self.value_expander().Expand(
self.file, 'non_callable_repeated.desmond')
self.assertListEqual(
list(values), [['brotha', 'brotha'], ['brotha', 'sista']])
# Now with an iterator.
values = self.value_expander().Expand(self.file, 'deferred_values')
self.assertListEqual([list(value) for value in values], [['a', 'b']])
# Iterator > generator.
values = self.value_expander().Expand(
self.file, 'imported_dlls.imported_functions')
expected = [['FindWindow', 'CreateFileA'], ['RegQueryValueEx']]
self.assertListEqual([list(value) for value in values], expected)
# Non-existing first path.
values = self.value_expander().Expand(self.file, 'nonexistant')
self.assertListEqual(list(values), [])
# Non-existing in the middle.
values = self.value_expander().Expand(self.file, 'hash.mink.boo')
self.assertListEqual(list(values), [])
# Non-existing as a leaf.
values = self.value_expander().Expand(self.file, 'hash.mink')
self.assertListEqual(list(values), [])
# Non-callable leaf.
values = self.value_expander().Expand(self.file, 'non_callable_leaf')
self.assertListEqual(list(values), [DummyFile.non_callable_leaf])
# callable.
values = self.value_expander().Expand(self.file, 'Callable')
self.assertListEqual(list(values), [])
# leaf under a callable. Will return nothing.
values = self.value_expander().Expand(self.file, 'Callable.a')
self.assertListEqual(list(values), [])
def testGenericBinaryOperator(self):
class TestBinaryOperator(objectfilter.GenericBinaryOperator):
values = list()
def Operation(self, x, _):
return self.values.append(x)
# Test a common binary operator.
tbo = TestBinaryOperator(
arguments=['whatever', 0], value_expander=self.value_expander)
self.assertEqual(tbo.right_operand, 0)
self.assertEqual(tbo.args[0], 'whatever')
tbo.Matches(DummyObject('whatever', 'id'))
tbo.Matches(DummyObject('whatever', 'id2'))
tbo.Matches(DummyObject('whatever', 'bg'))
tbo.Matches(DummyObject('whatever', 'bg2'))
self.assertListEqual(tbo.values, ['id', 'id2', 'bg', 'bg2'])
def testContext(self):
self.assertRaises(
objectfilter.InvalidNumberOfOperands, objectfilter.Context,
arguments=['context'], value_expander=self.value_expander)
self.assertRaises(
objectfilter.InvalidNumberOfOperands, objectfilter.Context,
arguments=[
'context', objectfilter.Equals(
arguments=['path', 'value'],
value_expander=self.value_expander),
objectfilter.Equals(
arguments=['another_path', 'value'],
value_expander=self.value_expander)],
value_expander=self.value_expander)
# One imported_dll imports 2 functions AND one imported_dll imports
# function RegQueryValueEx.
arguments = [
objectfilter.Equals(
arguments=['imported_dlls.num_imported_functions', 1],
value_expander=self.value_expander),
objectfilter.Contains(
arguments=['imported_dlls.imported_functions',
'RegQueryValueEx'],
value_expander=self.value_expander)]
condition = objectfilter.AndFilter(arguments=arguments)
# Without context, it matches because both filters match separately.
self.assertEqual(True, condition.Matches(self.file))
arguments = [
objectfilter.Equals(
arguments=['num_imported_functions', 2],
value_expander=self.value_expander),
objectfilter.Contains(
arguments=['imported_functions', 'RegQueryValueEx'],
value_expander=self.value_expander)]
condition = objectfilter.AndFilter(arguments=arguments)
# The same DLL imports 2 functions AND one of these is RegQueryValueEx.
context = objectfilter.Context(arguments=['imported_dlls', condition],
value_expander=self.value_expander)
# With context, it doesn't match because both don't match in the same dll.
self.assertEqual(False, context.Matches(self.file))
# One imported_dll imports only 1 function AND one imported_dll imports
# function RegQueryValueEx.
condition = objectfilter.AndFilter(arguments=[
objectfilter.Equals(
arguments=['num_imported_functions', 1],
value_expander=self.value_expander),
objectfilter.Contains(
arguments=['imported_functions', 'RegQueryValueEx'],
value_expander=self.value_expander)])
# The same DLL imports 1 function AND it's RegQueryValueEx.
context = objectfilter.Context(['imported_dlls', condition],
value_expander=self.value_expander)
self.assertEqual(True, context.Matches(self.file))
# Now test the context with a straight query.
query = u'\n'.join([
'@imported_dlls',
'(',
' imported_functions contains "RegQueryValueEx"',
' AND num_imported_functions == 1',
')'])
filter_ = objectfilter.Parser(query).Parse()
filter_ = filter_.Compile(self.filter_imp)
self.assertEqual(True, filter_.Matches(self.file))
def testRegexpRaises(self):
with self.assertRaises(ValueError):
objectfilter.Regexp(
arguments=['name', 'I [dont compile'],
value_expander=self.value_expander)
def testEscaping(self):
parser = objectfilter.Parser(r'a is "\n"').Parse()
self.assertEqual(parser.args[0], '\n')
# Invalid escape sequence.
parser = objectfilter.Parser(r'a is "\z"')
with self.assertRaises(objectfilter.ParseError):
parser.Parse()
# Can escape the backslash.
parser = objectfilter.Parser(r'a is "\\"').Parse()
self.assertEqual(parser.args[0], '\\')
# Test hexadecimal escaping.
# This fails as it's not really a hex escaped string.
parser = objectfilter.Parser(r'a is "\xJZ"')
with self.assertRaises(objectfilter.ParseError):
parser.Parse()
# Instead, this is what one should write.
parser = objectfilter.Parser(r'a is "\\xJZ"').Parse()
self.assertEqual(parser.args[0], r'\xJZ')
# Standard hex-escape.
parser = objectfilter.Parser(r'a is "\x41\x41\x41"').Parse()
self.assertEqual(parser.args[0], 'AAA')
# Hex-escape + a character.
parser = objectfilter.Parser(r'a is "\x414"').Parse()
self.assertEqual(parser.args[0], r'A4')
# How to include r'\x41'.
parser = objectfilter.Parser(r'a is "\\x41"').Parse()
self.assertEqual(parser.args[0], r'\x41')
def testParse(self):
# Arguments are either int, float or quoted string.
objectfilter.Parser('attribute == 1').Parse()
objectfilter.Parser('attribute == 0x10').Parse()
parser = objectfilter.Parser('attribute == 1a')
with self.assertRaises(objectfilter.ParseError):
parser.Parse()
objectfilter.Parser('attribute == 1.2').Parse()
objectfilter.Parser('attribute == \'bla\'').Parse()
objectfilter.Parser('attribute == "bla"').Parse()
parser = objectfilter.Parser('something == red')
self.assertRaises(objectfilter.ParseError, parser.Parse)
# Can't start with AND.
parser = objectfilter.Parser('and something is \'Blue\'')
with self.assertRaises(objectfilter.ParseError):
parser.Parse()
# Test negative filters.
parser = objectfilter.Parser('attribute not == \'dancer\'')
with self.assertRaises(objectfilter.ParseError):
parser.Parse()
parser = objectfilter.Parser('attribute == not \'dancer\'')
with self.assertRaises(objectfilter.ParseError):
parser.Parse()
parser = objectfilter.Parser('attribute not not equals \'dancer\'')
with self.assertRaises(objectfilter.ParseError):
parser.Parse()
parser = objectfilter.Parser('attribute not > 23')
with self.assertRaises(objectfilter.ParseError):
parser.Parse()
# Need to close braces.
objectfilter.Parser('(a is 3)').Parse()
parser = objectfilter.Parser('(a is 3')
self.assertRaises(objectfilter.ParseError, parser.Parse)
# Need to open braces to close them.
parser = objectfilter.Parser('a is 3)')
self.assertRaises(objectfilter.ParseError, parser.Parse)
# Context Operator alone is not accepted.
parser = objectfilter.Parser('@attributes')
with self.assertRaises(objectfilter.ParseError):
parser.Parse()
# Accepted only with braces.
objectfilter.Parser('@attributes( name is \'adrien\')').Parse()
# Not without them.
parser = objectfilter.Parser('@attributes name is \'adrien\'')
with self.assertRaises(objectfilter.ParseError):
parser.Parse()
# Can nest context operators.
query = '@imported_dlls( @imported_function( name is \'OpenFileA\'))'
objectfilter.Parser(query).Parse()
# Can nest context operators and mix braces without it messing up.
query = '@imported_dlls( @imported_function( name is \'OpenFileA\'))'
parser = objectfilter.Parser(query).Parse()
query = u'\n'.join([
'@imported_dlls',
'(',
' @imported_function',
' (',
' name is "OpenFileA" and ordinal == 12',
' )',
')'])
parser = objectfilter.Parser(query).Parse()
# Mix context and binary operators.
query = u'\n'.join([
'@imported_dlls',
'(',
' @imported_function',
' (',
' name is "OpenFileA"',
' ) AND num_functions == 2',
')'])
parser = objectfilter.Parser(query).Parse()
# Also on the right.
query = u'\n'.join([
'@imported_dlls',
'(',
' num_functions == 2 AND',
' @imported_function',
' (',
' name is "OpenFileA"',
' )',
')'])
# Altogether.
# There's an imported dll that imports OpenFileA AND
# an imported DLL matching advapi32.dll that imports RegQueryValueExA AND
# and it exports a symbol called 'inject'.
query = u'\n'.join([
'@imported_dlls( @imported_function ( name is "OpenFileA" ) )',
'AND',
'@imported_dlls (',
' name regexp "(?i)advapi32.dll"',
' AND @imported_function ( name is "RegQueryValueEx" )',
')',
'AND @exported_symbols(name is "inject")'])
def testCompile(self):
obj = DummyObject('something', 'Blue')
parser = objectfilter.Parser('something == \'Blue\'').Parse()
filter_ = parser.Compile(self.filter_imp)
self.assertEqual(filter_.Matches(obj), True)
parser = objectfilter.Parser('something == \'Red\'').Parse()
filter_ = parser.Compile(self.filter_imp)
self.assertEqual(filter_.Matches(obj), False)
parser = objectfilter.Parser('something == "Red"').Parse()
filter_ = parser.Compile(self.filter_imp)
self.assertEqual(filter_.Matches(obj), False)
obj = DummyObject('size', 4)
parser = objectfilter.Parser('size < 3').Parse()
filter_ = parser.Compile(self.filter_imp)
self.assertEqual(filter_.Matches(obj), False)
parser = objectfilter.Parser('size == 4').Parse()
filter_ = parser.Compile(self.filter_imp)
self.assertEqual(filter_.Matches(obj), True)
query = 'something is \'Blue\' and size not contains 3'
parser = objectfilter.Parser(query).Parse()
filter_ = parser.Compile(self.filter_imp)
self.assertEqual(filter_.Matches(obj), False)
if __name__ == '__main__':
unittest.main()
|
jorik041/plaso
|
tests/lib/objectfilter.py
|
Python
|
apache-2.0
| 17,640
|
[
"Desmond"
] |
28ed359efe23b032d10f228a4ecb090bbdd2d748e90bfd6a65a24455eb3f2521
|
"""
Viewing Stanford 3D Scanning Repository bunny model
"""
# Copyright (c) 2014-2015, Enthought, Inc.
# Standard library imports
import os
from os.path import join
# Enthought library imports
from mayavi import mlab
### Download the bunny data, if not already on disk ############################
if not os.path.exists('bunny.tar.gz'):
# Download the data
try:
from urllib import urlopen
except ImportError:
from urllib.request import urlopen
print("Downloading bunny model, Please Wait (3MB)")
opener = urlopen(
'http://graphics.stanford.edu/pub/3Dscanrep/bunny.tar.gz')
open('bunny.tar.gz', 'wb').write(opener.read())
# Extract the data
import tarfile
bunny_tar_file = tarfile.open('bunny.tar.gz')
try:
os.mkdir('bunny_data')
except:
pass
bunny_tar_file.extractall('bunny_data')
bunny_tar_file.close()
# Path to the bunny ply file
bunny_ply_file = join('bunny_data', 'bunny', 'reconstruction', 'bun_zipper.ply')
# Render the bunny ply file
mlab.pipeline.surface(mlab.pipeline.open(bunny_ply_file))
mlab.show()
import shutil
shutil.rmtree('bunny_data')
|
dmsurti/mayavi
|
examples/mayavi/mlab/bunny.py
|
Python
|
bsd-3-clause
| 1,125
|
[
"Mayavi"
] |
0157b2dca2658ba4974aca83ce441484956032117a806a59ccbfec71affc6d8f
|
from setuptools import setup, find_packages
__version__ = eval(open('mitty/version.py').read().split('=')[1])
setup(
name='mitty',
version=__version__,
description='Simulator for genomic data',
author='Seven Bridges Genomics',
author_email='kaushik.ghose@sbgenomics.com',
packages=find_packages(include=['mitty*']),
include_package_data=True,
entry_points={
# Register the built in plugins
'mitty.plugins.sfs': ['double_exp = mitty.plugins.site_frequency.double_exp'],
'mitty.plugins.variants': ['snp = mitty.plugins.variants.snp_plugin',
'delete = mitty.plugins.variants.delete_plugin',
'uniformdel = mitty.plugins.variants.uniform_deletions',
'uniformins = mitty.plugins.variants.uniform_insertions',
'insert = mitty.plugins.variants.insert_plugin',
#'inversion = mitty.plugins.variants.inversion_plugin',
#'low_entropy_insert = mitty.plugins.variants.low_entropy_insert_plugin'
],
'mitty.plugins.population': ['standard = mitty.plugins.population.standard',
'vn = mitty.plugins.population.vn'],
'mitty.plugins.reads': ['simple_sequential = mitty.plugins.reads.simple_sequential_plugin',
'simple_illumina = mitty.plugins.reads.simple_illumina_plugin'],
# Command line scripts
'console_scripts': ['genomes = mitty.genomes:cli',
'reads = mitty.reads:cli',
'perfectbam = mitty.benchmarking.perfectbam:cli',
'badbams = mitty.benchmarking.badbams:cli',
'alindel = mitty.benchmarking.indel_alignment_accuracy:cli',
'benchsummary = mitty.benchmarking.benchmark_summary:cli',
'vcf2pop = mitty.lib.vcf2pop:cli',
'bam2tfq = mitty.benchmarking.convert_bam_to_truth_fastq:cli',
'alindel_plot = mitty.benchmarking.indel_alignment_accuracy_plot:cli',
'misplot = mitty.benchmarking.misalignment_plot:cli',
'acubam = mitty.benchmarking.bam_accuracy:cli',
'migratedb = mitty.util.db_migrate:cli',
'plot_gc_bias = mitty.util.plot_gc_bias:cli',
'splitta = mitty.util.splitta:cli',
'kmers = mitty.util.kmers:cli',
'pybwa = mitty.util.pybwa:cli']
},
install_requires=[
'cython',
'setuptools>=11.0.0',
'numpy>=1.9.0',
'docopt>=0.6.2',
'click>=3.3',
'pysam>=0.8.1',
'h5py>=2.5.0',
'matplotlib>=1.3.0',
'scipy'
],
)
|
latticelabs/Mitty
|
setup.py
|
Python
|
gpl-2.0
| 2,920
|
[
"pysam"
] |
72cc7e2fec7f17fbe68aefe1f1c1cc87d252f172269188a456e6155ea07bf7b1
|
'''
Created on 23/11/2009
@author: brian
'''
from scipysim.actors import MakeChans, CompositeActor
from scipysim.actors.signal import Ramp, Delay, RandomSource
from scipysim.actors.math import Summer
from scipysim.actors.display import Plotter
import logging
logging.basicConfig(level=logging.DEBUG)
logging.info("Logger enabled")
class DelayedRampSum(CompositeActor):
'''Delaying an input (by an integer timestep ) to the multi input summer.'''
def __init__(self, res=10, simulation_length=40):
super(DelayedRampSum, self).__init__()
conns = MakeChans(5)
src1 = Ramp(conns[0], resolution=res, simulation_time=simulation_length)
src2 = Ramp(conns[1], resolution=res, simulation_time=simulation_length)
src3 = RandomSource(conns[2], resolution=res, simulation_time=simulation_length)
# The following "magic number" is one time step, (1/res)
# the delay must be an integer factor of this so the events line up
# for the summer block to work...
time_step = 1.0 / res
delay1 = Delay(conns[1], conns[4], 3 * time_step)
summer = Summer([conns[0], conns[4], conns[2]], conns[3])
dst = Plotter(conns[3])
self.components = [src1, src2, src3, summer, dst, delay1]
if __name__ == '__main__':
DelayedRampSum().run()
|
hardbyte/scipy-sim
|
scipysim/models/multiple_delayed_sum_ramp_plot.py
|
Python
|
gpl-3.0
| 1,333
|
[
"Brian"
] |
d13de7ee74b54f6514c5566bd17bce82395be74173aeacebeb8c8e2f7dbe4c32
|
import cgi
import os
import datetime
import HTMLParser
import json
import logging
import re
import ushlex as shlex
import urllib
from urlparse import urlparse
from bson.objectid import ObjectId
from django.conf import settings
from django.contrib.auth.signals import user_logged_in
#from django.contrib.auth import login as user_login
from django.middleware.csrf import rotate_token
from django.contrib.auth import authenticate
from django.contrib.auth import login as user_login
# we implement django.contrib.auth.login as user_login in here to accomodate mongoengine/pymongo
try:
from django.urls import reverse, resolve, get_script_prefix
except ImportError:
from django.core.urlresolvers import reverse, resolve, get_script_prefix
from django.http import HttpResponse
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.html import escape as html_escape
from django.utils.http import urlencode, urlunquote, is_safe_url
try:
from mongoengine.base import ValidationError
except ImportError:
from mongoengine.errors import ValidationError
from operator import itemgetter
from crits.config.config import CRITsConfig
from crits.core.audit import AuditLog
from crits.core.bucket import Bucket
from crits.core.class_mapper import class_from_id, class_from_type, key_descriptor_from_obj_type
from crits.core.crits_mongoengine import Action, Releasability, json_handler
from crits.core.crits_mongoengine import CritsSourceDocument
from crits.core.crits_mongoengine import EmbeddedPreferredAction
from crits.core.source_access import SourceAccess
from crits.core.data_tools import create_zip, format_file
from crits.core.mongo_tools import mongo_connector, get_file
from crits.core.role import Role
from crits.core.sector import Sector
from crits.core.user import CRITsUser, EmbeddedSubscriptions
from crits.core.user import EmbeddedLoginAttempt
from crits.core.user_tools import user_sources
from crits.core.user_tools import save_user_secret
from crits.core.user_tools import get_user_email_notification
from crits.core.user_tools import get_acl_object
from crits.actors.actor import Actor
from crits.backdoors.backdoor import Backdoor
from crits.campaigns.campaign import Campaign
from crits.certificates.certificate import Certificate
from crits.comments.comment import Comment
from crits.domains.domain import Domain
from crits.events.event import Event
from crits.exploits.exploit import Exploit
from crits.ips.ip import IP
from crits.notifications.handlers import get_user_notifications, generate_audit_notification
from crits.pcaps.pcap import PCAP
from crits.raw_data.raw_data import RawData
from crits.emails.email import Email
from crits.samples.sample import Sample
from crits.screenshots.screenshot import Screenshot
from crits.signatures.signature import Signature
from crits.targets.target import Target
from crits.indicators.indicator import Indicator
from crits.core.totp import valid_totp
from crits.vocabulary.acls import *
logger = logging.getLogger(__name__)
def action_add(type_, id_, tlo_action, user=None, **kwargs):
"""
Add an action to a TLO.
:param type_: The class type of the top level object.
:type type_: str
:param id_: The ObjectId of the to level object to update.
:type id_: str
:param tlo_action: The information about the action.
:type tlo_action: dict
:returns: dict with keys:
"success" (boolean),
"message" (str) if failed,
"object" (dict) if successful.
"""
obj_class = class_from_type(type_)
if not obj_class:
return {'success': False,
'message': 'Not a valid type: %s' % type_}
if type_ != "Campaign":
sources = user_sources(user)
obj = obj_class.objects(id=id_,
source__name__in=sources).first()
else:
obj = obj_class.objects(id=id_).first()
if not obj:
return {'success': False,
'message': 'Could not find TLO'}
try:
tlo_action = datetime_parser(tlo_action)
tlo_action['analyst'] = user.username
obj.add_action(tlo_action['action_type'],
tlo_action['active'],
tlo_action['analyst'],
tlo_action['begin_date'],
tlo_action['end_date'],
tlo_action['performed_date'],
tlo_action['reason'],
date = datetime.datetime.now())
obj.save(username=user)
return {'success': True, 'object': tlo_action}
except (ValidationError, TypeError, KeyError), e:
return {'success': False, 'message': e}
def action_remove(type_, id_, date, action_type, user, **kwargs):
"""
Remove an action from a TLO.
:param type_: The class type of the top level object.
:type type_: str
:param id_: The ObjectId of the TLO to remove an action from.
:type id_: str
:param date: The date of the action to remove.
:type date: datetime.datetime
:param action_type: The name of the action to remove.
:type action_type: str
:param analyst: The user removing the action.
:type analyst: str
:returns: dict with keys "success" (boolean) and "message" (str) if failed.
"""
obj_class = class_from_type(type_)
if not obj_class:
return {'success': False,
'message': 'Not a valid type: %s' % type_}
if type_ != "Campaign":
sources = user_sources(user)
obj = obj_class.objects(id=id_,
source__name__in=sources).first()
else:
obj = obj_class.objects(id=id_).first()
if not obj:
return {'success': False,
'message': 'Could not find TLO'}
try:
date = datetime_parser(date)
obj.delete_action(date, action_type)
obj.save(username=user)
return {'success': True}
except (ValidationError, TypeError), e:
return {'success': False, 'message': e}
def action_update(type_, id_, tlo_action, user=None, **kwargs):
"""
Update an action for a TLO.
:param type_: The class type of the top level object.
:type type_: str
:param id_: The ObjectId of the top level object to update.
:type id_: str
:param tlo_action: The information about the action.
:type tlo_action: dict
:returns: dict with keys:
"success" (boolean),
"message" (str) if failed,
"object" (dict) if successful.
"""
obj_class = class_from_type(type_)
if not obj_class:
return {'success': False,
'message': 'Not a valid type: %s' % type_}
if type_ != "Campaign":
sources = user_sources(user)
obj = obj_class.objects(id=id_,
source__name__in=sources).first()
else:
obj = obj_class.objects(id=id_).first()
if not obj:
return {'success': False,
'message': 'Could not find TLO'}
try:
tlo_action = datetime_parser(tlo_action)
tlo_action['analyst'] = user
obj.edit_action(tlo_action['action_type'],
tlo_action['active'],
tlo_action['analyst'],
tlo_action['begin_date'],
tlo_action['end_date'],
tlo_action['performed_date'],
tlo_action['reason'],
tlo_action['date'])
obj.save(username=user)
return {'success': True, 'object': tlo_action}
except (ValidationError, TypeError), e:
return {'success': False, 'message': e}
def description_update(type_, id_, description, user, **kwargs):
"""
Change the description of a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param description: The description to use.
:type description: str
:param user: The user setting the description.
:type user: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
klass = class_from_type(type_)
if not klass:
return {'success': False, 'message': 'Could not find object.'}
if hasattr(klass, 'source'):
sources = user_sources(user)
obj = klass.objects(id=id_, source__name__in=sources).first()
else:
obj = klass.objects(id=id_).first()
if not obj:
return {'success': False, 'message': 'Could not find object.'}
# Have to unescape the submitted data. Use unescape() to escape
# < and friends. Use urllib2.unquote() to escape %3C and friends.
h = HTMLParser.HTMLParser()
description = h.unescape(description)
try:
obj.description = description
obj.save(username=user)
return {'success': True, 'message': "Description set."}
except ValidationError, e:
return {'success': False, 'message': e}
def data_update(type_, id_, data, analyst):
"""
Change the data of a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param data: The data to use.
:type data: str
:param analyst: The user setting the description.
:type analyst: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
klass = class_from_type(type_)
if not klass:
return {'success': False, 'message': 'Could not find object.'}
if hasattr(klass, 'source'):
sources = user_sources(analyst)
obj = klass.objects(id=id_, source__name__in=sources).first()
else:
obj = klass.objects(id=id_).first()
if not obj:
return {'success': False, 'message': 'Could not find object.'}
# Have to unescape the submitted data. Use unescape() to escape
# < and friends. Use urllib2.unquote() to escape %3C and friends.
h = HTMLParser.HTMLParser()
data = h.unescape(data)
try:
obj.data = data
obj.save(username=analyst)
return {'success': True, 'message': "Data set."}
except ValidationError, e:
return {'success': False, 'message': e}
def get_favorites(analyst):
"""
Get all favorites for a user.
:param analyst: The username.
:type analyst: str
:returns: dict with keys "success" (boolean) and "results" (string)
"""
user = CRITsUser.objects(username=analyst).first()
if not user:
return {'success': False, 'message': '<div id="favorites_results">Could not find user.</div>'}
favorites = user.favorites.to_dict()
if not favorites:
return {'success': True, 'message': '<div id="favorites_results">You have no favorites.</div>'}
field_dict = {
'Actor': 'name',
'Backdoor': 'name',
'Campaign': 'name',
'Certificate': 'filename',
'Comment': 'object_id',
'Domain': 'domain',
'Email': 'id',
'Event': 'title',
'Exploit': 'name',
'Indicator': 'id',
'IP': 'ip',
'PCAP': 'filename',
'RawData': 'title',
'Sample': 'filename',
'Screenshot': 'id',
'Signature': 'title',
'Target': 'email_address'
}
results = '''
<table>
<tbody>
'''
for type_, attr in field_dict.iteritems():
if type_ in favorites:
ids = [ObjectId(s) for s in favorites[type_]]
objs = class_from_type(type_).objects(id__in=ids).only(attr)
for obj in objs:
obj_attr = getattr(obj, attr)
results += '<tr><td>%s</td><td><a href="%s">%s</a></td>' % (type_,
reverse('crits-core-views-details',
args=(type_, str(obj.id))),
obj_attr)
results += '<td><span class="ui-icon ui-icon-trash remove_favorite favorites_icon_active" '
results += 'data-type="%s" data-id="%s"></span></td><td width="5px"></td></tr>' % (type_, str(obj.id))
results += '</tbody></table>'
return {'success': True, 'results': results}
def favorite_update(type_, id_, analyst):
"""
Toggle the favorite of a top-level object in a user profile on or off.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param analyst: The user toggling the favorite.
:type analyst: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
user = CRITsUser.objects(username=analyst).first()
if not user:
return {'success': False, 'message': 'Could not find user.'}
if id_ in user.favorites[type_]:
user.favorites[type_].remove(id_)
else:
user.favorites[type_].append(id_)
try:
user.save()
except:
pass
return {'success': True}
def status_update(type_, id_, value="In Progress", user=None, **kwargs):
"""
Update the status of a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param value: The status to set it to.
:type value: str
:param user: The user setting the status.
:type user: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
obj = class_from_id(type_, id_)
if not obj:
return {'success': False, 'message': 'Could not find object.'}
try:
obj.set_status(value)
# Check to see if the set_status was successful or not.
if obj.status != value:
return {'success': False, 'message': 'Invalid status: %s.' % value }
obj.save(username=user)
return {'success': True, 'value': value}
except ValidationError, e:
return {'success': False, 'message': e}
def get_data_for_item(item_type, item_id):
"""
Get a minimal amount of data for the passed item.
Used by the clipboard to provide selected item information.
:param item_type: Item type (Domain, Indicator, etc...)
:type item_type: str
:param item_id: Item database ID (_id)
:type item_id: str
:returns: dict -- Contains the item data
"""
type_to_fields = {
'Actor': ['name', ],
'Backdoor': ['name', ],
'Campaign': ['name', ],
'Certificate': ['filename', ],
'Domain': ['domain', ],
'Email': ['from_address', 'date', ],
'Event': ['title', 'event_type', ],
'Exploit': ['name', 'cve', ],
'Indicator': ['value', 'ind_type', ],
'IP': ['ip', 'type', ],
'PCAP': ['filename', ],
'RawData': ['title', ],
'Sample': ['filename', ],
'Signature': ['title', ],
'Target': ['email_address', ],
}
response = {'OK': 0, 'Msg': ''}
if not item_id or not item_type:
response['Msg'] = "No item data provided"
return response
if not item_type in type_to_fields:
response['Msg'] = "Invalid item type: %s" % item_type
return response
doc = class_from_id(item_type, item_id)
if not doc:
response['Msg'] = "Item not found"
return response
response['OK'] = 1
response['data'] = {}
for field in type_to_fields[item_type]:
if field in doc:
value = doc[field]
if len(value) > 30:
saved = value
value = saved[:15]
value += '...'
value += saved[-15:]
response['data'][field.title()] = value
return response
def add_releasability(type_, id_, name, user, **kwargs):
"""
Add releasability to a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param name: The source to add releasability for.
:type name: str
:param user: The user adding the releasability.
:type user: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
obj = class_from_id(type_, id_)
if not obj:
return {'success': False,
'message': "Could not find object."}
try:
obj.add_releasability(name=name, analyst=user, instances=[])
obj.save(username=user)
obj.reload()
return {'success': True,
'obj': obj.to_dict()['releasability']}
except Exception, e:
return {'success': False,
'message': "Could not add releasability: %s" % e}
def add_releasability_instance(type_, _id, name, analyst, note=None):
"""
Add releasability instance to a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param name: The source to add releasability instance for.
:type name: str
:param analyst: The user adding the releasability instance.
:type analyst: str
:param note: Optional note about this instance.
:type note: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
obj = class_from_id(type_, _id)
if not obj:
return {'success': False,
'message': "Could not find object."}
try:
date = datetime.datetime.now()
ri = Releasability.ReleaseInstance(analyst=analyst, date=date, note=note)
obj.add_releasability_instance(name=name, instance=ri)
obj.save(username=analyst)
obj.reload()
return {'success': True,
'obj': obj.to_dict()['releasability']}
except Exception, e:
return {'success': False,
'message': "Could not add releasability instance: %s" % e}
def remove_releasability_instance(type_, _id, name, date, analyst):
"""
Remove releasability instance from a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param name: The source to remove releasability instance from.
:type name: str
:param date: The date of the instance being removed.
:type date: datetime.datetime
:param analyst: The user removing the releasability instance.
:type analyst: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
obj = class_from_id(type_, _id)
if not obj:
return {'success': False,
'message': "Could not find object."}
try:
obj.remove_releasability_instance(name=name, date=date)
obj.save(username=analyst)
obj.reload()
return {'success': True,
'obj': obj.to_dict()['releasability']}
except Exception, e:
return {'success': False,
'message': "Could not remove releasability instance: %s" % e}
def remove_releasability(type_, _id, name, analyst):
"""
Remove releasability from a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param name: The source to remove from releasability.
:type name: str
:param analyst: The user removing the releasability.
:type analyst: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
obj = class_from_id(type_, _id)
if not obj:
return {'success': False,
'message': "Could not find object."}
try:
obj.remove_releasability(name=name)
obj.save(username=analyst)
obj.reload()
return {'success': True,
'obj': obj.to_dict()['releasability']}
except Exception, e:
return {'success': False,
'message': "Could not remove releasability: %s" % e}
def sanitize_releasability(releasability, user_sources):
"""
Remove any releasability that is for sources a user does not have access to
see.
:param releasability: The releasability list for a top-level object.
:type releasability: list
:param user_sources: The sources a user has access to.
:type user_sources: list
:returns: list
"""
# currently this uses dictionary lookups.
# when we move to classes, this should use attributes
return [r for r in releasability if r['name'] in user_sources]
def ui_themes():
"""
Return a list of available UI themes.
:returns: list
"""
ui_themes = os.listdir(os.path.join(settings.MEDIA_ROOT,
'css/jquery-themes'))
return ui_themes
def does_source_exist(source, active=False):
"""
Determine if a source exists.
:param source: The name of the source to search for.
:type source: str
:param active: Whether the source also needs to be marked as active or not.
:type active: boolean
:returns: True, False
"""
query = {'name': source}
if active:
query['active'] = 'on'
if len(SourceAccess.objects(__raw__=query)) > 0:
return True
else:
return False
def add_new_source(source, analyst):
"""
Add a new source to CRITs.
:param source: The name of the new source.
:type source: str
:param analyst: The user adding the new source.
:type analyst: str
:returns: True, False
"""
try:
source = source.strip()
src = SourceAccess.objects(name=source).first()
if src:
return False
src = SourceAccess()
src.name = source
src.save(username=analyst)
r = Role.objects(name=settings.ADMIN_ROLE).first()
if r:
r.add_source(source,
read=True,
write=True,
tlp_green=True,
tlp_red=True,
tlp_amber=True)
r.save()
return True
except ValidationError:
return False
def merge_source_lists(left, right):
"""
Merge source lists takes two source list objects and merges them together.
Left can be an empty list and it will set the list to be the right list for
you. We will always return the left list.
:param left: Source list one.
:type left: list
:param right: Source list two.
:type right: list
:returns: list
"""
if left is None:
return right
elif len(left) < 1:
return right
else:
#if two sources have the same name and same date, we can assume they're
# the same instance
left_name_dates = {}
for i in left:
left_name_dates[i['name']] = [inst['date'] for inst in i['instances']]
for src in right:
match = False
for s in left:
if src['name'] == s['name']:
match = True
left_dates = left_name_dates[s['name']]
for i in src['instances']:
if i['date'] not in left_dates:
s['instances'].append(i)
if not match:
left.append(src)
return left
def source_add_update(type_, id_, action_type, source, method='',
reference='', tlp=None, date=None, user=None, **kwargs):
"""
Add or update a source for a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param obj_id: The ObjectId to search for.
:type obj_id: str
:param action_type: Whether or not we are doing an "add" or "update".
:type action_type: str
:param source: The name of the source.
:type source: str
:param method: The method of data acquisition for the source.
:type method: str
:param reference: The reference to the data for the source.
:type reference: str
:param tlp: The TLP level from this source.
:type tlp: str
:param date: The date of the instance to add/update.
:type date: datetime.datetime
:param user: The user performing the add/update.
:type user: str
:returns: dict with keys:
"success" (boolean),
"message" (str),
"object" (if successful)
:class:`crits.core.crits_mongoengine.EmbeddedSource.SourceInstance`
"""
obj = class_from_id(type_, id_)
if not obj:
return {'success': False,
'message': 'Unable to find object in database.'}
try:
date = datetime_parser(date)
if action_type == "add":
obj.add_source(source=source,
method=method,
reference=reference,
date=date,
tlp=tlp,
analyst=user)
else:
obj.edit_source(source=source,
method=method,
reference=reference,
date=date,
tlp=tlp,
analyst=user)
obj.save(username=user)
obj.reload()
obj.sanitize_sources(username=user)
if not obj.source:
return {'success': False,
'message': 'Object has no sources.'}
for s in obj.source:
if s.name == source:
if action_type == "add":
return {'success': True,
'object': s,
'message': "Source addition successful!"}
else:
for i in s.instances:
if i.date == date:
return {'success': True,
'object': s,
'instance': i,
'message': "Source addition successful!"}
break
return {'success': False,
'message': ('Could not make source changes. '
'Refresh page and try again.')}
except (ValidationError, TypeError), e:
return {'success':False, 'message': e}
def source_remove(type_, id_, name, date, user=None, **kwargs):
"""
Remove a source instance from a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param name: The name of the source.
:type name: str
:param date: The date of the instance to remove.
:type date: datetime.datetime
:param user: The user performing the removal.
:type user: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
obj = class_from_id(type_, id_)
if not obj:
return {'success': False,
'message': 'Unable to find object in database.'}
try:
date = datetime_parser(date)
result = obj.remove_source(source=name,
date=date)
obj.save(username=user)
return result
except (ValidationError, TypeError), e:
return {'success':False, 'message': e}
def source_remove_all(obj_type, obj_id, name, analyst=None):
"""
Remove a source from a top-level object.
:param obj_type: The CRITs type of the top-level object.
:type obj_type: str
:param obj_id: The ObjectId to search for.
:type obj_id: str
:param name: The name of the source.
:type name: str
:param analyst: The user performing the removal.
:type analyst: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
obj = class_from_id(obj_type, obj_id)
if not obj:
return {'success': False,
'message': 'Unable to find object in database.'}
try:
result = obj.remove_source(source=name,
remove_all=True)
obj.save(username=analyst)
return result
except ValidationError, e:
return {'success':False, 'message': e}
def get_sources(obj_type, obj_id, analyst):
"""
Get a list of sources for a top-level object.
:param obj_type: The CRITs type of the top-level object.
:type obj_type: str
:param obj_id: The ObjectId to search for.
:type obj_id: str
:param analyst: The user performing the search.
:type analyst: str
:returns: list if successful or dict with keys "success" (boolean) and
"message" (str)
"""
obj = class_from_id(obj_type, obj_id)
if not obj:
return {'success': False,
'message': 'Unable to find object in database.'}
obj.sanitize_sources(username=analyst)
return obj.source
def get_source_names(active=False, limited=False, username=None):
"""
Get a list of available sources in CRITs sorted alphabetically.
:param active: Whether or not the sources returned should be active.
:type active: boolean
:param limited: If the sources should be limited to only those the user has
access to.
:type limited: boolean
:param username: The user requesting the source list.
:type username: str
:returns: list
"""
query = {}
if limited:
user_src_list = user_sources(username)
query["name"] = {'$in': user_src_list}
if active:
query['active'] = 'on'
c = SourceAccess.objects(__raw__=query).order_by('+name')
return c
def get_action_types_for_tlo(obj_type):
final = []
if obj_type is not None:
for a in Action.objects(object_types=obj_type,
active='on').order_by("+name"):
final.append(a.name)
return final
def get_item_names(obj, active=None, user=None):
"""
Get a list of item names for a specific item in CRITs.
:param obj: The class representing the item to get names for.
:type obj: class
:param active: Return:
None: active and inactive items.
True: active items.
False: inactive items.
:type active: boolean
:returns: :class:`crits.core.crits_mongoengine.CritsQuerySet`
"""
# Don't use this to get sources.
if isinstance(obj, SourceAccess):
return []
if active is None:
c = obj.objects().order_by('+name')
else:
if active:
c = obj.objects(active='on').order_by('+name')
else:
c = obj.objects(active='off').order_by('+name')
return c
def promote_bucket_list(bucket, confidence, name, related, description, analyst):
"""
Promote a bucket to a Campaign. Every top-level object which is tagged with
this specific bucket will get attributed to the provided campaign.
:param bucket: The bucket to promote.
:type bucket: str
:param confidence: The Campaign confidence.
:type confidence: str
:param name: The Campaign name.
:type name: str
:param related: If we should extend this attribution to top-level objects
related to these top-level objects.
:type related: boolean
:param description: A description of this Campaign attribution.
:type description: str
:param analyst: The user promoting this bucket.
:type analyst: str
:returns: dict with keys "success" (boolean) and "message" (str)
"""
from crits.campaigns.handlers import campaign_add
bucket = Bucket.objects(name=bucket).first()
if not bucket:
return {'success': False, 'message': 'Unable to find bucket.'}
for ctype in [k for k in Bucket._meta['schema_doc'].keys() if k != 'name' and k != 'Campaign']:
# Don't bother if the count for this type is 0
if getattr(bucket, ctype, 0) == 0:
continue
klass = class_from_type(ctype)
if not klass:
continue
objs = klass.objects(bucket_list=bucket.name)
for obj in objs:
campaign_add(name, confidence, description, related, analyst, obj=obj)
return {'success': True,
'message': 'Bucket successfully promoted. <a href="%s">View campaign.</a>' % reverse('crits-campaigns-views-campaign_details', args=(name,))}
def alter_bucket_list(obj, buckets, val):
"""
Given a list of buckets on this object, increment or decrement
the bucket_list objects accordingly. This is used when adding
or removing a bucket list to an item, and when deleting an item.
:param obj: The top-level object instantiated class.
:type obj: class which inherits from
:class:`crits.core.crits_mongoengine.CritsBaseAttributes`.
:param buckets: List of buckets.
:type buckets: list
:param val: The amount to change the count by.
:type val: int
"""
# This dictionary is used to set values on insert only.
# I haven't found a way to get mongoengine to use the defaults
# when doing update_one() on the queryset.
from crits.core.bucket import Bucket
soi = { k: 0 for k in Bucket._meta['schema_doc'].keys() if k != 'name' and k != obj._meta['crits_type'] }
soi['schema_version'] = Bucket._meta['latest_schema_version']
# We are using mongo_connector here because mongoengine does not have
# support for a setOnInsert option. If mongoengine were to gain support
# for this we should switch to using it instead of pymongo here.
buckets_col = mongo_connector(settings.COL_BUCKET_LISTS)
for name in buckets:
buckets_col.update({'name': name},
{'$inc': {obj._meta['crits_type']: val},
'$setOnInsert': soi},
upsert=True)
# Find and remove this bucket if, and only if, all counts are zero.
if val == -1:
Bucket.objects(name=name,
Actor=0,
Backdoor=0,
Campaign=0,
Certificate=0,
Domain=0,
Email=0,
Event=0,
Exploit=0,
Indicator=0,
IP=0,
PCAP=0,
RawData=0,
Sample=0,
Signature=0,
Target=0).delete()
def generate_bucket_csv(request):
"""
Generate CSV output for the Bucket list.
:param request: The request for this CSV.
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
return csv_export(request, Bucket)
def generate_bucket_jtable(request, option):
"""
Generate the jtable data for rendering in the bucket list template.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param option: Action to take.
:type option: str of either 'jtlist', 'jtdelete', or 'inline'.
:returns: :class:`django.http.HttpResponse`
"""
if option == 'jtlist':
details_url = 'crits-core-views-bucket_list'
details_key = 'name'
response = jtable_ajax_list(Bucket,
details_url,
details_key,
request,
includes=['name',
'Actor',
'Backdoor',
'Campaign',
'Certificate',
'Domain',
'Email',
'Event',
'Exploit',
'Indicator',
'IP',
'PCAP',
'RawData',
'Sample',
'Signature',
'Target'])
return HttpResponse(json.dumps(response, default=json_handler),
content_type='application/json')
fields = ['name', 'Actor', 'Backdoor', 'Campaign', 'Certificate', 'Domain',
'Email', 'Event', 'Exploit', 'Indicator', 'IP', 'PCAP', 'RawData',
'Sample', 'Signature', 'Target', 'Promote']
jtopts = {'title': 'Buckets',
'fields': fields,
'listurl': 'jtlist',
'searchurl': reverse('crits-core-views-global_search_listing'),
'default_sort': 'name ASC',
'no_sort': ['Promote'],
'details_link': ''}
jtable = build_jtable(jtopts, request)
for ctype in fields:
if ctype == 'id':
continue
elif ctype == 'name':
url = reverse('crits-core-views-global_search_listing') + '?search_type=bucket_list&search=Search&force_full=1'
elif ctype == 'Promote':
url = reverse('crits-core-views-bucket_promote')
else:
lower = ctype.lower()
if lower != "rawdata":
url = reverse('crits-%ss-views-%ss_listing' % (lower, lower))
else:
lower = "raw_data"
url = reverse('crits-%s-views-%s_listing' % (lower, lower))
for field in jtable['fields']:
if field['fieldname'].startswith("'" + ctype):
if ctype == 'name':
field['display'] = """ function (data) {
return '<a href="%s&q='+encodeURIComponent(data.record.name)+'">' + data.record.name + '</a>';
}
""" % url
elif ctype == 'Promote':
# This is really ugly. I don't know of a better way to
# use the campaign addition form and also submit name of
# the bucket. So the form is POSTed but the URL also
# has a bucket parameter that is for the name of the
# to operate on.
field['display'] = """ function (data) {
return '<div class="icon-container"><span class="add_button" data-intro="Add a campaign" data-position="right"><a href="#" action="%s?name='+encodeURIComponent(data.record.name)+'" class="ui-icon ui-icon-plusthick dialogClick" dialog="campaign-add" persona="promote" title="Promote to campaign"></a></span></div>'
}
""" % url
else:
field['display'] = """ function (data) {
return '<a href="%s?bucket_list='+encodeURIComponent(data.record.name)+'">'+data.record.%s+'</a>';
}
""" % (url, ctype)
return render(request, 'bucket_lists.html',
{'jtable': jtable,
'jtid': 'bucket_lists'})
def modify_bucket_list(itype, oid, tags, analyst):
"""
Modify the bucket list for a top-level object.
:param itype: The CRITs type of the top-level object to modify.
:type itype: str
:param oid: The ObjectId to search for.
:type oid: str
:param tags: The list of buckets.
:type tags: list
:param analyst: The user making the modifications.
"""
obj = class_from_id(itype, oid)
if not obj:
return
obj.add_bucket_list(tags, analyst, append=False)
try:
obj.save(username=analyst)
except ValidationError:
pass
def download_object_handler(total_limit, depth_limit, rel_limit, rst_fmt,
bin_fmt, object_types, objs, sources,
make_zip=True):
"""
Given a list of tuples, collect the objects for each given the total
number of objects to return for each, the depth to traverse for each
and the maximum number of relationships to consider before ignoring.
NOTE: This function can collect more than total_limit number of objects
because total_limit applies only to each call to collect_objects() and
not to the total number of things collected.
:param total_limit: The max number of objects to return.
:type total_limit: int
:param depth_limit: The level of relationships to recurse into.
:type depth_limit: int
:param rel_limit: The limit on how many relationhips a top-level object
should have before we ignore its relationships.
:type rel_limit: int
:param rst_fmt: The format the results should be in ("zip", "json",
"json_no_bin").
:type rst_fmt: str
:param object_types: The types of top-level objects to include.
:type object_types: list
:param objs: A list of types (<obj_type>, <obj_id>) that we should use as
our basis to collect for downloading.
:type objs: list
:param sources: A list of sources to limit results against.
:type sources: list
:returns: A dict with the keys:
"success" (boolean),
"filename" (str),
"data" (str),
"mimetype" (str)
"""
json_docs = []
to_zip = []
need_filedata = rst_fmt != 'json_no_bin'
if not need_filedata:
bin_fmt = None
# If rst_fmt is json & bin_fmt is not zlib or base64, force it to base64.
if rst_fmt == 'json' and bin_fmt not in ['zlib', 'base64']:
bin_fmt = 'base64'
for (obj_type, obj_id) in objs:
# get related objects
new_objects = collect_objects(obj_type, obj_id, depth_limit,
total_limit, rel_limit, object_types,
sources, need_filedata=need_filedata)
# if result format calls for binary data to be zipped, loop over
# collected objects and convert binary data to bin_fmt specified, then
# add to the list of data to zip up
for (oid, (otype, obj)) in new_objects.items():
if ((otype == PCAP._meta['crits_type'] or
otype == Sample._meta['crits_type'] or
otype == Certificate._meta['crits_type']) and
rst_fmt == 'zip'):
if obj.filedata: # if data is available
if bin_fmt == 'raw':
to_zip.append((obj.filename, obj.filedata.read()))
else:
(data, ext) = format_file(obj.filedata.read(),
bin_fmt)
to_zip.append((obj.filename + ext, data))
obj.filedata.seek(0)
else:
try:
exclude = [] if need_filedata else ['filedata']
json_docs.append((oid, otype, obj.to_json(exclude)))
except:
pass
stamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
if len(objs) == 1:
fname = "CRITs_%s_%s_%s" % (obj_type, obj_id, stamp)
else:
fname = "CRITs_%s" % stamp
if rst_fmt != 'zip': # JSON File
return {'success': True,
'data': "[%s]" % ",".join(doc[2] for doc in json_docs),
'filename': "%s.json" % fname,
'mimetype': 'text/json'}
else: # ZIP File
for doc in json_docs:
inner_filename = "%s-%s.json" % (doc[1], doc[0])
to_zip.append((inner_filename, doc[2]))
return {'success': True,
'data': create_zip(to_zip, True),
'filename': "%s.zip" % fname,
'mimetype': 'application/zip'}
def collect_objects(obj_type, obj_id, depth_limit, total_limit, rel_limit,
object_types, sources, need_filedata=True, depth=0):
"""
Collects an object from the database, along with its related objects, to
the specified depth, or until the total limit is reached. This is a
breadth first traversal because I think it's better to get objects as
close to the initial one as possible, rather than traversing to the
bottom of a tree first.
If depth_limit is 0, relationships are not examined.
If an object has too many relationships (configurable system wide)
then it is ignored and that branch of the relationship tree is not
taken.
The returned object types will be only those in object_types. If
a sample is found without a valid filedata attribute it will be
collected only if need_fildata is False.
Objects are returned as a dictionary with the following key/value
mapping:
_id: (obj_type, crits_obj)
Sources should be a list of the names of the sources the user has
permission to access.
:param obj_type: The CRITs top-level object type to work with.
:type obj_type: str
:param obj_id: The ObjectId to search for.
:type obj_id: str
:param depth_limit: The level of relationships to recurse into.
:type depth_limit: int
:param total_limit: The max number of objects to return.
:type total_limit: int
:param rel_limit: The limit on how many relationhips a top-level object
should have before we ignore its relationships.
:type rel_limit: int
:param object_types: The types of top-level objects to include.
:type object_types: list
:param sources: A list of sources to limit results against.
:type sources: list
:param need_filedata: Include data from GridFS if applicable.
:type need_filedata: boolean
:param depth: Depth tracker. Default is 0 to start at no relationships and
work our way down.
:returns: A dict with ObjectIds as keys, and values of tuples
(<object_type>, <object>).
"""
objects = {}
# This dictionary is used to keep track of nodes that have been
# seen already. This ensures that we do not circle back on the graph.
seen_objects = {}
def inner_collect(obj_type, obj, sources, depth, depth_limit, total_limit,
object_types, need_filedata):
# Don't keep going if the total number of objects is reached.
if len(objects) >= total_limit:
return objects
# Be cognizant of the need to collect samples with no backing binary
# if the user asked for no binaries (need_filedata is False).
#
# If the object has a filedata attribute we need to collect it
# if need_filedata is true and the filedata attribute is valid.
# If the object does not have a valid filedata attribute and
# need_filedata is False, then collect it (metadata only).
#
# If the object is not one we want to collect we will still traverse
# down that path of the graph, but will not collect the object.
if obj_type in object_types:
if hasattr(obj, 'filedata'):
if obj.filedata and need_filedata:
objects[obj.id] = (obj_type, obj)
elif not need_filedata:
objects[obj.id] = (obj_type, obj)
else:
objects[obj.id] = (obj_type, obj)
seen_objects[obj.id] = True
# If not recursing (depth_limit == 0), return.
# If at depth limit, return.
if depth_limit == 0 or depth >= depth_limit:
return objects
new_objs = []
for r in obj.relationships:
# Don't touch objects we have already seen.
if r.object_id in seen_objects:
continue
seen_objects[r.object_id] = True
new_class = class_from_type(r.rel_type)
if not new_class:
continue
new_obj = new_class.objects(id=str(r.object_id),
source__name__in=sources).first()
if not new_obj:
continue
# Don't go down this branch if there are too many relationships.
# This most often happens when a common resource is extracted
# from many samples.
if len(new_obj.relationships) > rel_limit:
continue
# Save the objects so we can recurse into them later.
new_objs.append((r.rel_type, new_obj))
# Try to collect the new object, but don't handle relationships.
# Do this by setting depth_limit to 0.
inner_collect(r.rel_type, new_obj, sources, depth, 0, total_limit,
object_types, need_filedata)
# Each of the new objects become a new starting point for traverse.
depth += 1
for (new_type, new_obj) in new_objs:
inner_collect(new_type, new_obj, sources, depth, depth_limit,
total_limit, object_types, need_filedata)
# END OF INNER COLLECT
klass = class_from_type(obj_type)
if not klass:
return objects
obj = klass.objects(id=str(obj_id), source__name__in=sources).first()
if not obj:
return objects
inner_collect(obj_type, obj, sources, 0, depth_limit, total_limit,
object_types, need_filedata)
return objects
def modify_source_access(analyst, data):
"""
Update a user profile.
:param analyst: The user to update.
:type analyst: str
:param data: The user profile fields to change and their values.
:type data: dict
:returns: dict with keys "success" (boolean) and "message" (str) if failed.
"""
user = CRITsUser.objects(username=data['username']).first()
if not user:
user = CRITsUser.create_user(
data.get('username', ''),
data.get('password', ''),
data.get('email') )
if not user:
return {'success': False,
'message': 'Missing user information username/password/email'}
user.first_name = data['first_name']
user.last_name = data['last_name']
user.email = data['email']
user.roles = data['roles']
user.organization = data['organization']
user.totp = data['totp']
user.secret = data['secret']
if len(data.get('password', '')) > 1:
if user.set_password(data['password']) == False:
config = CRITsConfig.objects().first()
pc = config.password_complexity_desc
return {'success': False,
'message': 'Password does not meet complexity policy: %s' % pc}
if data['subscriptions'] == '':
user.subscriptions = EmbeddedSubscriptions()
user.acl_needs_update = True
try:
user.save(username=analyst)
return {'success': True}
except ValidationError, e:
return {'success': False,
'message': format_error(e)}
def datetime_parser(value):
"""
Iterate over a dict to confirm that keys containing the word 'dict' are
in fact datetime.datetime objects.
If a string is passed, returns a datetime.datetime
:param value: str or a dictionary to iterate over.
:type value: str or dict
:returns: str or dict
"""
if isinstance(value,datetime.datetime):
return value
elif isinstance(value,basestring) and value:
return datetime.datetime.strptime(value, settings.PY_DATETIME_FORMAT)
elif isinstance(value,dict):
for k,v in value.items():
# Make sure that date is in the key, value is a string, and val is not ''
if "date" in k and isinstance(v,basestring) and v:
value[k] = datetime.datetime.strptime(v, settings.PY_DATETIME_FORMAT)
return value
else:
raise TypeError("Invalid type passed.")
def format_error(e):
"""
Takes an Exception and returns a nice string representation.
:param e: An exception.
:type e: Exception
:returns: str
"""
return e.__class__.__name__+": "+unicode(e)
def toggle_item_state(type_, oid, analyst):
"""
Toggle an item active/inactive.
:param type_: The CRITs type for this item.
:type type_: str
:param oid: The ObjectId to search for.
:type oid: str
:param analyst: The user toggling this item.
:type analyst: str
:returns: dict with key "success" (boolean)
"""
obj = class_from_id(type_, oid)
if not obj:
return {'success': False}
if obj.active == 'on':
obj.active = 'off'
else:
obj.active = 'on'
try:
obj.save(username=analyst)
return {'success': True}
except ValidationError:
return {'success': False}
def do_add_preferred_actions(obj_type, obj_id, username):
"""
Add all preferred actions to an object.
:param obj_type: The type of object to update.
:type obj_type: str
:param obj_id: The ObjectId of the object to update.
:type obj_id: str
:param username: The user adding the preferred actions.
:type username: str
:returns: dict with keys:
"success" (boolean),
"message" (str) if failed,
"object" (list of dicts) if successful.
"""
klass = class_from_type(obj_type)
if not klass:
return {'success': False, 'message': 'Invalid type'}
preferred_actions = Action.objects(preferred__object_type=obj_type,
active='on')
if not preferred_actions:
return {'success': False, 'message': 'No preferred actions'}
sources = user_sources(username)
obj = klass.objects(id=obj_id, source__name__in=sources).first()
if not obj:
return {'success': False, 'message': 'Could not find object'}
actions = []
# Get preferred actions and add them.
for a in preferred_actions:
for p in a.preferred:
if (p.object_type == obj_type and
obj.__getattribute__(p.object_field) == p.object_value):
now = datetime.datetime.now()
action = {'action_type': a.name,
'active': 'on',
'analyst': username,
'begin_date': now,
'end_date': None,
'performed_date': now,
'reason': 'Preferred action toggle',
'date': now}
obj.add_action(action['action_type'],
action['active'],
action['analyst'],
action['begin_date'],
action['end_date'],
action['performed_date'],
action['reason'],
action['date'])
actions.append(action)
if len(actions) < 1:
return {'success': False, 'message': 'No preferred actions'}
# Change status to In Progress if it is currently 'New'
if obj.status == 'New':
obj.set_status('In Progress')
try:
obj.save(username=username)
except ValidationError, e:
return {'success': False, 'message': e}
return {'success': True, 'object': actions}
def get_item_state(type_, name):
"""
Get the state of an item.
:param type_: The CRITs type for this item.
:type type_: str
:param name: The name of the item.
:type name: str
:returns: True if active, False if inactive.
"""
query = {'name': name}
obj = class_from_type(type_).objects(__raw__=query).first()
if not obj:
return False
if obj.active == 'on':
return True
else:
return False
def remove_quotes(val):
"""
Remove surrounding quotes from a string.
:param val: The string to remove quotes from.
:type val: str
:returns: str
"""
if val.startswith(('"', "'",)) and val.endswith(('"', "'",)):
val = val[1:-1]
return val
def generate_regex(val):
"""
Takes the value, removes surrounding quotes, and generates a PyMongo $regex
query for use on a field.
:param val: The string to use for a regex.
:type val: str
:returns: dict with key '$regex' if successful, 'error' if failed.
"""
try:
return {'$regex': re.compile('%s' % remove_quotes(val), re.I)}
except Exception, e:
return {'error': 'Invalid Regular Expression: %s\n\n\t%s' % (val,
str(e))}
def parse_search_term(term, force_full=False):
"""
Parse a search term to break it into search operators that we can use to
enhance the search results.
:param term: Search term
:type term: str
:returns: search string or dictionary for regex search
"""
# decode the term so we aren't dealing with weird encoded characters
if force_full == False:
term = urllib.unquote(term)
search = {}
# setup lexer, parse our term, and define operators
try:
sh = shlex.shlex(term.strip())
sh.wordchars += '!@#$%^&*()-_=+[]{}|\:;<,>.?/~`'
sh.commenters = ''
parsed = list(iter(sh.get_token, ''))
except Exception as e:
search['query'] = {'error': str(e)}
return search
operators = ['regex', 'full', 'type', 'field']
# for each parsed term, check to see if we have an operator and a value
regex_term = ""
if len(parsed) > 0:
for p in parsed:
s = p.split(':')
if len(s) >= 2:
so = s[0]
st = ':'.join(s[1:])
if so in operators:
# can make this more flexible for regex?
if so == 'regex':
search['query'] = generate_regex(st)
elif so == 'full':
regex_term += "%s " % (st,)
force_full = True
elif so == 'type':
search['type'] = st.title()
elif so == 'field':
search['field'] = remove_quotes(st.lower())
else:
regex_term += "%s:%s " % (so, st)
else:
regex_term += "%s " % p
if regex_term:
if force_full:
search['query'] = remove_quotes(regex_term.strip())
else:
search['query'] = generate_regex(regex_term.strip())
return search
def gen_global_query(obj,user,term,search_type="global",force_full=False):
"""
Generate a search query. Also calls :func:`check_query` for validation.
:param obj: CRITs Document Object
:type obj: :class:`crits.core.crits_mongoengine.CritsDocument`
:param user: CRITs user
:type user: str
:param term: Search term
:type term: str
:param search_type: Search type
:type search_type: str
:returns: dict -- The validated query dictionary
"""
type_ = obj._meta['crits_type']
search_list = []
query = {}
# Some terms, regardless of the query, will want to be full search terms and
# not regex terms.
force_full_terms = ['analysis_result', 'ssdeephash']
force = False
# Exclude searches for 'source' or 'releasability'
# This is required because the check_query function doesn't handle
# regex searches for these two fields
if 'source' in search_type or 'releasability' in search_type:
return query
if search_type in force_full_terms or force_full != False:
force = True
parsed_search = parse_search_term(term, force_full=force)
if 'query' not in parsed_search:
return {'success': False,
'ignore': False,
'error': 'No query to search'}
if 'error' in parsed_search['query']:
return {'success': False,
'ignore': False,
'error': parsed_search['query']['error']}
search_query = parsed_search['query']
if 'type' in parsed_search:
t = class_from_type(parsed_search['type'])
if t:
type_ = parsed_search['type']
if obj._meta['crits_type'] != type_:
return {'success': False,
'ignore': True,
'error': 'This type is being ignored.'}
if 'field' in parsed_search:
query = {parsed_search['field']: parsed_search['query']}
defaultquery = check_query({search_type: search_query},user,obj)
sample_queries = {
'size' : {'size': search_query},
'md5hash': {'md5': search_query},
'sha1hash': {'sha1': search_query},
'ssdeephash': {'ssdeep': search_query},
'sha256hash': {'sha256': search_query},
'impfuzzyhash': {'impfuzzy': search_query},
# slow in larger collections
'filename': {'$or': [
{'filename': search_query},
{'filenames': search_query},
]},
'campaign': {'campaign.name': search_query},
# slightly slow in larger collections
'object_value': {'objects.value': search_query},
'bucket_list': {'bucket_list': search_query},
'ticket': {'tickets.ticket_number': search_query},
'sectors': {'sectors': search_query},
'source': {'source.name': search_query},
}
# if a specific field is being defined to search against, return early
if 'field' in parsed_search:
if 'filedata' in query:
query = {'filedata': None}
return query
elif search_type == "bucket_list":
query = {'bucket_list': search_query}
elif search_type == "sectors":
query = {'sectors': search_query}
elif search_type == "actor_identifier":
query = {'identifiers.identifier_id': search_query}
# object_ comes from the core/views.py search function.
# It joins search_type with otype
elif search_type.startswith("object_"):
if search_type == "object_value":
query = {"objects.value": search_query}
else:
otypes = search_type.split("_")[1].split(" - ")
if len(otypes) == 1:
query = {"objects": {"$elemMatch": {"name": otypes[0],
"value": search_query}}}
else:
query = {"objects": {"$elemMatch": {"name": otypes[1],
"type": otypes[0],
"value": search_query}}}
elif search_type == "byobject":
query = {'comment': search_query}
elif search_type == "global":
if type_ == "Sample":
search_list.append(sample_queries["object_value"])
search_list.append(sample_queries["filename"])
if len(term) == 32:
search_list.append(sample_queries["md5hash"])
elif type_ == "AnalysisResult":
search_list = [
{'results.result': search_query},
]
elif type_ == "Actor":
search_list = [
{'name': search_query},
{'objects.value': search_query},
]
elif type_ == "Certificate":
search_list = [
{'md5': search_query},
{'objects.value': search_query},
]
elif type_ == "PCAP":
search_list = [
{'md5': search_query},
{'objects.value': search_query},
]
elif type_ == "RawData":
search_list = [
{'md5': search_query},
{'data': search_query},
{'objects.value': search_query},
]
elif type_ == "Signature":
search_list = [
{'md5': search_query},
{'data': search_query},
{'objects.value': search_query},
]
elif type_ == "Indicator":
search_list = [
{'value': search_query},
{'objects.value': search_query}
]
elif type_ == "Domain":
search_list = [
{'domain': search_query},
{'objects.value': search_query}
]
elif type_ == "Email":
search_list = [
{'from': search_query},
{'subject': search_query},
{'raw_body': search_query},
{'raw_headers': search_query},
{'objects.value': search_query},
{'x_originating_ip': search_query},
{'originating_ip': search_query}
]
elif type_ == "Event":
search_list = [
{'description': search_query},
{'title': search_query},
{'objects.value': search_query}
]
elif type_ == "IP":
search_list = [
{'ip': search_query},
{'objects.value': search_query}
]
elif type_ == "Comment":
search_list = [
{'comment': search_query},
]
elif type_ == "Campaign":
search_list = [
{'name': search_query},
{'aliases': search_query},
]
elif type_ == "Screenshot":
search_list = [
{'description': search_query},
{'tags': search_query},
]
elif type_ == "Target":
search_list = [
{'email_address': search_query},
{'firstname': search_query},
{'lastname': search_query},
]
else:
search_list = [{'name': search_query}]
search_list.append({'source.instances.reference':search_query})
search_list.append({'bucket_list': search_query})
search_list.append({'sectors': search_query})
query = {'$or': search_list}
else:
if type_ == "Domain":
query = {'domain': search_query}
elif type_ == "Email":
if search_type == "ip":
query = {'$or': [{'originating_ip': search_query},
{'x_originating_ip': search_query}]}
elif search_type == "reference":
query = {'source.instances.reference': search_query}
else:
query = defaultquery
elif type_ == "RawData":
if search_type == "data":
query = {'data': search_query}
elif search_type == "data_type":
query = {'data_type': search_query}
elif search_type == "title":
query = {'title': search_query}
elif search_type == "tool":
query = {'tool.name': search_query}
else:
query = defaultquery
elif type_ == "Signature":
if search_type == "data":
query = {'data': search_query}
elif search_type == "data_type":
query = {'data_type': search_query}
elif search_type == "title":
query = {'title': search_query}
elif search_type == "tool":
query = {'tool.name': search_query}
else:
query = defaultquery
elif type_ == "Event":
if search_type == "campaign":
query = {'campaign.name': search_query}
elif search_type == "source":
query = {'source.name': search_query}
else:
query = defaultquery
elif type_ == "Indicator":
if search_type == "campaign":
query = {'campaign.name': search_query}
elif search_type == "ticket_number":
query = {'tickets.ticket_number': search_query}
elif search_type == "source":
query = {'source.name': search_query}
elif search_type == "confidence":
query = {'confidence.rating': search_query}
elif search_type == "impact":
query = {'impact.rating': search_query}
else:
query = defaultquery
elif type_ == "IP":
query = {'ip': search_query}
elif type_ == "Sample":
if search_type not in sample_queries:
return {'success': None,
'ignore': False,
'error': 'Search type not in sample queries.'}
query = sample_queries[search_type]
if 'size' in query:
try:
query = {'size': int(query['size'])}
except ValueError:
return {'success': None,
'ignore': False,
'error': 'Size must be an integer.'}
else:
query = defaultquery
return query
def check_query(qparams,user,obj):
"""
Remove and/or filter queries which may cause issues
:param qparams: MongoDB query
:type qparams: dict
:param user: CRITs user
:type user: str
:param obj: CRITs Document Object
:type obj: :class:`crits.core.crits_mongoengine.CritsDocument`
:returns: dict -- The validated query dictionary
"""
# Iterate over the supplied query keys and make sure they start
# with a valid field from the document
goodkeys = {}
for key,val in qparams.items():
# Skip anything with Mongo's special $
if '$' in key:
continue
# Grab the base field for doing the key checks
try:
indx = key.index('.')
field = key[:indx]
except:
field = key
# Check for mapping, reverse because we're going the other way
invmap = dict((v,k) for k, v in obj._db_field_map.iteritems())
if field in invmap:
field = invmap[field]
# Only allow query keys that exist in the object
if hasattr(obj,field):
goodkeys[key] = val
# Filter out invalid queries regarding source/releasability
sourcefilt = user_sources(user)
newquery = goodkeys.copy()
for key in goodkeys:
# Sources
if "source" in key:
if key != "source.name" and key != "source":
del newquery[key]
else:
if goodkeys[key] not in sourcefilt:
del newquery[key]
# Releasability
if "releasability" in key:
if key != "releasability.name" and key != "releasability":
del newquery[key]
else:
if goodkeys[key] not in sourcefilt:
del newquery[key]
return newquery
def data_query(col_obj, user, limit=25, skip=0, sort=[], query={},
projection=[], excludes=[], count=False):
"""
Basic query function
:param col_obj: MongoEngine collection object (Required)
:type col_obj: :class:`crits.core.crits_mongoengine.CritsDocument`
:param user: CRITs user (Required)
:type user: str
:param limit: Limit on returned rows
:type limit: int `(25)`
:param skip: Number of rows to skip
:type skip: int `(0)`
:param sort: Fields to sort by (Prepend field name with '-' to reverse sort)
:type sort: list
:param query: MongoDB query
:type query: dict
:param projection: Projection filter to apply to query
:type projection: list
:param excludes: fields to exclude from query results
:type excludes: list
:returns: dict -- Keys are result, data, count, msg, crits_type. 'data'
contains a :class:`crits.core.crits_mongoengine.CritsQuerySet` object.
"""
results = {'result':'ERROR'}
results['data'] = []
results['count'] = 0
results['msg'] = ""
results['crits_type'] = col_obj._meta['crits_type']
sourcefilt = user_sources(user)
if isinstance(sort,basestring):
sort = sort.split(',')
if isinstance(projection,basestring):
projection = projection.split(',')
if not projection:
projection = []
# It came from: https://stackoverflow.com/questions/12068558/use-mongoengine-and-pymongo-together
col = col_obj._get_collection()
docs = None
try:
if not issubclass(col_obj,CritsSourceDocument):
results['count'] = col.find(query).count()
if count:
results['result'] = "OK"
return results
if col_obj._meta['crits_type'] == 'User':
docs = col_obj.objects(__raw__=query).only(*projection).exclude('password',
'password_reset',
'api_keys').\
order_by(*sort).skip(skip).\
limit(limit)
else:
docs = col_obj.objects(__raw__=query).\
order_by(*sort).\
skip(skip).limit(limit)
# Else, all other objects that have sources associated with them
# need to be filtered appropriately for source access and TLP access
else:
#fily = {'id': 1, 'tlp':1,'source':1}
#filterlist = []
#query['source.name'] = {'$in': sourcefilt}
#resy = col.find(query, fily).sort(*sort)
#for r in resy:
# if user.check_dict_source_tlp(r):
# filterlist.append(str(r['_id']))
#results['count'] = len(filterlist)
#if count:
# results['result'] = "OK"
# return results
#docs = col_obj.objects.filter(id__in=filterlist).\
tlp_filter_query = user.filter_dict_source_tlp(query)
docs = col_obj.objects.filter(__raw__=tlp_filter_query).\
order_by(*sort).skip(skip).\
only(*projection).limit(limit)
results['count'] = docs.count()
if count:
results['result'] = "OK"
return results
for doc in docs:
if hasattr(doc, "sanitize_sources"):
doc.sanitize_sources(username="%s" % user, sources=sourcefilt)
except Exception, e:
results['msg'] = "ERROR: %s. Sort performed on: %s" % (e,
', '.join(sort))
return results
results['data'] = docs
results['result'] = "OK"
return results
def csv_query(col_obj,user,fields=[],limit=0,skip=0,sort=[],query={}):
"""
Runs query and returns items in CSV format with fields as row headers
:param col_obj: MongoEngine collection object (Required)
:type col_obj: :class:`crits.core.crits_mongoengine.CritsDocument`
:param user: CRITs user (Required)
:type user: str
:param fields: Fields to return in the CSV
:type fields: list
:param limit: Limit on returned rows
:type limit: int
:param skip: Number of rows to skip
:type skip: int
:param sort: Fields to sort by (Prepend field name with '-' to reverse sort)
:type sort: list
:param query: MongoDB query
:type query: dict
"""
# Use maximum row count from config if an invalid value is given
crits_config = CRITsConfig.objects().first()
if crits_config:
csv_max = crits_config.csv_max
else:
csv_max = 25000 # Arbitrary Default
if not isinstance(limit, int) or limit < 1 or limit > csv_max:
limit = csv_max
results = data_query(col_obj, user=user, limit=limit,
skip=skip, sort=sort, query=query,
projection=fields)
if results['result'] == "OK":
return results['data'].to_csv(fields)
else:
return results['msg']
def parse_query_request(request,col_obj):
"""
Get query modifiers from a request
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:returns: dict -- Keys are fields, sort, limit, skip
"""
resp = {}
resp['fields'] = request.GET.get('fields',[])
if resp['fields']:
try:
resp['fields'] = resp['fields'].split(',')
except:
return render(request, "error.html", {"error": "Invalid fields specified"})
goodfields = []
for field in resp['fields']:
# Skip anything with Mongo's special $
if '$' in field:
continue
# Grab the base field for doing the key checks
try:
indx = field.index('.')
base = field[:indx]
extra = field[indx:]
except:
base = field
extra = ""
# Check for mapping, reverse because we're going the other way
invmap = dict((v,k) for k, v in col_obj._db_field_map.iteritems())
if base in invmap:
base = invmap[base]
# Only allow query keys that exist in the object
if hasattr(col_obj,base):
goodfields.append(base+extra)
resp['fields'] = goodfields
resp['sort'] = request.GET.get('sort',[])
resp['limit'] = int(request.GET.get('limit', 0))
resp['skip'] = int(request.GET.get('skip',0))
return resp
def csv_export(request, col_obj, query={}):
"""
Returns a :class:`django.http.HttpResponse` object which prompts the user
to download a CSV file containing the results from :func:`csv_query`.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param col_obj: MongoEngine collection object (Required)
:type col_obj: :class:`crits.core.crits_mongoengine.CritsDocument`
:param query: MongoDB query
:type query: dict
:returns: :class:`django.http.HttpResponse` -- CSV download response
"""
opts = parse_query_request(request,col_obj)
if not query:
resp = get_query(col_obj, request)
if resp['Result'] == "ERROR":
response = render(request, "error.html", {"error": resp['Message'] })
return response
query = resp['query']
result = csv_query(col_obj, request.user, fields=opts['fields'],
sort=opts['sort'], query=query, limit=opts['limit'],
skip=opts['skip'])
if isinstance(result, basestring):
response = HttpResponse(result, content_type="text/csv")
response['Content-Disposition'] = "attachment;filename=crits-%s-export.csv" % col_obj._meta['crits_type']
else:
response = render(request, "error.html", {"error" : result })
return response
def get_query(col_obj,request):
"""
Pull out a query from a request object
:param col_obj: MongoEngine collection object (Required)
:type col_obj: :class:`crits.core.crits_mongoengine.CritsDocument`
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:returns: dict -- The MongoDB query
"""
keymaps = {
"actor_identifier": "identifiers.identifier_id",
"campaign": "campaign.name",
"source": "source.name",
"confidence": "confidence.rating",
"impact": "impact.rating",
"object_value":"objects.value",
"analysis_result":"results.result",
}
term = ""
query = {}
response = {}
params_escaped = {}
for k,v in request.GET.items():
params_escaped[k] = html_escape(v)
for k,v in request.POST.items():
params_escaped[k] = html_escape(v)
urlparams = "?%s" % urlencode(params_escaped)
if "q" in request.GET:
force_full = request.GET.get('force_full', False)
term = request.GET.get('q')
search_type = request.GET.get('search_type',None)
if not search_type:
response['Result'] = "ERROR"
response['Message'] = "No search_type defined"
return response
otype = request.GET.get('otype', None)
if otype:
search_type = search_type + "_" + otype
term = HTMLParser.HTMLParser().unescape(term)
qdict = gen_global_query(col_obj,
request.user.username,
term,
search_type,
force_full=force_full
)
if not qdict.get('success', True):
if qdict.get('ignore', False):
response['Result'] = "IGNORE"
else:
response['Result'] = "ERROR"
response['Message'] = qdict.get('error', 'Unable to process query')
return response
query.update(qdict)
term = request.GET['q']
qparams = request.GET.copy()
qparams.update(request.POST.copy())
qparams = check_query(qparams,request.user.username,col_obj)
for key,value in qparams.items():
if key in keymaps:
key = keymaps[key]
# This one is not a straight rename like the others. If
# searching for x_originating_ip also search for originating_ip,
# and vice versa. This means we have to logically or the query
# where the others do not.
if key in ['x_originating_ip', 'originating_ip']:
query["$or"] = [
{"x_originating_ip": value},
{"originating_ip": value}
]
elif key in ['size', 'length']:
try:
query[key] = int(value)
except ValueError:
results = {}
results['Result'] = "ERROR"
results['Message'] = "'size' requires integer, not %s" % value
return results
else:
query[key] = value
term = term + " " + value
results = {}
results['Result'] = "OK"
results['query'] = query
results['term'] = term
results['urlparams'] = urlparams
return results
def jtable_ajax_list(col_obj,url,urlfieldparam,request,excludes=[],includes=[],query={}):
"""
Handles jTable listing POST requests
:param col_obj: MongoEngine collection object (Required)
:type col_obj: :class:`crits.core.crits_mongoengine.CritsDocument`
:param url: Base URL for objects. Ex ``crits.domains.views.domain_detail``
:type url: str
:param urlfieldparam: Field to use for the item detail's URL key. Passed
as arg with ``url`` to :func:`django.core.urlresolvers.reverse`
:type urlfieldparam: str
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param excludes: Fields to exclude
:type excludes: list
:param includes: Fields to include
:type includes: list
:param query: MongoDB query
:type query: dict
"""
response = {"Result": "ERROR"}
users_sources = user_sources(request.user.username)
user = request.user
if request.is_ajax():
pageSize = request.user.get_preference('ui','table_page_size',25)
# Thought these were POSTs...GET works though
skip = int(request.GET.get("jtStartIndex", "0"))
if "jtLimit" in request.GET:
pageSize = int(request.GET['jtLimit'])
else:
pageSize = int(request.GET.get("jtPageSize", pageSize))
# Set the sort order
sort = request.GET.get("jtSorting", urlfieldparam+" ASC")
keys = sort.split(',')
multisort = []
keymaps = {
"actor_identifier": "identifiers.identifier_id",
"campaign": "campaign.name",
"source": "source.name",
"confidence": "confidence.rating",
"impact": "impact.rating",
"object_value": "objects.value",
"analysis_result": "results.result",
}
for key in keys:
(keyname, keyorder) = key.split()
if keyname in keymaps:
keyname = keymaps[keyname]
if keyorder == "DESC":
keyname = "-%s" % keyname
multisort.append(keyname)
# Build the query
term = ""
if not query:
resp = get_query(col_obj, request)
if resp['Result'] in ["ERROR", "IGNORE"]:
return resp
query = resp['query']
term = resp['term']
response = data_query(col_obj, user=request.user, limit=pageSize,
skip=skip, sort=multisort, query=query,
projection=includes, excludes=excludes)
if response['result'] == "ERROR":
return {'Result': "ERROR", 'Message': response['msg']}
response['crits_type'] = col_obj._meta['crits_type']
# Escape term for rendering in the UI.
response['term'] = cgi.escape(term)
response['data'] = response['data'].to_dict(excludes, includes)
# Convert data_query to jtable stuff
response['Records'] = response.pop('data')
response['TotalRecordCount'] = response.pop('count')
response['Result'] = response.pop('result')
acl = get_acl_object(col_obj._meta['crits_type'])
for doc in response['Records']:
for key, value in doc.items():
# all dates should look the same
if isinstance(value, datetime.datetime):
doc[key] = datetime.datetime.strftime(value,
"%Y-%m-%d %H:%M:%S")
if key == "password_reset":
doc['password_reset'] = None
if key == "campaign":
camps = []
if user.has_access_to(Common.CAMPAIGN_READ):
if acl and user.has_access_to(acl.CAMPAIGNS_READ):
for campdict in value:
camps.append(campdict['name'])
doc[key] = "|||".join(camps)
elif key == "source":
srcs = []
if col_obj._meta['crits_type'] == 'ActorIdentifier':
if user.has_access_to(ActorACL.SOURCES_READ):
for srcdict in doc[key]:
if srcdict['name'] in users_sources:
srcs.append(srcdict['name'])
elif user.has_access_to(acl.SOURCES_READ):
for srcdict in doc[key]:
if srcdict['name'] in users_sources:
srcs.append(srcdict['name'])
doc[key] = "|||".join(srcs)
elif key == "status":
if not user.has_access_to(acl.STATUS_READ):
doc[key] = None
elif key == "description":
if acl and not user.has_access_to(acl.DESCRIPTION_READ):
doc[key] = ""
elif key == "tags":
tags = []
for tag in doc[key]:
tags.append(tag)
doc[key] = "|||".join(tags)
elif key == "is_active":
if value:
doc[key] = "True"
else:
doc[key] = "False"
elif key == "datatype":
doc[key] = value.keys()[0]
elif key == "results":
doc[key] = len(doc[key])
elif key == "preferred":
final = ""
for p in doc[key]:
final += p['object_type']
final += "|"
final += p['object_field']
final += "|"
final += p['object_value']
final += "||"
doc[key] = final
elif isinstance(value, list):
if value:
for item in value:
if not isinstance(item, basestring):
break
else:
doc[key] = ",".join(value)
else:
doc[key] = ""
doc[key] = html_escape(doc[key])
if col_obj._meta['crits_type'] == "Comment":
mapper = {
"Actor": 'crits-actors-views-actor_detail',
"Campaign": 'crits-campaigns-views-campaign_details',
"Certificate": 'crits-certificates-views-certificate_details',
"Domain": 'crits-domains-views-domain_detail',
"Email": 'crits-emails-views-email_detail',
"Event": 'crits-events-views-view_event',
"Indicator": 'crits-indicators-views-indicator',
"IP": 'crits-ips-views-ip_detail',
"PCAP": 'crits-pcaps-views-pcap-details',
"RawData": 'crits-raw_data-views-raw_data_details',
"Sample": 'crits-samples-views-detail',
"Signature": 'crits-signatures-views-detail',
}
doc['url'] = reverse(mapper[doc['obj_type']],
args=(doc['url_key'],))
elif col_obj._meta['crits_type'] == "AuditLog":
if doc.get('method', 'delete()') != 'delete()':
doc['url'] = details_from_id(doc['type'],
doc.get('target_id', None))
elif not url:
doc['url'] = None
else:
doc['url'] = reverse(url, args=(unicode(doc[urlfieldparam]),))
return response
def jtable_ajax_delete(obj,request):
"""
Delete a document specified in the jTable POST.
:param obj: MongoEngine collection object (Required)
:type obj: :class:`crits.core.crits_mongoengine.CritsDocument`
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:returns: bool -- True if item was deleted
"""
# Make sure we are supplied _id
if not "id" in request.POST:
return False
docid = request.POST['id']
if not docid:
return False
# Finally, make sure there is a related document
doc = obj.objects(id=docid).first()
if not doc:
return False
if "delete_all_relationships" in dir(doc):
doc.delete_all_relationships()
# For samples/pcaps
if "filedata" in dir(doc):
doc.filedata.delete()
doc.delete(username=request.user.username)
return True
def build_jtable(jtopts, request):
"""
Build a dictionary containing proper jTable options.
:param jtopts: Python dictionary containing jTable options.
:type jtopts: dict.
:param request: Current Django request
:type request: :class:`django.http.HttpRequest`
:returns: dict -- Contains the jTable configuration used by the template.
**jtopts supports the following keys**
**Required**
*title*
Contains the jTable title.
*listurl*
URL for the Django view that returns the data in JSON.
*searchurl*
URL to use when filtering data, usually the base URL for the view,
without any options.
*fields*
Python list containing the fields to show for a document. The
first item will be linked to the details view.
**Optional**
*default_sort*
Defines the field and order to sort by.
Ex. "field <ASC|DESC>"
Default: FirstField ASC
*deleteurl*
URL for Django view to delete an item
*no_sort*
Python list containing which fields to disable sorting
*hidden_fields*
Python list containing which fields to hide. This list is a
subset of 'fields'
*linked_fields*
Python list containing which fields should allow filtering.
*paging*
Allow paging on this jTable.
Default: true
*pageSize*
Number of rows per page
Deafult: User Preference (defaults to 25)
*sorting*
Allow sorting by column on this jTable
Default: true
*multiSorting*
Allow sorting by multiple columns on this jTable
Default: true
*details_link*
Define the field that should link to the details
Default: First field
If specified as '__disable__', then no linking will occur
If specified as 'details', an icon is used for the link
"""
# Check for required values
if not all(required in jtopts for required in ['listurl','searchurl','fields','title']):
raise KeyError("Missing required key for jtopts in build_jtable")
return None
# jTable requires a key for the field
# Mongo provides _id as a unique identifier, so we will require that
if "id" not in jtopts['fields']:
jtopts['fields'].append("id")
# If we push the _id field on, we will also hide it by default
if 'hidden_fields' in jtopts:
jtopts['hidden_fields'].append("id")
else:
jtopts['hidden_fields'] = ["id",]
pageSize = request.user.get_preference('ui','table_page_size',25)
# Default jTable options
default_options = {
"paging" : "true",
"pageSize": pageSize,
"sorting": "true",
"multiSorting": "true",
}
# Default widths for certain columns in the jTable
colwidths = {
"details": "'2%'",
'recip': "'2%'",
"comment":"'15%'",
"date":"'8%'",
"isodate":"'8%'",
"id":"'4%'",
"favorite":"'4%'",
"actions":"'4%'",
"size":"'4%'",
"added":"'8%'",
"created":"'8%'",
"modified":"'8%'",
"subject":"'17%'",
"value":"'18%'",
"type":"'10%'",
"filetype":"'15%'",
"status":"'5%'",
"source":"'7%'",
"campaign":"'7%'",
}
# Mappings for the column titles
titlemaps = {
"Isodate": "Date",
"Created": "Added",
"Ip": "IP",
"Id": "Store ID",
}
jtable = {}
# This allows overriding of default options if they are specified in jtopts
for defopt,defval in default_options.items():
if defopt in jtopts:
jtable[defopt] = jtopts[defopt]
else:
jtable[defopt] = defval
# Custom options
if 'title' in jtopts:
jtable['title'] = jtopts['title']
else:
jtable['title'] = ""
jtable['defaultSorting'] = jtopts['default_sort']
# Define jTable actions
jtable['actions'] = {}
# List action
# If we have get parameters, append them
if request.GET:
jtable['actions']['listAction'] = jtopts['listurl'] + "?"+request.GET.urlencode(safe='@')
else:
jtable['actions']['listAction'] = jtopts['listurl']
# Delete action
# If deleteurl is set, provide a delete action in jTable
if 'deleteurl' in jtopts and jtopts['deleteurl']:
jtable['actions']['deleteAction'] = jtopts['deleteurl']
# We don't have any views available for these actions
#jtable['actions']['createAction'] = reverse()
#jtable['actions']['updateAction'] = reverse()
# Generate the fields
jtable['fields'] = []
for field in jtopts['fields']:
fdict = {}
# Create the column title here
title = field.replace("_"," ").title().strip()
if title in titlemaps:
title = titlemaps[title]
# Some options require quotes, so we use "'%s'" to quote them
fdict['title'] = "'%s'" % title
fdict['fieldname'] = "'%s'" % field
if field in colwidths:
fdict['width'] = colwidths[field]
# Every jTable needs a key. All our items in Mongo have a unique _id
# identifier, so by default we always include that here as the key
if field == "id":
fdict['key'] = "true"
fdict['display'] = """function (data) { return '<div class="icon-container"><span id="'+data.record.id+'" class="id_copy ui-icon ui-icon-copy"></span></div>';}"""
if field == "favorite":
fdict['display'] = """function (data) { return '<div class="icon-container"><span id="'+data.record.id+'" class="favorites_icon_jtable ui-icon ui-icon-star"></span></div>';}"""
if field == "actions":
fdict['display'] = """function (data) { return '<div class="icon-container"><span data-id="'+data.record.id+'" id="'+data.record.id+'" class="preferred_actions_jtable ui-icon ui-icon-heart"></span></div>';}"""
if field == "thumb":
fdict['display'] = """function (data) { return '<img src="%s'+data.record.id+'/thumb/" />';}""" % reverse('crits-screenshots-views-render_screenshot')
if field == "description" and jtable['title'] == "Screenshots":
fdict['display'] = """function (data) { return '<span class="edit_underline edit_ss_description" data-id="'+data.record.id+'">'+data.record.description+'</span>';}"""
if 'no_sort' in jtopts and field in jtopts['no_sort']:
fdict['sorting'] = "false"
if 'hidden_fields' in jtopts and field in jtopts['hidden_fields']:
# hide the row but allow the user to show it
fdict['visibility'] = '"hidden"'
# This creates links for certain jTable columns
# It will link anything listed in 'linked_fields'
campbase = reverse('crits-campaigns-views-campaign_details',args=('__CAMPAIGN__',))
# If linked_fields is not specified lets link source and campaign
# if they exist as fields in the jTable
if 'linked_fields' not in jtopts:
jtopts['linked_fields'] = []
if 'source' in jtopts['fields']:
jtopts['linked_fields'].append("source")
if 'campaign' in jtopts['fields']:
jtopts['linked_fields'].append("campaign")
if field in jtopts['linked_fields']:
fdict['display'] = """function (data) {
return link_jtable_column(data, '%s', '%s', '%s');
} """ % (field, jtopts['searchurl'], campbase)
jtable['fields'].append(fdict)
if 'details_link' in jtopts:
if jtopts['details_link'] == "__disabled__":
return jtable
else:
if jtopts['details_link'] not in jtopts['fields']:
return jtable
# Link the field in details_link
linkfield = "'%s'" % jtopts["details_link"]
for i,field in enumerate(jtable['fields']):
if field['fieldname'] != linkfield:
continue
if field['fieldname'] == "'details'":
jtable['fields'][i]['display'] = 'function (data) {if (!data.record.url) { return '';}; return \'<a href="\'+data.record.url+\'" target="_parent"><div class="icon-container"><span class="ui-icon ui-icon-document" title="View Details"></span></div></a>\';}'
else:
jtable['fields'][i]['display'] = "function (data) {return '<a href=\"'+data.record.url+'\">'+data.record."+jtopts['fields'][i]+"+'</a>';}"
else:
# Provide default behavior
if jtable['fields'][0]['fieldname'] == "'details'":
jtable['fields'][0]['display'] = 'function (data) {return \'<a href="\'+data.record.url+\'"><div class="icon-container"><span class="ui-icon ui-icon-document" title="View Details"></span></div></a>\';}'
else:
jtable['fields'][0]['display'] = "function (data) {return '<a href=\"'+data.record.url+'\">'+data.record."+jtopts['fields'][0]+"+'</a>';}"
return jtable
def generate_items_jtable(request, itype, option):
"""
Generate a jtable list for the Item provided.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param itype: The CRITs item we want to list.
:type itype: str
:param option: Action to take.
:type option: str of either 'jtlist', 'jtdelete', or 'inline'.
:returns: :class:`django.http.HttpResponse`
"""
obj_type = class_from_type(itype)
if itype == 'ActorThreatIdentifier':
fields = ['name', 'active', 'id']
click = "function () {window.parent.$('#actor_identifier_type_add').click();}"
elif itype == 'Campaign':
fields = ['name', 'description', 'active', 'id']
click = "function () {window.parent.$('#new-campaign').click();}"
elif itype == 'Action':
fields = ['name', 'active', 'object_types', 'preferred', 'id']
click = "function () {window.parent.$('#action_add').click();}"
elif itype == 'RawDataType':
fields = ['name', 'active', 'id']
click = "function () {window.parent.$('#raw_data_type_add').click();}"
elif itype == 'SignatureType':
fields = ['name', 'active', 'id']
click = "function () {window.parent.$('#signature_type_add').click();}"
elif itype == 'SignatureDependency':
fields = ['name', 'id']
click = "function () {window.parent.$('#signature_dependency_add').click();}"
elif itype == 'SourceAccess':
fields = ['name', 'active', 'id']
click = "function () {window.parent.$('#source_create').click();}"
if option == 'jtlist':
details_url = None
details_url_key = 'name'
response = jtable_ajax_list(obj_type, details_url, details_url_key,
request, includes=fields)
return HttpResponse(json.dumps(response, default=json_handler),
content_type="application/json")
'''Special case for dependency, to allow for deletions, no more toggle on dependencies '''
''' This is modified here to fit with rest of code, there is no delete field in mongo, but the user can delete '''
if itype == 'SignatureDependency':
fields = ['name', 'delete', 'id']
jtopts = {
'title': "%ss" % itype,
'default_sort': 'name ASC',
'listurl': reverse('crits-core-views-items_listing',
args=(itype, 'jtlist',)),
'deleteurl': None,
'searchurl': None,
'fields': fields,
'hidden_fields': ['id'],
'linked_fields': [],
'details_link': '',
}
jtable = build_jtable(jtopts, request)
jtable['toolbar'] = [
{
'tooltip': "'Add %s'" % itype,
'text': "'Add %s'" % itype,
'click': click,
},
]
for field in jtable['fields']:
if field['fieldname'].startswith("'active"):
field['display'] = """ function (data) {
return '<a id="is_active_' + data.record.id + '" href="#" onclick=\\'javascript:toggleItemActive("%s","'+data.record.id+'");\\'>' + data.record.active + '</a>';
}
""" % itype
if field['fieldname'].startswith("'name"):
field['display'] = """ function (data) { return '<a href="#" onclick=\\'javascript:editAction("'+data.record.name+'", "'+data.record.object_types+'", "'+data.record.preferred+'");\\'>' + data.record.name + '</a>';
}
"""
'''special case for signature dependency, add a delete button to allow for removal'''
if itype == 'SignatureDependency':
for field in jtable['fields']:
if field['fieldname'].startswith("'delete"):
field['display'] = """ function (data) {
return '<button title="Delete" class="jtable-command-button jtable-delete-command-button" id="to_delete_' + data.record.id + '" href="#" onclick=\\'javascript:deleteSignatureDependency("%s","'+data.record.id+'");\\'><span>Delete</span></button>';
}
""" % itype
if option == "inline":
return render(request, "jtable.html", {'jtable': jtable, 'jtid': '%ss_listing' % itype.lower(), 'button': '%ss_tab' % itype.lower()})
else:
return render(request, "item_editor.html",
{'jtable': jtable,
'jtid': 'items_listing'})
def generate_roles_jtable(request, option):
"""
Generate a jtable list for Roles.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param option: Action to take.
:type option: str of either 'jtlist', 'jtdelete', or 'inline'.
:returns: :class:`django.http.HttpResponse`
"""
obj_type = Role
itype = "Role"
mapper = obj_type._meta['jtable_opts']
if option == 'jtlist':
details_url = mapper['details_url']
details_url_key = mapper['details_url_key']
fields = mapper['fields']
response = jtable_ajax_list(obj_type,
details_url,
details_url_key,
request,
includes=fields)
return HttpResponse(json.dumps(response, default=json_handler),
content_type="application/json")
#TODO: make this delete a role and remove it from any users that have it.
# if option == "jtdelete":
jtopts = {
'title': "Roles",
'default_sort': mapper['default_sort'],
'listurl': reverse('crits-core-views-roles_listing', args=('jtlist',)),
'deleteurl': reverse('crits-core-views-roles_listing',
args=('jtdelete',)),
'searchurl': reverse(mapper['searchurl']),
'fields': mapper['jtopts_fields'],
'hidden_fields': mapper['hidden_fields'],
'linked_fields': mapper['linked_fields'],
'no_sort': mapper['no_sort']
}
jtable = build_jtable(jtopts, request)
jtable['toolbar'] = [
{
'tooltip': "'Add Role'",
'text': "'Add Role'",
'click': "function () {$('#new-role').click();}",
},
]
for field in jtable['fields']:
if field['fieldname'].startswith("'active"):
field['display'] = """ function (data) {
return '<a id="is_active_' + data.record.id + '" href="#" onclick=\\'javascript:toggleItemActive("%s","'+data.record.id+'");\\'>' + data.record.active + '</a>';
}
""" % itype
if option == "inline":
return render(request, "jtable.html",
{'jtable': jtable,
'jtid': 'roles_listing'})
else:
return render(request, "user_editor.html",
{'jtable': jtable,
'jtid': 'roles_listing'})
def generate_users_jtable(request, option):
"""
Generate a jtable list for Users.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param option: Action to take.
:type option: str of either 'jtlist', 'jtdelete', or 'inline'.
:returns: :class:`django.http.HttpResponse`
"""
obj_type = CRITsUser
if option == 'jtlist':
details_url = None
details_url_key = 'username'
fields = ['username', 'first_name', 'last_name', 'email',
'last_login', 'organization', 'is_active',
'id', 'roles']
excludes = ['login_attempts']
response = jtable_ajax_list(obj_type, details_url, details_url_key,
request, includes=fields,
excludes=excludes)
return HttpResponse(json.dumps(response, default=json_handler),
content_type="application/json")
jtopts = {
'title': "Users",
'default_sort': 'last_login DESC',
'listurl': reverse('crits-core-views-users_listing', args=('jtlist',)),
'deleteurl': None,
'searchurl': None,
'fields': ['username', 'first_name', 'last_name', 'email',
'last_login', 'organization', 'is_active',
'id', 'roles'],
'hidden_fields': ['id'],
'linked_fields': []
}
jtable = build_jtable(jtopts, request)
jtable['toolbar'] = [
{
'tooltip': "'Add User'",
'text': "'Add User'",
'click': "function () {editUser('');}",
},
]
for field in jtable['fields']:
if field['fieldname'].startswith("'username"):
field['display'] = """ function (data) {
return '<a class="user_edit" href="#" onclick=\\'javascript:editUser("'+data.record.username+'");\\'>' + data.record.username + '</a>';
}
"""
if field['fieldname'].startswith("'is_active"):
field['display'] = """ function (data) {
return '<a id="is_active_' + data.record.username + '" href="#" onclick=\\'javascript:toggleUserActive("'+data.record.username+'");\\'>' + data.record.is_active + '</a>';
}
"""
if option == "inline":
return render(request, "jtable.html",
{'jtable': jtable,
'jtid': 'users_listing'})
else:
return render(request, "user_editor.html",
{'jtable': jtable,
'jtid': 'users_listing'})
def generate_dashboard(request):
"""
Generate the Dashboard.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
from crits.dashboards.handlers import get_dashboard
args = get_dashboard(request.user)
return render(request, 'dashboard.html', args)
def dns_timeline(query, analyst, sources):
"""
Query for domains, format that data for timeline view, and return them.
:param query: The query to use to find the Domains.
:type query: dict
:param analyst: The user requesting the timeline.
:type analyst: str
:param sources: List of user's sources.
:type sources: list
:returns: list of dictionaries.
"""
domains = Domain.objects(__raw__=query)
offline = ['255.255.255.254', '127.0.0.1', '127.0.0.2', '0.0.0.0']
event_id = 0
events = []
for d in domains:
d.sanitize_sources(username=analyst,
sources=sources)
domain = d.domain
state = "off"
ip_list = [r for r in d.relationships if r.rel_type == 'IP']
ip_list = sorted(ip_list, key=itemgetter('relationship_date'), reverse=False)
description = ""
e = {}
for ipl in ip_list:
ip = IP.objects(ip=ipl.object_id,
source__name__in=sources).first()
if ipl['relationship_date'] is None:
continue
e['id'] = event_id
e['date_display'] = "hour"
e['importance'] = 20
e['icon'] = "halfcircle_blue.png"
event_id += 1
if ip and ip.ip in offline:
if state == "on":
e['enddate'] = datetime.datetime.strftime(ipl['relationship_date'],
settings.PY_DATETIME_FORMAT)
e['description'] = description
state = "off"
events.append(e)
description = ""
e = {}
elif state == "off":
pass
elif ip:
if state == "on":
description += "<br /><b><a style=\"display: inline;\" href=\"%s\">%s</a>:</b> %s" % (reverse('crits-ips-views-ip_detail', args=[ip.ip]), ip.ip, ipl['relationship_date'])
elif state == "off":
e['startdate'] = datetime.datetime.strftime(ipl['relationship_date'],
settings.PY_DATETIME_FORMAT)
e['title'] = domain
description += "<br /><b><a style=\"display: inline;\" href=\"%s\">%s</a>:</b> %s" % (reverse('crits-ips-views-ip_detail', args=[ip.ip]), ip.ip, ipl['relationship_date'])
state = "on"
return events
def email_timeline(query, analyst, sources):
"""
Query for emails, format that data for timeline view, and return them.
:param query: The query to use to find the Emails.
:type query: dict
:param analyst: The user requesting the timeline.
:type analyst: str
:param sources: List of user's sources.
:type sources: list
:returns: list of dictionaries.
"""
emails = Email.objects(__raw__=query)
events = []
event_id = 0
for email in emails:
email.sanitize_sources(username=analyst,
sources=sources)
email = email.to_dict()
if "source" in email and email["source"][0] is not None:
e = {}
e['title'] = ""
e['id'] = event_id
e['date_display'] = "hour"
e['importance'] = 20
e['icon'] = "halfcircle_blue.png"
event_id += 1
if "from" in email:
if email["from"]:
e['title'] += email["from"]
if "campaign" in email:
try:
if "name" in email["campaign"][0]:
e['title'] += " (%s)" % email["campaign"][0]["name"]
except:
pass
if "source" in email:
if "name" in email["source"][0]:
e['title'] += " (%s)" % email["source"][0]["name"]
description = ""
sources = []
if "from" in email:
description += "<br /><b>%s</b>: <a style=\"display: inline;\" href=\"%s\">%s</a>" % \
(email["from"],
reverse('crits-emails-views-email_detail', args=[email['_id']]),
email["from"])
if "isodate" in email:
e['startdate'] = "%s" % email["isodate"]
else:
if "source" in email:
e['startdate'] = "%s" % email["source"][0]['instances'][0]["date"]
if "source" in email:
description += "<br /><hr><b>Source:</b>"
for source in email["source"]:
if "name" in source and "instances" in source:
description += "<br /><b>%s</b>: %s" % (source["name"],
source['instances'][0]["date"])
e['description'] = description
events.append(e)
return events
def indicator_timeline(query, analyst, sources):
"""
Query for indicators, format that data for timeline view, and return them.
:param query: The query to use to find the Indicators.
:type query: dict
:param analyst: The user requesting the timeline.
:type analyst: str
:param sources: List of user's sources.
:type sources: list
:returns: list of dictionaries.
"""
indicators = Indicator.objects(__raw__=query)
events = []
event_id = 0
for indicator in indicators:
indicator.sanitize_sources(username=analyst,
sources=sources)
indicator = indicator.to_dict()
e = {}
e['title'] = indicator['value']
e['id'] = event_id
e['date_display'] = "hour"
e['importance'] = 20
e['icon'] = "halfcircle_blue.png"
event_id += 1
e['startdate'] = indicator['created'].strftime("%Y-%m-%d %H:%M:%S.%Z")
description = ""
description += "<br /><b>Value</b>: <a style=\"display: inline;\" href=\"%s\">%s</a>" % (reverse('crits-indicators-views-indicator', args=[indicator['_id']]), indicator['value'])
description += "<br /><b>Type</b>: %s" % indicator['type']
description += "<br /><b>Created</b>: %s" % indicator['created']
e['description'] = description
events.append(e)
return events
def generate_user_profile(username, request):
"""
Generate the user profile page.
:param username: The user profile to generate.
:type username: str
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
user_source_access = user_sources(username)
user_source_access.sort()
limit = 5
user_info = CRITsUser.objects(username=username).first()
if not user_info:
return {"status": "ERROR", "message": "User not found"}
# recent indicators worked on
query = {'$or': [{'actions.analyst': "%s" % username},
{'activity.analyst': "%s" % username},
{'objects.analyst': "%s" % username}]}
indicator_list = (Indicator.objects(__raw__=query)
.only('value',
'ind_type',
'created',
'campaign',
'source',
'status')
.order_by('-created')
.limit(limit)
.sanitize_sources(username))
# recent emails worked on
query = {'campaign.analyst': "%s" % username}
email_list = (Email.objects(__raw__=query)
.order_by('-date')
.limit(limit)
.sanitize_sources(username))
# samples
sample_md5s = (AuditLog.objects(user=username,
target_type="Sample")
.order_by('-date')
.limit(limit))
md5s = []
for sample in sample_md5s:
md5s.append(sample.value.split(" ")[0])
filter_data = ('md5', 'source', 'filename', 'mimetype',
'size', 'campaign')
sample_list = (Sample.objects(md5__in=md5s)
.only(*filter_data)
.sanitize_sources(username))
subscriptions = user_info.subscriptions
subscription_count = 0
# collect subscription information
if 'Sample' in subscriptions:
subscription_count += len(subscriptions['Sample'])
final_samples = []
ids = [ObjectId(s['_id']) for s in subscriptions['Sample']]
samples = Sample.objects(id__in=ids).only('md5', 'filename')
m = map(itemgetter('_id'), subscriptions['Sample'])
for sample in samples:
s = sample.to_dict()
s['md5'] = sample['md5']
s['id'] = sample.id
s['date'] = subscriptions['Sample'][m.index(sample.id)]['date']
final_samples.append(s)
subscriptions['Sample'] = final_samples
if 'PCAP' in subscriptions:
subscription_count += len(subscriptions['PCAP'])
final_pcaps = []
ids = [ObjectId(p['_id']) for p in subscriptions['PCAP']]
pcaps = PCAP.objects(id__in=ids).only('md5', 'filename')
m = map(itemgetter('_id'), subscriptions['PCAP'])
for pcap in pcaps:
p = pcap.to_dict()
p['id'] = pcap.id
p['date'] = subscriptions['PCAP'][m.index(pcap.id)]['date']
final_pcaps.append(p)
subscriptions['PCAP'] = final_pcaps
if 'Email' in subscriptions:
subscription_count += len(subscriptions['Email'])
final_emails = []
ids = [ObjectId(e['_id']) for e in subscriptions['Email']]
emails = Email.objects(id__in=ids).only('from_address',
'sender',
'subject')
m = map(itemgetter('_id'), subscriptions['Email'])
for email in emails:
e = email.to_dict()
e['id'] = email.id
e['date'] = subscriptions['Email'][m.index(email.id)]['date']
final_emails.append(e)
subscriptions['Email'] = final_emails
if 'Indicator' in subscriptions:
subscription_count += len(subscriptions['Indicator'])
final_indicators = []
ids = [ObjectId(i['_id']) for i in subscriptions['Indicator']]
indicators = Indicator.objects(id__in=ids).only('value', 'ind_type')
m = map(itemgetter('_id'), subscriptions['Indicator'])
for indicator in indicators:
i = indicator.to_dict()
i['id'] = indicator.id
i['date'] = subscriptions['Indicator'][m.index(indicator.id)]['date']
final_indicators.append(i)
subscriptions['Indicator'] = final_indicators
if 'Event' in subscriptions:
subscription_count += len(subscriptions['Event'])
final_events = []
ids = [ObjectId(v['_id']) for v in subscriptions['Event']]
events = Event.objects(id__in=ids).only('title', 'description')
m = map(itemgetter('_id'), subscriptions['Event'])
for event in events:
e = event.to_dict()
e['id'] = event.id
e['date'] = subscriptions['Event'][m.index(event.id)]['date']
final_events.append(e)
subscriptions['Event'] = final_events
if 'Domain' in subscriptions:
subscription_count += len(subscriptions['Domain'])
final_domains = []
ids = [ObjectId(d['_id']) for d in subscriptions['Domain']]
domains = Domain.objects(id__in=ids).only('domain')
m = map(itemgetter('_id'), subscriptions['Domain'])
for domain in domains:
d = domain.to_dict()
d['id'] = domain.id
d['date'] = subscriptions['Domain'][m.index(domain.id)]['date']
final_domains.append(d)
subscriptions['Domain'] = final_domains
if 'IP' in subscriptions:
subscription_count += len(subscriptions['IP'])
final_ips = []
ids = [ObjectId(a['_id']) for a in subscriptions['IP']]
ips = IP.objects(id__in=ids).only('ip')
m = map(itemgetter('_id'), subscriptions['IP'])
for ip in ips:
i = ip.to_dict()
i['id'] = ip.id
i['date'] = subscriptions['IP'][m.index(ip.id)]['date']
final_ips.append(i)
subscriptions['IP'] = final_ips
if 'Campaign' in subscriptions:
subscription_count += len(subscriptions['Campaign'])
final_campaigns = []
ids = [ObjectId(c['_id']) for c in subscriptions['Campaign']]
campaigns = Campaign.objects(id__in=ids).only('name')
m = map(itemgetter('_id'), subscriptions['Campaign'])
for campaign in campaigns:
c = campaign.to_dict()
c['id'] = campaign.id
c['date'] = subscriptions['Campaign'][m.index(campaign.id)]['date']
final_campaigns.append(c)
subscriptions['Campaign'] = final_campaigns
# Collect favorite information
favorites = user_info.favorites.to_dict()
collected_favorites = {}
total_favorites = 0
for type_ in favorites.keys():
ids = [ObjectId(f) for f in favorites[type_]]
if ids:
count = class_from_type(type_).objects(id__in=ids).count()
else:
count = 0
total_favorites += count
url = reverse('crits-core-views-favorites_list', args=(type_, 'inline'))
collected_favorites[type_] = {
'count': count,
'url': url
}
#XXX: this can be removed after jtable
notifications = get_user_notifications(username)
result = {'username': username,
'user_info': user_info,
'user_sources': user_source_access,
'indicators': indicator_list,
'emails': email_list,
'favorites': collected_favorites,
'total_favorites': total_favorites,
'notifications': notifications,
'samples': sample_list,
'subscriptions': subscriptions,
'subscription_count': subscription_count,
'ui_themes': ui_themes(),
'rt_url': settings.RT_URL}
result['preferences'] = generate_user_preference(request)
return result
def generate_favorites_jtable(request, type_, option):
"""
Generate favorites jtable.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param type_: The type of CRITs object.
:type type_: str
:returns: :class:`django.http.HttpResponse`
"""
klass = class_from_type(type_)
mapper = klass._meta['jtable_opts']
if option == "jtlist":
# Sets display url
details_url = mapper['details_url']
details_url_key = mapper['details_url_key']
fields = mapper['fields']
user = CRITsUser.objects(username=request.user.username).only('favorites').first()
favorites = user.favorites.to_dict()
ids = [ObjectId(s) for s in favorites[type_]]
query = {'_id': {'$in': ids}}
response = jtable_ajax_list(klass,
details_url,
details_url_key,
request,
includes=fields,
query=query)
return HttpResponse(json.dumps(response,
default=json_handler),
content_type="application/json")
jtopts = {
'title': type_ + 's',
'default_sort': mapper['default_sort'],
'listurl': reverse('crits-core-views-favorites_list', args=(type_, 'jtlist')),
'searchurl': reverse(mapper['searchurl']),
'fields': mapper['jtopts_fields'],
'hidden_fields': mapper['hidden_fields'],
'linked_fields': mapper['linked_fields'],
'details_link': mapper['details_link'],
'no_sort': mapper['no_sort']
}
jtable = build_jtable(jtopts, request)
if option == "inline":
return render(request, "jtable.html",
{'jtable': jtable,
'jtid': '%s_listing' % type_,
'button' : '%ss_tab' % type_})
else:
return render(request, "%s_listing.html" % type_,
{'jtable': jtable,
'jtid': '%s_listing' % type_})
def generate_user_preference(request,section=None,key=None,name=None):
"""
Generate user preferences.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param section: The section of the preferences to return.
:type section: str
:param key: The specific preference field within the section
to be retrieved.
:type key: str
:param name: The section of the preferences to return.
:type name: This is used to differentiate between different
preference under the same "section" and "key".
Otherwise the first "section" name that matches will
be returned. For example there may be two
different "notify" sections and also
two different "toggle" keys. But the "key" matching
the "name" value will be returned.
:returns: list
"""
# Returned as an array to maintain the order
# could also have a key/value and a ordered array
from crits.core.forms import PrefUIForm, NavMenuForm, ToastNotificationConfigForm
toast_notifications_title = "Toast Notifications"
config = CRITsConfig.objects().first()
if not config.enable_toasts:
toast_notifications_title += " (currently globally disabled by an admin)"
preferences = [
{'section': 'notify',
'title': 'Notifications',
'toggle': 'email',
'enabled': get_user_email_notification(request.user.username),
'name': 'Email Notifications'
},
{'section': 'toast_notifications',
'title': toast_notifications_title,
'form': ToastNotificationConfigForm(request),
'formclass': ToastNotificationConfigForm,
},
{'section': 'ui',
'title': 'UI Settings',
'form': PrefUIForm(request),
'formclass': PrefUIForm,
'reload': True },
{'section': 'nav',
'form': NavMenuForm(request),
'formclass': NavMenuForm,
'name': 'Navigation Menu',
'title': 'Navigation Menu',
'reload': True },
]
# Only return the requested section as hash
if section:
for pref in preferences:
if key:
if pref['section'] == section and pref[key] == name:
return pref
else:
if pref['section'] == section:
return pref
return preferences
def reset_user_password(username=None, action=None, email=None,
submitted_rcode=None, new_p=None, new_p_c=None,
analyst=None):
"""
Handle the process of resetting a user's password.
:param username: The user resetting their password.
:type username: str
:param action: What action we need to take:
- send_email: sends email to user with reset code
- submit_reset_code: validate the reset code
- submit_passwords: reset the password
:type action: str
:param email: The user's email address.
:type email: str
:param submitted_rcode: The reset code submitted by the user.
:type submitted_rcode: str
:param new_p: The new password provided by the user.
:type new_p: str
:param new_p_c: The new password confirmation provided by the user.
:type new_p_c: str
:param analyst: The user submitting these changes.
:type analyst: str
:returns: :class:`django.http.HttpResponse`
"""
if action not in ('send_email', 'submit_reset_code', 'submit_passwords'):
response = {'success': False, 'message': 'Invalid action'}
return HttpResponse(json.dumps(response, default=json_handler),
content_type="application/json")
user = CRITsUser.objects(username=username, email=email).first()
if not user:
# make it seem like this worked even if it didn't to prevent people
# from brute forcing usernames and email addresses.
response = {'success': True, 'message': 'Instructions sent to %s' % email}
return HttpResponse(json.dumps(response, default=json_handler),
content_type="application/json")
if action == 'send_email':
rcode = user.set_reset_code(analyst)
crits_config = CRITsConfig.objects().first()
if crits_config.crits_email_end_tag:
subject = "CRITs Password Reset" + crits_config.crits_email_subject_tag
else:
subject = crits_config.crits_email_subject_tag + "CRITs Password Reset"
body = """You are receiving this email because someone has requested a
password reset for your account. If it was not you, please log
into CRITs immediately which will remove the reset code from your
account. If it was you, here is your reset code:\n\n
"""
body += "%s\n\n" % rcode
body += """You have five minutes to reset your password before this
reset code expires.\n\nThank you!
"""
user.email_user(subject, body)
response = {'success': True, 'message': 'Instructions sent to %s' % email}
return HttpResponse(json.dumps(response, default=json_handler),
content_type="application/json")
if action == 'submit_reset_code':
return HttpResponse(json.dumps(user.validate_reset_code(submitted_rcode,
analyst),
default=json_handler),
content_type="application/json")
if action == 'submit_passwords':
return HttpResponse(json.dumps(user.reset_password(submitted_rcode,
new_p, new_p_c,
analyst),
default=json_handler),
content_type="application/json")
def login_user(username, password, next_url=None, user_agent=None,
remote_addr=None, accept_language=None, request=None,
totp_pass=None):
"""
Handle the process of authenticating a user.
:param username: The user authenticating to the system.
:type username: str
:param password: The password provided by the user.
:type password: str
:param next_url: The URL to redirect to after successful login.
:type next_url: str
:param user_agent: The user-agent of the request.
:type user_agent: str
:param remote_addr: The remote-address of the request.
:type remote_addr: str
:param accept_language: The accept-language of the request.
:type accept_language: str
:param request: The request.
:type request: :class:`django.http.HttpRequest`
:param totp_pass: The TOTP password provided by the user.
:type totp_pass: str
:returns: dict with keys:
"success" (boolean),
"type" (str) - Type of failure,
"message" (str)
"""
error = 'Unknown user or bad password.'
response = {}
crits_config = CRITsConfig.objects().first()
if not crits_config:
response['success'] = False
response['type'] = "login_failed"
response['message'] = error
return response
if request:
totp = crits_config.totp_web
else:
totp = crits_config.totp_cli
# Do the username and password authentication
# TOTP is passed here so that authenticate() can check if
# the threshold has been exceeded.
user = authenticate(username=username,
password=password,
user_agent=user_agent,
remote_addr=remote_addr,
accept_language=accept_language,
totp_enabled=totp)
if user:
if totp == 'Required' or (totp == 'Optional' and user.totp):
# Remote user auth'd but has not seen TOTP screen yet
if crits_config.remote_user and not totp_pass:
response['success'] = False
response['type'] = "totp_required"
response['message'] = "TOTP required"
return response
e = EmbeddedLoginAttempt(user_agent=user_agent,
remote_addr=remote_addr,
accept_language=accept_language)
secret = user.secret
if not secret and not totp_pass:
response['success'] = False
response['type'] = "no_secret"
response['message'] = ("You have no TOTP secret. Please enter "
"a new PIN in the TOTP field.")
return response
elif not secret and totp_pass:
response['success'] = False
response['type'] = "secret_generated"
res = save_user_secret(username, totp_pass, "crits", (200,200))
if res['success']:
user.reload()
secret = res['secret']
if not request:
response['secret'] = secret
return response
message = "Setup your authenticator using: '%s'" % secret
message += "<br />Then authenticate again with your PIN + token."
if res['qr_img']:
message += '<br /><img src="data:image/png;base64,'
message += '%s" />' % res['qr_img']
response['message'] = message
else:
response['message'] = "Secret Generation Failed"
return response
elif not valid_totp(username, totp_pass, secret):
e.success = False
user.login_attempts.append(e)
user.invalid_login_attempts += 1
user.save()
response['success'] = False
response['type'] = "login_failed"
response['message'] = error
return response
e.success = True
user.login_attempts.append(e)
user.save()
if user.is_active:
user.get_access_list(update=True)
user.invalid_login_attempts = 0
user.password_reset.reset_code = ""
user.save()
if crits_config and request:
request.session.set_expiry(crits_config.session_timeout * 60 * 60)
elif request:
request.session.set_expiry(settings.SESSION_TIMEOUT)
if request:
user_login(request, user)
response['type'] = "login_successful"
# Redirect to next or default dashboard
if next_url is not None and next_url != '' and next_url != 'None':
response.update(validate_next(next_url))
return response
response['success'] = True
if 'message' not in response:
response['message'] = reverse('crits-dashboards-views-dashboard')
return response
else:
logger.info("Attempted login to a disabled account detected: %s" %
user.username)
response['success'] = False
response['type'] = "login_failed"
response['message'] = error
return response
def validate_next(next_url=None):
"""
Validate that the next_url is valid and redirect, or invalid and proceed to
the error page.
:param next_url: The next url to go to.
:type next_url: str
:returns: dict
"""
response = {}
try:
# test that we can go from URL to view to URL
# to validate the URL is something we know about.
# We use get_script_prefix() here to tell us what
# the script prefix is configured in Apache.
# We strip it out so resolve can work properly, and then
# redirect to the full url.
prefix = get_script_prefix()
tmp_url = next_url
if next_url.startswith(prefix):
tmp_url = tmp_url.replace(prefix, '/', 1)
next_url = urlunquote(tmp_url)
if not is_safe_url(next_url):
raise Exception
resolve(urlparse(next_url).path)
response['success'] = True
response['type'] = "already_authenticated"
response['message'] = next_url
except Exception:
response['success'] = False
response['message'] = 'ALERT - attempted open URL redirect attack to %s. Please report this to your system administrator.' % next_url
logger.info('ALERT: redirect attack: %s' % next_url)
return response
def generate_global_search(request):
"""
Generate global search results.
:param request: The request.
:type request: :class:`django.http.HttpRequest`
:returns: dict with keys:
"url_params" (str),
"term" (str) - the search term,
"results" (list),
"Result" (str of "OK" or "ERROR")
"""
# Perform rapid search for ObjectID strings
searchtext = request.GET['q']
if ObjectId.is_valid(searchtext):
for obj_type, url, key in [
['Actor', 'crits-actors-views-actor_detail', 'id'],
['Backdoor', 'crits-backdoors-views-backdoor_detail', 'id'],
['Campaign', 'crits-campaigns-views-campaign_details', 'name'],
['Certificate', 'crits-certificates-views-certificate_details', 'md5'],
['Domain', 'crits-domains-views-domain_detail', 'domain'],
['Email', 'crits-emails-views-email_detail', 'id'],
['Event', 'crits-events-views-view_event', 'id'],
['Exploit', 'crits-exploits-views-exploit_detail', 'id'],
['Indicator', 'crits-indicators-views-indicator', 'id'],
['IP', 'crits-ips-views-ip_detail', 'ip'],
['PCAP', 'crits-pcaps-views-pcap_details', 'md5'],
['RawData', 'crits-raw_data-views-raw_data_details', 'id'],
['Sample', 'crits-samples-views-detail', 'md5'],
['Signature', 'crits-signatures-views-signature_detail', 'id'],
['Target', 'crits-targets-views-target_info', 'email_address']]:
obj = class_from_id(obj_type, searchtext)
if obj:
return {'url': url, 'key': obj[key]}
# Importing here to prevent a circular import with Services and runscript.
from crits.services.analysis_result import AnalysisResult
results = []
for col_obj,url in [
[Actor, "crits-actors-views-actors_listing"],
[AnalysisResult, "crits-services-views-analysis_results_listing"],
[Backdoor, "crits-backdoors-views-backdoors_listing"],
[Campaign, "crits-campaigns-views-campaigns_listing"],
[Certificate, "crits-certificates-views-certificates_listing"],
[Comment, "crits-comments-views-comments_listing"],
[Domain, "crits-domains-views-domains_listing"],
[Email, "crits-emails-views-emails_listing"],
[Event, "crits-events-views-events_listing"],
[Exploit, "crits-exploits-views-exploits_listing"],
[Indicator,"crits-indicators-views-indicators_listing"],
[IP, "crits-ips-views-ips_listing"],
[PCAP, "crits-pcaps-views-pcaps_listing"],
[RawData, "crits-raw_data-views-raw_data_listing"],
[Sample, "crits-samples-views-samples_listing"],
[Screenshot, "crits-screenshots-views-screenshots_listing"],
[Signature, "crits-signatures-views-signatures_listing"],
[Target, "crits-targets-views-targets_listing"]]:
ctype = col_obj._meta['crits_type']
resp = get_query(col_obj, request)
if resp['Result'] == "ERROR":
return resp
elif resp['Result'] == "IGNORE":
results.append({'count': 0,
'url': url,
'name': ctype})
else:
formatted_query = resp['query']
term = resp['term']
urlparams = resp['urlparams']
resp = data_query(col_obj, request.user, query=formatted_query, count=True)
results.append({'count': resp['count'],
'url': url,
'name': ctype})
return {'url_params': urlparams,
'term': term,
'results': results,
'Result': "OK"}
def download_grid_file(request, dtype, sample_md5):
"""
Download a file from GriDFS. The file will get zipped up.
This should go away and get roped into our other download feature.
:param request: The request.
:type request: :class:`django.http.HttpRequest`
:param dtype: 'pcap', 'object', or 'cert'.
:type dtype: str
:param sample_md5: The MD5 of the file to download.
:type sample_md5: str
:returns: :class:`django.http.HttpResponse`
"""
if dtype == 'object':
grid = mongo_connector("%s.files" % settings.COL_OBJECTS)
obj = grid.find_one({'md5': sample_md5})
if obj is None:
dtype = 'pcap'
else:
data = [(obj['filename'], get_file(sample_md5, "objects"))]
zip_data = create_zip(data, False)
response = HttpResponse(zip_data, content_type="application/octet-stream")
response['Content-Disposition'] = 'attachment; filename=%s' % obj['filename'] + ".zip"
return response
if dtype == 'pcap':
pcaps = mongo_connector(settings.COL_PCAPS)
pcap = pcaps.find_one({"md5": sample_md5})
if not pcap:
return render(request, 'error.html',
{'data': request,
'error': "File not found."})
data = [(pcap['filename'], get_file(sample_md5, "pcaps"))]
zip_data = create_zip(data, False)
response = HttpResponse(zip_data, content_type="application/octet-stream")
response['Content-Disposition'] = 'attachment; filename=%s' % pcap['filename'] + ".zip"
return response
if dtype == 'cert':
certificates = mongo_connector(settings.COL_CERTIFICATES)
cert = certificates.find_one({"md5": sample_md5})
if not cert:
return render(request, 'error.html',
{'data': request,
'error': "File not found."})
data = [(cert['filename'], get_file(sample_md5, "certificates"))]
zip_data = create_zip(data, False)
response = HttpResponse(zip_data, content_type="application/octet-stream")
response['Content-Disposition'] = 'attachment; filename=%s' % cert['filename'] + ".zip"
return response
def generate_counts_jtable(request, option):
"""
Generate the jtable data for counts.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param option: Action to take.
:type option: str of either 'jtlist', 'jtdelete', or 'inline'.
:returns: :class:`django.http.HttpResponse`
"""
if option == "jtlist":
count = mongo_connector(settings.COL_COUNTS)
counts = count.find_one({'name': 'counts'})
response = {}
response['Result'] = "OK"
response['Records'] = []
if counts:
for k, v in sorted(counts['counts'].items()):
record = {}
record['type'] = k
record['count'] = v
record['id'] = 0
record['url'] = ""
response['Records'].append(record)
return HttpResponse(json.dumps(response,
default=json_handler),
content_type="application/json")
else:
return render(request, 'error.html',
{'data': request,
'error': "Invalid request"})
def generate_audit_csv(request):
"""
Generate a CSV file of the audit log entries
:param request: The request for this CSV.
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
return csv_export(request, AuditLog)
def generate_audit_jtable(request, option):
"""
Generate the jtable data for audit log entries.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param option: Action to take.
:type option: str of either 'jtlist', 'jtdelete', or 'inline'.
:returns: :class:`django.http.HttpResponse`
"""
obj_type = AuditLog
type_ = "audit"
if option == "jtlist":
# Sets display url
details_url = 'crits-core-views-details'
details_url_key = "target_id"
response = jtable_ajax_list(obj_type,
details_url,
details_url_key,
request)
return HttpResponse(json.dumps(response,
default=json_handler),
content_type="application/json")
jtopts = {
'title': "Audit Log Entries",
'default_sort': "date DESC",
'listurl': reverse('crits-core-views-%s_listing' % type_,
args=('jtlist',)),
'deleteurl': '',
'searchurl': reverse('crits-core-views-%s_listing' % type_),
'fields': ["details",
"user",
"type",
"method",
"value",
"date",
"id"],
'hidden_fields': ["id"],
'linked_fields': [],
'details_link': 'details',
'no_sort': ['details', ],
}
jtable = build_jtable(jtopts, request)
jtable['toolbar'] = []
if option == "inline":
return render(request, "jtable.html",
{'jtable': jtable,
'jtid': '%s_listing' % type_,
'button': '%ss_tab' % type_})
else:
return render(request, "%s_listing.html" % type_,
{'jtable': jtable,
'jtid': '%s_listing' % type_})
def details_from_id(type_, id_):
"""
Determine the details URL based on type and ID and redirect there.
:param type_: The CRITs type to search for.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:returns: str
"""
type_map = {'Actor': 'crits-actors-views-actor_detail',
'Backdoor': 'crits-backdoors-views-backdoor_detail',
'Campaign': 'crits-campaigns-views-campaign_details',
'Certificate': 'crits-certificates-views-certificate_details',
'Domain': 'crits-domains-views-domain_detail',
'Email': 'crits-emails-views-email_detail',
'Event': 'crits-events-views-view_event',
'Exploit': 'crits-exploits-views-exploit_detail',
'Indicator': 'crits-indicators-views-indicator',
'IP': 'crits-ips-views-ip_detail',
'PCAP': 'crits-pcaps-views-pcap_details',
'RawData': 'crits-raw_data-views-raw_data_details',
'Sample': 'crits-samples-views-detail',
'Screenshot': 'crits-screenshots-views-render_screenshot',
'Signature': 'crits-signatures-views-signature_detail',
'Target': 'crits-targets-views-target_info',
}
if type_ in type_map and id_:
if type_ == 'Campaign':
arg = class_from_id(type_, id_)
if arg:
arg = arg.name
elif type_ == 'Certificate':
arg = class_from_id(type_, id_)
if arg:
arg = arg.md5
elif type_ == 'Domain':
arg = class_from_id(type_, id_)
if arg:
arg = arg.domain
elif type_ == 'IP':
arg = class_from_id(type_, id_)
if arg:
arg = arg.ip
elif type_ == 'PCAP':
arg = class_from_id(type_, id_)
if arg:
arg = arg.md5
elif type_ == 'Sample':
arg = class_from_id(type_, id_)
if arg:
arg = arg.md5
elif type_ == 'Target':
arg = class_from_id(type_, id_)
if arg:
arg = arg.email_address
else:
arg = id_
if not arg:
return None
return reverse(type_map[type_], args=(arg,))
else:
return None
def audit_entry(self, username, type_, new_doc=False):
"""
Generate an audit entry.
:param self: The object.
:type self: class which inherits from
:class:`crits.core.crits_mongoengine.CritsBaseAttributes`
:param username: The user performing the action.
:type username: str
:param type_: The type of action being performed ("save", "delete").
:type type_: str
:param new_doc: If this is a new document being added to the database.
:type new_doc: boolean
"""
if username is None:
# If no username, skip the audit log
return
my_type = self._meta['crits_type']
# don't audit audits
if my_type in ("AuditLog", "Service"):
return
changed_fields = [f.split('.')[0] for f in self._get_changed_fields() if f not in ("modified",
"save",
"delete")]
# Remove any duplicate fields
changed_fields = list(set(changed_fields))
if new_doc and not changed_fields:
what_changed = "new document"
else:
what_changed = ', '.join(changed_fields)
key_descriptor = key_descriptor_from_obj_type(my_type)
if key_descriptor is not None:
value = getattr(self, key_descriptor, '')
else:
value = ""
if type_ == "save":
a = AuditLog()
a.user = username
a.target_type = my_type
a.target_id = self.id
a.value = what_changed
a.method = "save()"
try:
a.save()
except ValidationError:
pass
elif type_ == "delete":
a = AuditLog()
a.user = username
a.target_type = my_type
a.target_id = self.id
a.value = value
a.method = "delete()"
try:
a.save()
except ValidationError:
pass
# Generate audit notification
generate_audit_notification(username, type_, self, changed_fields, what_changed, new_doc)
def ticket_add(type_, id_, ticket, user, **kwargs):
"""
Add a ticket to a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param ticket: The ticket to add.
:type ticket: dict with keys "date", and "ticket_number".
:param user: The user creating the ticket.
:type user: str
:returns: dict with keys:
"success" (boolean),
"object" (str) if successful,
"message" (str) if failed.
"""
obj = class_from_id(type_, id_)
if not obj:
return {'success': False, 'message': 'Could not find object.'}
try:
ticket = datetime_parser(ticket)
ticket['analyst'] = user.username
obj.add_ticket(ticket['ticket_number'],
ticket['analyst'],
ticket['date'])
obj.save(username=user)
return {'success': True, 'object': ticket}
except (ValidationError, TypeError, KeyError), e:
return {'success': False, 'message': e}
def ticket_update(type_, id_, ticket, user=None, **kwargs):
"""
Update a ticket for a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param ticket: The ticket to add.
:type ticket: dict with keys "date", and "ticket_number".
:param date: The date of the ticket which will be updated.
:type date: datetime.datetime.
:param user: The user updating the ticket.
:type user: str
:returns: dict with keys:
"success" (boolean),
"object" (str) if successful,
"message" (str) if failed.
"""
obj = class_from_id(type_, id_)
if not obj:
return {'success': False, 'message': 'Could not find object.'}
try:
ticket = datetime_parser(ticket)
ticket['analyst'] = user
obj.edit_ticket(ticket['analyst'],
ticket['ticket_number'],
ticket['date'])
obj.save(username=user)
return {'success': True, 'object': ticket}
except (ValidationError, TypeError, KeyError), e:
return {'success': False, 'message': e}
def ticket_remove(type_, id_, date, user, **kwargs):
"""
Remove a ticket from a top-level object.
:param type_: The CRITs type of the top-level object.
:type type_: str
:param id_: The ObjectId to search for.
:type id_: str
:param date: The date of the ticket to remove.
:type date: datetime.datetime.
:param user: The user removing the ticket.
:type user: str
:returns: dict with keys:
"success" (boolean),
"message" (str) if failed.
"""
obj = class_from_id(type_, id_)
if not obj:
return {'success': False, 'message': 'Could not find object.'}
try:
date = datetime_parser(date)
obj.delete_ticket(date)
obj.save(username=user)
return {'success': True}
except ValidationError, e:
return {'success': False, 'message': e}
def unflatten(dictionary):
"""
Unflatten a dictionary.
:param dictionary: The dictionary to unflatten.
:type dictionary: dict
:returns: dict
"""
resultDict = dict()
for key, value in dictionary.iteritems():
parts = key.split(".")
d = resultDict
for part in parts[:-1]:
if part not in d:
d[part] = dict()
d = d[part]
d[parts[-1]] = value
return resultDict
def alter_sector_list(obj, sectors, val):
"""
Given a list of sectors on this object, increment or decrement
the sectors objects accordingly. This is used when adding
or removing a sector list to an item, and when deleting an item.
:param obj: The top-level object instantiated class.
:type obj: class which inherits from
:class:`crits.core.crits_mongoengine.CritsBaseAttributes`.
:param sectors: List of sectors.
:type sectors: list
:param val: The amount to change the count by.
:type val: int
"""
# This dictionary is used to set values on insert only.
# I haven't found a way to get mongoengine to use the defaults
# when doing update_one() on the queryset.
soi = { k: 0 for k in Sector._meta['schema_doc'].keys() if k != 'name' and k != obj._meta['crits_type'] }
soi['schema_version'] = Sector._meta['latest_schema_version']
# We are using mongo_connector here because mongoengine does not have
# support for a setOnInsert option. If mongoengine were to gain support
# for this we should switch to using it instead of pymongo here.
sectors_col = mongo_connector(settings.COL_SECTOR_LISTS)
for name in sectors:
sectors_col.update({'name': name},
{'$inc': {obj._meta['crits_type']: val},
'$setOnInsert': soi},
upsert=True)
# Find and remove this sector if, and only if, all counts are zero.
if val == -1:
Sector.objects(name=name,
Actor=0,
Campaign=0,
Certificate=0,
Domain=0,
Email=0,
Event=0,
Indicator=0,
IP=0,
PCAP=0,
RawData=0,
Sample=0,
Signature=0,
Target=0).delete()
def generate_sector_csv(request):
"""
Generate CSV output for the Sector list.
:param request: The request for this CSV.
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
return csv_export(request, Sector)
def generate_sector_jtable(request, option):
"""
Generate the jtable data for rendering in the sector list template.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param option: Action to take.
:type option: str of either 'jtlist', 'jtdelete', or 'inline'.
:returns: :class:`django.http.HttpResponse`
"""
if option == 'jtlist':
details_url = 'crits-core-views-sector_list'
details_key = 'name'
response = jtable_ajax_list(Sector,
details_url,
details_key,
request,
includes=['name',
'Actor',
'Backdoor',
'Campaign',
'Certificate',
'Domain',
'Email',
'Event',
'Exploit',
'Indicator',
'IP',
'PCAP',
'RawData',
'Sample',
'Signature',
'Target'])
return HttpResponse(json.dumps(response, default=json_handler),
content_type='application/json')
fields = ['name', 'Actor', 'Backdoor', 'Campaign', 'Certificate', 'Domain',
'Email', 'Event', 'Exploit', 'Indicator', 'IP', 'PCAP', 'RawData',
'Sample', 'Signature', 'Target']
jtopts = {'title': 'Sectors',
'fields': fields,
'listurl': 'jtlist',
'searchurl': reverse('crits-core-views-global_search_listing'),
'default_sort': 'name ASC',
'no_sort': [],
'details_link': ''}
jtable = build_jtable(jtopts, request)
for ctype in fields:
if ctype == 'id':
continue
elif ctype == 'name':
url = reverse('crits-core-views-global_search_listing') + '?search_type=sectors&search=Search&force_full=1'
else:
lower = ctype.lower()
if lower != "rawdata":
url = reverse('crits-%ss-views-%ss_listing' % (lower, lower))
else:
lower = "raw_data"
url = reverse('crits-%s-views-%s_listing' % (lower, lower))
for field in jtable['fields']:
if field['fieldname'].startswith("'" + ctype):
if ctype == 'name':
field['display'] = """ function (data) {
return '<a href="%s&q='+encodeURIComponent(data.record.name)+'">' + data.record.name + '</a>';
}
""" % url
else:
field['display'] = """ function (data) {
return '<a href="%s?sectors='+encodeURIComponent(data.record.name)+'">'+data.record.%s+'</a>';
}
""" % (url, ctype)
return render(request, 'sector_lists.html',
{'jtable': jtable,
'jtid': 'sector_lists'})
def modify_sector_list(itype, oid, sectors, analyst):
"""
Modify the sector list for a top-level object.
:param itype: The CRITs type of the top-level object to modify.
:type itype: str
:param oid: The ObjectId to search for.
:type oid: str
:param sectors: The list of sectors.
:type sectors: list
:param analyst: The user making the modifications.
"""
obj = class_from_id(itype, oid)
if not obj:
return
obj.add_sector_list(sectors, analyst, append=False)
try:
obj.save(username=analyst)
except ValidationError:
pass
def get_bucket_autocomplete(term):
"""
Get existing buckets to autocomplete.
:param term: The current term to look for autocomplete options.
:type term: str
:returns: list
"""
results = Bucket.objects(name__istartswith=term)
buckets = [b.name for b in results]
return HttpResponse(json.dumps(buckets, default=json_handler),
content_type='application/json')
def get_role_details(rid, roles, analyst):
"""
Generate the data to render the Role details template.
:param rid: The ObjectId of the Role to get details for.
:type rid: str
:param analyst: The user requesting this information.
:type analyst: str
:returns: template (str), arguments (dict)
"""
template = None
if rid:
role = Role.objects(id=rid).first()
if not role or role.name == settings.ADMIN_ROLE:
error = ("Either this Role does not exist or you do "
"not have permission to view it.")
template = "error.html"
args = {'error': error}
return template, args
show_roles = None
if roles:
if isinstance(roles, basestring):
roles = roles.split(',')
roles = [r.strip() for r in roles]
tmp = CRITsUser()
tmp.roles = roles
role = tmp.get_access_list()
rid = None
show_roles = roles
do_not_render = ['_id', 'schema_version']
if role != None:
from crits.core.forms import RoleSourceEdit
d = {'sources': [s['name'] for s in role['sources']]}
source_form = RoleSourceEdit(initial=d)
args = {'role': role.to_dict(),
'do_not_render': do_not_render,
'source_form': source_form,
'show_roles': show_roles,
"rid": rid}
return template, args
def edit_role_name(rid, old_name, name, analyst):
"""
Edit the name of a Role.
:param rid: The ObjectId of the role to alter.
:type rid: str
:param old_name: The name of the Role.
:type old_name: str
:param name: The new name of the Role.
:type name: str
:param analyst: The user making the change.
:type analyst: str
"""
name = name.strip()
if old_name != settings.ADMIN_ROLE and name != settings.ADMIN_ROLE:
Role.objects(id=rid,
name__ne=settings.ADMIN_ROLE).update_one(set__name=name)
CRITsUser.objects(roles=old_name).update(set__roles__S=name)
return {'success': True}
else:
return {'success': False}
def edit_role_description(rid, description, analyst):
"""
Edit the description of a role.
:param rid: The ObjectId of the role to alter.
:type rid: str
:param description: The new description for the Role.
:type description: str
:param analyst: The user making the change.
:type analyst: str
"""
description = description.strip()
Role.objects(id=rid,
name__ne=settings.ADMIN_ROLE).update_one(set__description=description)
return {'success': True}
def users_need_acl_updating(rid=None, rname=None):
"""
A role has been updated and users should be flagged to have their ACL
updated on the next ACL check.
:param rid: The ObjectID of the role in question.
:type rid: str
:param rname: The name of the role in question.
:type rname: str
"""
if rid:
rname = Role.objects(id=rid).first().name
if rname is None:
return
CRITsUser.objects(roles=rname).update(set__acl_needs_update=True, multi=True)
return
def add_role_source(rid, name, analyst):
"""
Add a source to a role.
:param rid: The ObjectId of the role to alter.
:type rid: str
:param name: The name of the source to add.
:type name: str
:param analyst: The user making the change.
:type analyst: str
"""
ed = {'name': name,
'read': False,
'write': False,
'tlp_red': False,
'tlp_amber': False,
'tlp_green': False}
d = {'push__sources': ed}
Role.objects(id=rid, name__ne=settings.ADMIN_ROLE).update_one(**d)
users_need_acl_updating(rid=rid)
html = render_to_string('role_source_item.html',
{'source': ed})
return {'success': True,
'html': html}
def remove_role_source(rid, name, analyst):
"""
Remove a source from a role.
:param rid: The ObjectId of the role to alter.
:type rid: str
:param name: The name of the source to remove.
:type name: str
:param analyst: The user making the change.
:type analyst: str
"""
d = {'pull__sources': {'name': name}}
Role.objects(id=rid, name__ne=settings.ADMIN_ROLE).update_one(**d)
users_need_acl_updating(rid=rid)
return {'success': True}
def set_role_value(rid, name, value, analyst):
"""
Set the value of a role item.
:param rid: The ObjectId of the role to alter.
:type rid: str
:param name: The name of the item to set.
:type name: str
:param value: The value to set.
:type value: boolean
:param analyst: The user making the change.
:type analyst: str
"""
if value in [1, '1', 'true', 'True', True]:
value = True
else:
value = False
if name.startswith("sources"):
d = name.split('__')
sname = d[1]
name = "%s__S__%s" % (d[0], d[2])
ud = {'set__%s' % name: value}
if name.startswith("sources"):
Role.objects(id=rid,
name__ne=settings.ADMIN_ROLE,
sources__name=sname).update_one(**ud)
else:
Role.objects(id=rid,name__ne=settings.ADMIN_ROLE).update_one(**ud)
users_need_acl_updating(rid=rid)
def add_new_role(name, copy_from, description, analyst):
"""
Add a new role to the system.
:param name: The name of the role.
:type name: str
:param copy_from: Copy this role from an existing role.
:type copy_from: str
:param analyst: The user adding the role.
:type analyst: str
:returns: True, False
"""
name = name.strip()
if name == settings.ADMIN_ROLE:
return False
if copy_from:
role = Role.objects(id=copy_from).first()
else:
role = Role()
role.name = name
if not len(description):
description = "None"
role.description = description
role.id = None
# hack because MongoEngine makes this false if you unset the id
role._created = True
try:
role.save(username=analyst)
role.reload()
return {'success': True,
'id': str(role.id)}
except ValidationError:
return {'success': False}
def render_role_graph(start_type="roles", start_node=None, expansion_node=None,
analyst=None):
"""
Gather the necessary data to render the Role graph. The format of a node is:
{'name': Name of node.
'childen': [{'name': Name of child',
'size': Size for child (if doesn't have more children).
}]
}
:param start_type: The starting type. Must be "roles", "sources", or "users".
:type start_type: str
:param start_node: The first node to render sub-nodes for.
:type start_node: str
:param expansion_node: The 3rd-level node to expand.
:type expansion_node: str
:returns: dict
"""
data = {'children': []}
url = reverse('crits-core-views-role_graph')
# Roles (default)
if start_type == "role" or start_type not in ['source', 'user']:
data['name'] = "Roles"
roles = Role.objects()
for role in roles:
role_dict = {'name': role.name,
'children': []}
if role.name == start_node:
role_dict['expand'] = True
else:
role_dict['expand'] = False
# get sources
source_list = {'name': 'Sources',
'children': []}
if expansion_node and expansion_node.lower() == 'sources':
source_list['expand'] = True
else:
source_list['expand'] = False
for source in role.sources:
d = {'name': source.name,
'url': "%s?start_type=source&start_node=%s" % (url,
source.name),
'size': 3000}
source_list['children'].append(d)
role_dict['children'].append(source_list)
# get users
user_list = {'name': 'Users',
'children': []}
if expansion_node and expansion_node.lower() == 'users':
user_list['expand'] = True
else:
user_list['expand'] = False
users = CRITsUser.objects(roles=role.name)
for user in users:
d = {'name': user.username,
'url': "%s?start_type=user&start_node=%s" % (url,
user.username),
'size': 3000}
user_list['children'].append(d)
role_dict['children'].append(user_list)
# populate
data['children'].append(role_dict)
# Sources
if start_type == "source":
data['name'] = "Sources"
sources = SourceAccess.objects()
for source in sources:
source_dict = {'name': source.name,
'children': []}
if source.name == start_node:
source_dict['expand'] = True
else:
source_dict['expand'] = False
users_dict = {'name': 'Users',
'children': []}
users_list = []
if expansion_node and expansion_node.lower() == 'users':
users_dict['expand'] = True
else:
users_dict['expand'] = False
# get roles
roles = Role.objects(sources__name=source.name)
for role in roles:
role_dict = {'name': role.name,
'url': "%s?start_type=role&start_node=%s" % (url,
role.name),
'children': []}
if expansion_node and expansion_node == role.name:
role_dict['expand'] = True
else:
role_dict['expand'] = False
users = CRITsUser.objects(roles=role.name)
for user in users:
d = {'name': user.username,
'url': "%s?start_type=user&start_node=%s" % (url,
user.username),
'size': 3000}
role_dict['children'].append(d)
if user.username not in users_list:
users_dict['children'].append(d)
users_list.append(user.username)
source_dict['children'].append(role_dict)
source_dict['children'].append(users_dict)
data['children'].append(source_dict)
# Users
if start_type == "user":
data['name'] = "Users"
users = CRITsUser.objects()
for user in users:
user_dict = {'name': user.username,
'children': []}
if user.username == start_node:
user_dict['expand'] = True
else:
user_dict['expand'] = True
sources_dict = {'name': 'Sources',
'children': []}
if expansion_node and expansion_node.lower() == 'sources':
sources_dict['expand'] = True
else:
sources_dict['expand'] = False
roles_dict = {'name': 'Roles',
'children': []}
if expansion_node and expansion_node.lower() == 'roles':
roles_dict['expand'] = True
else:
roles_dict['expand'] = False
roles = Role.objects(name__in=user.roles)
for role in roles:
for source in role.sources:
d = {'name': source.name,
'url': "%s?start_type=source&start_node=%s" % (url,
source.name),
'size': 3000}
sources_dict['children'].append(d)
d = {'name': role.name,
'url': "%s?start_type=role&start_node=%s" % (url,
role.name),
'size': 3000}
roles_dict['children'].append(d)
user_dict['children'].append(sources_dict)
user_dict['children'].append(roles_dict)
data['children'].append(user_dict)
return data
def modify_tlp(itype, oid, tlp, analyst):
"""
Modify the TLP for a top-level object.
:param itype: The CRITs type of the top-level object to modify.
:type itype: str
:param oid: The ObjectId to search for.
:type oid: str
:param tlp: The TLP to set.
:type sectors: str
:param analyst: The user making the modifications.
"""
obj = class_from_id(itype, oid)
if not obj:
return {'success': False,
'message': "Cannot find object to set this TLP level for."}
tlp_dict = {'#ffffff': 'white',
'#00ff00': 'green',
'#ffcc22': 'amber',
'#ff0000': 'red'}
tlp = tlp_dict.get(tlp, None) or tlp
obj.set_tlp(tlp)
try:
obj.save(username=analyst)
if obj.tlp == tlp:
return {'success': True}
else:
return {'success': False,
'message': "Cannot set this TLP level."}
except ValidationError:
return {'success': False,
'message': "Invalid TLP level."}
def add_new_action(action, object_types, preferred, analyst):
"""
Add a new action to CRITs.
:param action: The action to add to CRITs.
:type action: str
:param object_types: The TLOs this is for.
:type object_types: list
:param preferred: The TLOs this is preferred for.
:type preferred: list
:param analyst: The user adding this action.
:returns: True, False
"""
action = action.strip()
idb_action = Action.objects(name=action).first()
if not idb_action:
idb_action = Action()
idb_action.name = action
idb_action.object_types = object_types
idb_action.preferred = []
prefs = preferred.split('\n')
for pref in prefs:
cols = pref.split(',')
if len(cols) != 3:
continue
epa = EmbeddedPreferredAction()
epa.object_type = cols[0].strip()
epa.object_field = cols[1].strip()
epa.object_value = cols[2].strip()
idb_action.preferred.append(epa)
try:
idb_action.save(username=analyst)
except ValidationError:
return False
return True
|
Magicked/crits
|
crits/core/handlers.py
|
Python
|
mit
| 180,063
|
[
"Amber"
] |
0a656c4f5dbce58e8e170a1467fa94868a6236bde7093329f39daa0b64b2becb
|
import io
import os
import re
from distutils.core import setup
def read(path, encoding='utf-8'):
path = os.path.join(os.path.dirname(__file__), path)
with io.open(path, encoding=encoding) as fp:
return fp.read()
def version(path):
"""Obtain the packge version from a python file e.g. pkg/__init__.py
See <https://packaging.python.org/en/latest/single_source_version.html>.
"""
version_file = read(path)
version_match = re.search(r"""^__version__ = ['"]([^'"]*)['"]""",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
DESCRIPTION = "Weighted Principal Component Analysis"
LONG_DESCRIPTION = """
wpca: Weighted Principal Component Analysis
===========================================
For more information, visit http://github.com/jakevdp/wpca/
"""
NAME = "wpca"
AUTHOR = "Jake VanderPlas"
AUTHOR_EMAIL = "jakevdp@uw.edu"
MAINTAINER = "Jake VanderPlas"
MAINTAINER_EMAIL = "jakevdp@uw.edu"
URL = 'http://github.com/jakevdp/wpca/'
DOWNLOAD_URL = 'http://github.com/jakevdp/wpca/'
LICENSE = 'BSD'
VERSION = version('wpca/__init__.py')
setup(name=NAME,
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
url=URL,
download_url=DOWNLOAD_URL,
license=LICENSE,
packages=['wpca',
'wpca.tests',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5'],
)
|
jakevdp/wpca
|
setup.py
|
Python
|
bsd-3-clause
| 1,960
|
[
"VisIt"
] |
bc0a1368027bde535bbc9507d17f8971e66f31f4ad50111b35de1c8a76ac5f3f
|
#!/usr/bin/python
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
""" Module: itim
============
"""
from __future__ import print_function
from multiprocessing import Process, Queue
import numpy as np
try:
from __builtin__ import zip as builtin_zip
except:
from builtins import zip as builtin_zip
from scipy.spatial import cKDTree
from . import messages
from . import utilities
from .surface import SurfaceFlatInterface as Surface
from .sanity_check import SanityCheck
from .interface import Interface
from .patches import patchTrajectory, patchOpenMM, patchMDTRAJ
class ITIM(Interface):
""" Identifies interfacial molecules at macroscopically flat interfaces.
*(Pártay, L. B.; Hantal, Gy.; Jedlovszky, P.; Vincze, Á.; Horvai, G., \
J. Comp. Chem. 29, 945, 2008)*
:param Object universe: The MDAnalysis_ Universe, MDTraj_ trajectory
or OpenMM_ Simulation objects.
:param Object group: An AtomGroup, or an array-like object with
the indices of the atoms in the group. Will
identify the interfacial molecules from this
group
:param float alpha: The probe sphere radius
:param str normal: The macroscopic interface normal direction
'x','y', 'z' or 'guess' (default)
:param bool molecular: Switches between search of interfacial
molecules / atoms (default: True)
:param int max_layers: The number of layers to be identified
:param dict radii_dict: Dictionary with the atomic radii of the
elements in the group. If None is supplied,
the default one (from GROMOS 43a1) will be
used.
:param float cluster_cut: Cutoff used for neighbors or density-based
cluster search (default: None disables the
cluster analysis)
:param float cluster_threshold_density: Number density threshold for
the density-based cluster search. 'auto'
determines the threshold automatically.
Default: None uses simple neighbors cluster
search, if cluster_cut is not None
:param Object extra_cluster_groups: Additional groups, to allow for
mixed interfaces
:param bool info: Print additional info
:param bool centered: Center the :py:obj:`group`
:param bool warnings: Print warnings
:param float mesh: The grid spacing used for the testlines
(default 0.4 Angstrom)
:param bool autoassign: If true (default) detect the interface
every time a new frame is selected.
Example:
>>> import MDAnalysis as mda
>>> import numpy as np
>>> import pytim
>>> from pytim.datafiles import *
>>>
>>> u = mda.Universe(WATER_GRO)
>>> oxygens = u.select_atoms("name OW")
>>>
>>> interface = pytim.ITIM(u, alpha=1.5, max_layers=4,molecular=True)
>>> # atoms in the layers can be accesses either through
>>> # the layers array:
>>> print (interface.layers)
[[<AtomGroup with 786 atoms> <AtomGroup with 681 atoms>
<AtomGroup with 663 atoms> <AtomGroup with 651 atoms>]
[<AtomGroup with 786 atoms> <AtomGroup with 702 atoms>
<AtomGroup with 666 atoms> <AtomGroup with 636 atoms>]]
>>> interface.layers[0,0] # upper side, first layer
<AtomGroup with 786 atoms>
>>> interface.layers[1,2] # lower side, third layer
<AtomGroup with 666 atoms>
>>> # or as a whole AtomGroup. This can include all atoms in all layers
>>> interface.atoms
<AtomGroup with 5571 atoms>
>>> selection = interface.atoms.sides == 0
>>> interface.atoms[ selection ] # all atoms in the upper side layer
<AtomGroup with 2781 atoms>
>>> selection = np.logical_and(interface.atoms.layers == 2 , selection)
>>> interface.atoms[ selection ] # upper side, second layer
<AtomGroup with 681 atoms>
>>> # the whole system can be quickly saved to a pdb file
>>> # including the layer information, written in the beta field
>>> # using:
>>> interface.writepdb('system.pdb',centered=True)
>>> # of course, the native interface of MDAnalysis can be used to
>>> # write pdb files, but the centering options are not available.
>>> # Writing to other formats that do not support the beta factor
>>> # will loose the information on the layers.
>>> interface.atoms.write('only_layers.pdb')
>>> # In some cases it might be necessary to compute two interfaces.
>>> # This could be done in the following way:
>>> import MDAnalysis as mda
>>> import pytim
>>> from pytim.datafiles import WATER_GRO, WATER_XTC
>>> u = mda.Universe(WATER_GRO,WATER_XTC)
>>> u2 = mda.Universe(WATER_GRO,WATER_XTC)
>>> inter = pytim.ITIM(u,group=u.select_atoms('resname SOL'))
>>> inter2 = pytim.ITIM(u2,group=u2.select_atoms('resname SOL'))
>>> for ts in u.trajectory[::50]:
... ts2 = u2.trajectory[ts.frame]
>>> # pytim can be used also on top of mdtraj (MDAnalysis must be present,though)
>>> import mdtraj
>>> import pytim
>>> from pytim.datafiles import WATER_GRO, WATER_XTC
>>> t = mdtraj.load_xtc(WATER_XTC,top=WATER_GRO)
>>> inter = pytim.ITIM(t)
.. _MDAnalysis: http://www.mdanalysis.org/
.. _MDTraj: http://www.mdtraj.org/
.. _OpenMM: http://www.openmm.org/
"""
@property
def layers(self):
"""Access the layers as numpy arrays of AtomGroups.
The object can be sliced as usual with numpy arrays, so, for example:
>>> import MDAnalysis as mda
>>> import pytim
>>> from pytim.datafiles import *
>>>
>>> u = mda.Universe(WATER_GRO)
>>> oxygens = u.select_atoms("name OW")
>>>
>>> interface = pytim.ITIM(u, alpha=1.5, max_layers=4,molecular=True)
>>> print(interface.layers[0,:]) # upper side (0), all layers
[<AtomGroup with 786 atoms> <AtomGroup with 681 atoms>
<AtomGroup with 663 atoms> <AtomGroup with 651 atoms>]
>>> repr(interface.layers[1,0]) # lower side (1), first layer (0)
'<AtomGroup with 786 atoms>'
>>> print(interface.layers[:,0:3]) # 1st - 3rd layer (0:3), on both sides
[[<AtomGroup with 786 atoms> <AtomGroup with 681 atoms>
<AtomGroup with 663 atoms>]
[<AtomGroup with 786 atoms> <AtomGroup with 702 atoms>
<AtomGroup with 666 atoms>]]
>>> print(interface.layers[1,0:4:2]) # side 1, layers 1-4 & stride 2 (0:4:2)
[<AtomGroup with 786 atoms> <AtomGroup with 666 atoms>]
"""
return self._layers
def __init__(self,
universe,
group=None,
alpha=1.5,
normal='guess',
molecular=True,
max_layers=1,
radii_dict=None,
cluster_cut=None,
cluster_threshold_density=None,
extra_cluster_groups=None,
info=False,
centered=False,
warnings=False,
mesh=0.4,
autoassign=True,
**kargs):
self.autoassign = autoassign
self.symmetry = 'planar'
self.do_center = centered
sanity = SanityCheck(self, warnings=warnings)
sanity.assign_universe(universe, group)
sanity.assign_alpha(alpha)
sanity.assign_mesh(mesh)
self.max_layers = max_layers
self._layers = np.empty(
[2, max_layers], dtype=self.universe.atoms[0].__class__)
self._surfaces = np.empty(max_layers, dtype=type(Surface))
self.info = info
self.normal = None
self.PDB = {}
self.molecular = molecular
sanity.assign_cluster_params(cluster_cut,
cluster_threshold_density, extra_cluster_groups)
sanity.assign_normal(normal)
sanity.assign_radii(radii_dict=radii_dict)
self.grid = None
self.use_threads = False
patchTrajectory(self.universe.trajectory, self)
self._assign_layers()
def _create_mesh(self):
""" Mesh assignment method
Based on a target value, determine a mesh size for the testlines
that is compatible with the simulation box.
Create the grid and initialize a cKDTree object with it to
facilitate fast searching of the gridpoints touched by molecules.
"""
box = utilities.get_box(self.universe, self.normal)
n, d = utilities.compute_compatible_mesh_params(self.target_mesh, box)
self.mesh_nx = n[0]
self.mesh_ny = n[1]
self.mesh_dx = d[0]
self.mesh_dy = d[1]
_x = np.linspace(0, box[0], num=int(self.mesh_nx), endpoint=False)
_y = np.linspace(0, box[1], num=int(self.mesh_ny), endpoint=False)
_X, _Y = np.meshgrid(_x, _y)
self.meshpoints = np.array([_X.ravel(), _Y.ravel()]).T
self.meshtree = cKDTree(self.meshpoints, boxsize=box[:2])
def _touched_lines(self, atom, _x, _y, _z, _radius):
return self.meshtree.query_ball_point([_x[atom], _y[atom]],
_radius[atom] + self.alpha)
def _append_layers(self, uplow, layer, layers):
inlayer_indices = np.flatnonzero(self._seen[uplow] == layer + 1)
inlayer_group = self.cluster_group[inlayer_indices]
if self.molecular is True:
# we first select the (unique) residues corresponding
# to inlayer_group, and then we create group of the
# atoms belonging to them, with
# inlayer_group.residues.atoms
inlayer_group = inlayer_group.residues.atoms
# now we need the indices within the cluster_group,
# of the atoms in the molecular layer group;
# NOTE that from MDAnalysis 0.16, .ids runs from 1->N
# (was 0->N-1 in 0.15), we use now .indices
indices = np.flatnonzero(
np.in1d(self.cluster_group.atoms.indices,
inlayer_group.atoms.indices))
# and update the tagged, sorted atoms
self._seen[uplow][indices] = layer + 1
# one of the two layers (upper,lower) or both are empty
if not inlayer_group:
raise Exception(messages.EMPTY_LAYER)
layers.append(inlayer_group)
def _assign_one_side(self,
uplow,
sorted_atoms,
_x,
_y,
_z,
_radius,
queue=None):
layers = []
for layer in range(0, self.max_layers):
# this mask tells which lines have been touched.
mask = self.mask[uplow][layer]
# atom here goes to 0 to #sorted_atoms, it is not a MDAnalysis
# index/atom
for atom in sorted_atoms:
if self._seen[uplow][atom] != 0:
continue
touched_lines = self._touched_lines(atom, _x, _y, _z, _radius)
_submask = mask[touched_lines]
if (len(_submask[_submask == 0]) == 0):
# no new contact, let's move to the next atom
continue
# let's mark now: 1) the touched lines
mask[touched_lines] = 1
# 2) the sorted atoms.
self._seen[uplow][atom] = layer + 1
# 3) if all lines have been touched, create a group that
# includes all atoms in this layer
if np.sum(mask) == len(mask):
self._append_layers(uplow, layer, layers)
break
if (queue is None):
return layers
else:
queue.put(layers)
def _prepare_layers_assignment(self):
self._create_mesh()
size = (2, int(self.max_layers), int(self.mesh_nx) * int(self.mesh_ny))
self.mask = np.zeros(size, dtype=int)
self.prepare_box()
def _prelabel_groups(self):
# first we label all atoms in group to be in the gas phase
self.label_group(self.analysis_group.atoms, beta=0.5)
# then all atoms in the largest group are labelled as liquid-like
self.label_group(self.cluster_group.atoms, beta=0.0)
def _assign_layers(self):
""" Determine the ITIM layers.
Note that the multiproc option is mainly for debugging purposes:
>>> import MDAnalysis as mda
>>> import pytim
>>> u = mda.Universe(pytim.datafiles.WATER_GRO)
>>> inter = pytim.ITIM(u,multiproc=True)
>>> test1 = len(inter.layers[0,0])
>>> inter = pytim.ITIM(u,multiproc=False)
>>> test2 = len(inter.layers[0,0])
>>> test1==test2
True
"""
up, low = 0, 1
self.reset_labels()
self._prepare_layers_assignment()
# groups have been checked already in _sanity_checks()
self._define_cluster_group()
# we always (internally) center in ITIM
self.center(planar_to_origin=True)
self._prelabel_groups()
_radius = self.cluster_group.radii
size = len(self.cluster_group.positions)
self._seen = [
np.zeros(size, dtype=np.int8),
np.zeros(size, dtype=np.int8)
]
_x = utilities.get_x(self.cluster_group, self.normal)
_y = utilities.get_y(self.cluster_group, self.normal)
_z = utilities.get_z(self.cluster_group, self.normal)
sort = np.argsort(_z + _radius * np.sign(_z))
# NOTE: np.argsort returns the sorted *indices*
# so far, it justs exploit a simple scheme splitting
# the calculation between the two sides. Would it be
# possible to implement easily 2d domain decomposition?
proc, queue = [None, None], [Queue(), Queue()]
proc[up] = Process(
target=self._assign_one_side,
args=(up, sort[::-1], _x, _y, _z, _radius, queue[up]))
proc[low] = Process(
target=self._assign_one_side,
args=(low, sort[::], _x, _y, _z, _radius, queue[low]))
for p in proc:
p.start()
for uplow in [up, low]:
for index, group in enumerate(queue[uplow].get()):
# cannot use self._layers[uplow][index] = group, otherwise
# info about universe is lost (do not know why yet)
# must use self._layers[uplow][index] =
# self.universe.atoms[group.indices]
self._layers[uplow][index] = self.universe.atoms[group.indices]
for p in proc:
p.join()
for q in queue:
q.close()
self.label_planar_sides()
for nlayer, layer in enumerate(self._layers[
0]): # TODO should this be moved out of assign_layers?
self._surfaces[nlayer] = Surface(self, options={'layer': nlayer})
if self.do_center is False: # NOTE: do_center requires centering in
# the middle of the box.
# ITIM always centers internally in the
# origin along the normal.
self.universe.atoms.positions = self.original_positions
else:
self._shift_positions_to_middle()
#
|
balazsfabian/pytim
|
pytim/itim.py
|
Python
|
gpl-3.0
| 16,238
|
[
"GROMOS",
"MDAnalysis",
"MDTraj",
"OpenMM"
] |
87808a733c8a08c7308de714f8a5d6f6c4fd97e6b56766f98b507bf95f1f6b6d
|
from __future__ import absolute_import, division, print_function
import numpy as np
from six.moves import xrange
from .common import Benchmark
class LaplaceInplace(Benchmark):
params = ['inplace', 'normal']
param_names = ['update']
def setup(self, update):
N = 150
Niter = 1000
dx = 0.1
dy = 0.1
dx2 = (dx * dx)
dy2 = (dy * dy)
def num_update(u, dx2, dy2):
u[1:(-1), 1:(-1)] = ((((u[2:, 1:(-1)] + u[:(-2), 1:(-1)]) * dy2) +
((u[1:(-1), 2:] + u[1:(-1), :(-2)]) * dx2))
/ (2 * (dx2 + dy2)))
def num_inplace(u, dx2, dy2):
tmp = u[:(-2), 1:(-1)].copy()
np.add(tmp, u[2:, 1:(-1)], out=tmp)
np.multiply(tmp, dy2, out=tmp)
tmp2 = u[1:(-1), 2:].copy()
np.add(tmp2, u[1:(-1), :(-2)], out=tmp2)
np.multiply(tmp2, dx2, out=tmp2)
np.add(tmp, tmp2, out=tmp)
np.multiply(tmp, (1.0 / (2.0 * (dx2 + dy2))),
out=u[1:(-1), 1:(-1)])
def laplace(N, Niter=100, func=num_update, args=()):
u = np.zeros([N, N], order='C')
u[0] = 1
for i in range(Niter):
func(u, *args)
return u
func = {'inplace': num_inplace, 'normal': num_update}[update]
def run():
laplace(N, Niter, func, args=(dx2, dy2))
self.run = run
def time_it(self, update):
self.run()
class MaxesOfDots(Benchmark):
def setup(self):
np.random.seed(1)
nsubj = 5
nfeat = 100
ntime = 200
self.arrays = [np.random.normal(size=(ntime, nfeat))
for i in xrange(nsubj)]
def maxes_of_dots(self, arrays):
"""
A magical feature score for each feature in each dataset
:ref:`Haxby et al., Neuron (2011) <HGC+11>`.
If arrays are column-wise zscore-d before computation it
results in characterizing each column in each array with
sum of maximal correlations of that column with columns
in other arrays.
Arrays must agree only on the first dimension.
For numpy it a join benchmark of dot products and max()
on a set of arrays.
"""
feature_scores = ([0] * len(arrays))
for (i, sd) in enumerate(arrays):
for (j, sd2) in enumerate(arrays[(i + 1):]):
corr_temp = np.dot(sd.T, sd2)
feature_scores[i] += np.max(corr_temp, axis=1)
feature_scores[((j + i) + 1)] += np.max(corr_temp, axis=0)
return feature_scores
def time_it(self):
self.maxes_of_dots(self.arrays)
|
DailyActie/Surrogate-Model
|
01-codes/numpy-master/benchmarks/benchmarks/bench_app.py
|
Python
|
mit
| 2,745
|
[
"NEURON"
] |
864ab91367f191f407f94e64ed14f3f3667ba10e0ea391696260a61514faa49d
|
# ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the License.
# You may obtain a copy of the License in the LICENSE file, or 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
__author__ = 'Brian Wickman'
import sys
import types
try:
from twitter.common import log
_log_function = log.warning
except ImportError:
def _log_function(msg):
print(msg, file=sys.stderr)
from .lru_cache import lru_cache
__all__ = (
'deprecated',
'deprecated_with_warning',
'lru_cache'
)
def _deprecated_wrap_fn(fn, message=None):
if not isinstance(fn, types.FunctionType):
raise ValueError("@deprecated annotation requires a function!")
def _function(*args, **kwargs):
_log_function("DEPRECATION WARNING: %s:%s is deprecated! %s" % (
_function.__module__,
_function.__name__,
message if message is not None else ""))
return fn(*args, **kwargs)
_function.__doc__ = fn.__doc__
_function.__name__ = fn.__name__
return _function
def deprecated(function):
"""@deprecated annotation. logs a warning to the twitter common logging framework
should calls be made to the decorated function.
e.g.
@deprecated
def qsort(lst):
...
"""
return _deprecated_wrap_fn(function)
class deprecated_with_warning(object):
"""@deprecated_with_warning annotation. logs a warning to the twitter
common logging framework should calls be made to the decorated
function, along with an additional supplied message.
e.g.
@deprecated_with_warning("Use sort() call instead!")
def qsort(lst):
...
"""
def __init__(self, message):
self._msg = message
def __call__(self, function):
return _deprecated_wrap_fn(function, self._msg)
|
foursquare/commons-old
|
src/python/twitter/common/decorators/__init__.py
|
Python
|
apache-2.0
| 2,486
|
[
"Brian"
] |
971a4f966aabb1b004d4b1c3dad3890d2b756bcf91e5c72e3e63858f87443aaa
|
import functools
from typing import List, Any
import numpy as np
import scipy.sparse as sp
import pytest
from sklearn.metrics import euclidean_distances
from sklearn.random_projection import johnson_lindenstrauss_min_dim
from sklearn.random_projection import _gaussian_random_matrix
from sklearn.random_projection import _sparse_random_matrix
from sklearn.random_projection import SparseRandomProjection
from sklearn.random_projection import GaussianRandomProjection
from sklearn.utils._testing import assert_raises
from sklearn.utils._testing import assert_raise_message
from sklearn.utils._testing import assert_array_equal
from sklearn.utils._testing import assert_almost_equal
from sklearn.utils._testing import assert_array_almost_equal
from sklearn.utils._testing import assert_warns
from sklearn.exceptions import DataDimensionalityWarning
all_sparse_random_matrix: List[Any] = [_sparse_random_matrix]
all_dense_random_matrix: List[Any] = [_gaussian_random_matrix]
all_random_matrix = all_sparse_random_matrix + all_dense_random_matrix
all_SparseRandomProjection: List[Any] = [SparseRandomProjection]
all_DenseRandomProjection: List[Any] = [GaussianRandomProjection]
all_RandomProjection = set(all_SparseRandomProjection +
all_DenseRandomProjection)
# Make some random data with uniformly located non zero entries with
# Gaussian distributed values
def make_sparse_random_data(n_samples, n_features, n_nonzeros):
rng = np.random.RandomState(0)
data_coo = sp.coo_matrix(
(rng.randn(n_nonzeros),
(rng.randint(n_samples, size=n_nonzeros),
rng.randint(n_features, size=n_nonzeros))),
shape=(n_samples, n_features))
return data_coo.toarray(), data_coo.tocsr()
def densify(matrix):
if not sp.issparse(matrix):
return matrix
else:
return matrix.toarray()
n_samples, n_features = (10, 1000)
n_nonzeros = int(n_samples * n_features / 100.)
data, data_csr = make_sparse_random_data(n_samples, n_features, n_nonzeros)
###############################################################################
# test on JL lemma
###############################################################################
def test_invalid_jl_domain():
assert_raises(ValueError, johnson_lindenstrauss_min_dim, 100, eps=1.1)
assert_raises(ValueError, johnson_lindenstrauss_min_dim, 100, eps=0.0)
assert_raises(ValueError, johnson_lindenstrauss_min_dim, 100, eps=-0.1)
assert_raises(ValueError, johnson_lindenstrauss_min_dim, 0, eps=0.5)
def test_input_size_jl_min_dim():
assert_raises(ValueError, johnson_lindenstrauss_min_dim,
3 * [100], eps=2 * [0.9])
assert_raises(ValueError, johnson_lindenstrauss_min_dim, 3 * [100],
eps=2 * [0.9])
johnson_lindenstrauss_min_dim(np.random.randint(1, 10, size=(10, 10)),
eps=np.full((10, 10), 0.5))
###############################################################################
# tests random matrix generation
###############################################################################
def check_input_size_random_matrix(random_matrix):
assert_raises(ValueError, random_matrix, 0, 0)
assert_raises(ValueError, random_matrix, -1, 1)
assert_raises(ValueError, random_matrix, 1, -1)
assert_raises(ValueError, random_matrix, 1, 0)
assert_raises(ValueError, random_matrix, -1, 0)
def check_size_generated(random_matrix):
assert random_matrix(1, 5).shape == (1, 5)
assert random_matrix(5, 1).shape == (5, 1)
assert random_matrix(5, 5).shape == (5, 5)
assert random_matrix(1, 1).shape == (1, 1)
def check_zero_mean_and_unit_norm(random_matrix):
# All random matrix should produce a transformation matrix
# with zero mean and unit norm for each columns
A = densify(random_matrix(10000, 1, random_state=0))
assert_array_almost_equal(0, np.mean(A), 3)
assert_array_almost_equal(1.0, np.linalg.norm(A), 1)
def check_input_with_sparse_random_matrix(random_matrix):
n_components, n_features = 5, 10
for density in [-1., 0.0, 1.1]:
assert_raises(ValueError,
random_matrix, n_components, n_features, density=density)
@pytest.mark.parametrize("random_matrix", all_random_matrix)
def test_basic_property_of_random_matrix(random_matrix):
# Check basic properties of random matrix generation
check_input_size_random_matrix(random_matrix)
check_size_generated(random_matrix)
check_zero_mean_and_unit_norm(random_matrix)
@pytest.mark.parametrize("random_matrix", all_sparse_random_matrix)
def test_basic_property_of_sparse_random_matrix(random_matrix):
check_input_with_sparse_random_matrix(random_matrix)
random_matrix_dense = functools.partial(random_matrix, density=1.0)
check_zero_mean_and_unit_norm(random_matrix_dense)
def test_gaussian_random_matrix():
# Check some statical properties of Gaussian random matrix
# Check that the random matrix follow the proper distribution.
# Let's say that each element of a_{ij} of A is taken from
# a_ij ~ N(0.0, 1 / n_components).
#
n_components = 100
n_features = 1000
A = _gaussian_random_matrix(n_components, n_features, random_state=0)
assert_array_almost_equal(0.0, np.mean(A), 2)
assert_array_almost_equal(np.var(A, ddof=1), 1 / n_components, 1)
def test_sparse_random_matrix():
# Check some statical properties of sparse random matrix
n_components = 100
n_features = 500
for density in [0.3, 1.]:
s = 1 / density
A = _sparse_random_matrix(n_components,
n_features,
density=density,
random_state=0)
A = densify(A)
# Check possible values
values = np.unique(A)
assert np.sqrt(s) / np.sqrt(n_components) in values
assert - np.sqrt(s) / np.sqrt(n_components) in values
if density == 1.0:
assert np.size(values) == 2
else:
assert 0. in values
assert np.size(values) == 3
# Check that the random matrix follow the proper distribution.
# Let's say that each element of a_{ij} of A is taken from
#
# - -sqrt(s) / sqrt(n_components) with probability 1 / 2s
# - 0 with probability 1 - 1 / s
# - +sqrt(s) / sqrt(n_components) with probability 1 / 2s
#
assert_almost_equal(np.mean(A == 0.0),
1 - 1 / s, decimal=2)
assert_almost_equal(np.mean(A == np.sqrt(s) / np.sqrt(n_components)),
1 / (2 * s), decimal=2)
assert_almost_equal(np.mean(A == - np.sqrt(s) / np.sqrt(n_components)),
1 / (2 * s), decimal=2)
assert_almost_equal(np.var(A == 0.0, ddof=1),
(1 - 1 / s) * 1 / s, decimal=2)
assert_almost_equal(np.var(A == np.sqrt(s) / np.sqrt(n_components),
ddof=1),
(1 - 1 / (2 * s)) * 1 / (2 * s), decimal=2)
assert_almost_equal(np.var(A == - np.sqrt(s) / np.sqrt(n_components),
ddof=1),
(1 - 1 / (2 * s)) * 1 / (2 * s), decimal=2)
###############################################################################
# tests on random projection transformer
###############################################################################
def test_sparse_random_projection_transformer_invalid_density():
for RandomProjection in all_SparseRandomProjection:
assert_raises(ValueError,
RandomProjection(density=1.1).fit, data)
assert_raises(ValueError,
RandomProjection(density=0).fit, data)
assert_raises(ValueError,
RandomProjection(density=-0.1).fit, data)
def test_random_projection_transformer_invalid_input():
for RandomProjection in all_RandomProjection:
assert_raises(ValueError,
RandomProjection(n_components='auto').fit, [[0, 1, 2]])
assert_raises(ValueError,
RandomProjection(n_components=-10).fit, data)
def test_try_to_transform_before_fit():
for RandomProjection in all_RandomProjection:
assert_raises(ValueError,
RandomProjection(n_components='auto').transform, data)
def test_too_many_samples_to_find_a_safe_embedding():
data, _ = make_sparse_random_data(1000, 100, 1000)
for RandomProjection in all_RandomProjection:
rp = RandomProjection(n_components='auto', eps=0.1)
expected_msg = (
'eps=0.100000 and n_samples=1000 lead to a target dimension'
' of 5920 which is larger than the original space with'
' n_features=100')
assert_raise_message(ValueError, expected_msg, rp.fit, data)
def test_random_projection_embedding_quality():
data, _ = make_sparse_random_data(8, 5000, 15000)
eps = 0.2
original_distances = euclidean_distances(data, squared=True)
original_distances = original_distances.ravel()
non_identical = original_distances != 0.0
# remove 0 distances to avoid division by 0
original_distances = original_distances[non_identical]
for RandomProjection in all_RandomProjection:
rp = RandomProjection(n_components='auto', eps=eps, random_state=0)
projected = rp.fit_transform(data)
projected_distances = euclidean_distances(projected, squared=True)
projected_distances = projected_distances.ravel()
# remove 0 distances to avoid division by 0
projected_distances = projected_distances[non_identical]
distances_ratio = projected_distances / original_distances
# check that the automatically tuned values for the density respect the
# contract for eps: pairwise distances are preserved according to the
# Johnson-Lindenstrauss lemma
assert distances_ratio.max() < 1 + eps
assert 1 - eps < distances_ratio.min()
def test_SparseRandomProjection_output_representation():
for SparseRandomProjection in all_SparseRandomProjection:
# when using sparse input, the projected data can be forced to be a
# dense numpy array
rp = SparseRandomProjection(n_components=10, dense_output=True,
random_state=0)
rp.fit(data)
assert isinstance(rp.transform(data), np.ndarray)
sparse_data = sp.csr_matrix(data)
assert isinstance(rp.transform(sparse_data), np.ndarray)
# the output can be left to a sparse matrix instead
rp = SparseRandomProjection(n_components=10, dense_output=False,
random_state=0)
rp = rp.fit(data)
# output for dense input will stay dense:
assert isinstance(rp.transform(data), np.ndarray)
# output for sparse output will be sparse:
assert sp.issparse(rp.transform(sparse_data))
def test_correct_RandomProjection_dimensions_embedding():
for RandomProjection in all_RandomProjection:
rp = RandomProjection(n_components='auto',
random_state=0,
eps=0.5).fit(data)
# the number of components is adjusted from the shape of the training
# set
assert rp.n_components == 'auto'
assert rp.n_components_ == 110
if RandomProjection in all_SparseRandomProjection:
assert rp.density == 'auto'
assert_almost_equal(rp.density_, 0.03, 2)
assert rp.components_.shape == (110, n_features)
projected_1 = rp.transform(data)
assert projected_1.shape == (n_samples, 110)
# once the RP is 'fitted' the projection is always the same
projected_2 = rp.transform(data)
assert_array_equal(projected_1, projected_2)
# fit transform with same random seed will lead to the same results
rp2 = RandomProjection(random_state=0, eps=0.5)
projected_3 = rp2.fit_transform(data)
assert_array_equal(projected_1, projected_3)
# Try to transform with an input X of size different from fitted.
assert_raises(ValueError, rp.transform, data[:, 1:5])
# it is also possible to fix the number of components and the density
# level
if RandomProjection in all_SparseRandomProjection:
rp = RandomProjection(n_components=100, density=0.001,
random_state=0)
projected = rp.fit_transform(data)
assert projected.shape == (n_samples, 100)
assert rp.components_.shape == (100, n_features)
assert rp.components_.nnz < 115 # close to 1% density
assert 85 < rp.components_.nnz # close to 1% density
def test_warning_n_components_greater_than_n_features():
n_features = 20
data, _ = make_sparse_random_data(5, n_features, int(n_features / 4))
for RandomProjection in all_RandomProjection:
assert_warns(DataDimensionalityWarning,
RandomProjection(n_components=n_features + 1).fit, data)
def test_works_with_sparse_data():
n_features = 20
data, _ = make_sparse_random_data(5, n_features, int(n_features / 4))
for RandomProjection in all_RandomProjection:
rp_dense = RandomProjection(n_components=3,
random_state=1).fit(data)
rp_sparse = RandomProjection(n_components=3,
random_state=1).fit(sp.csr_matrix(data))
assert_array_almost_equal(densify(rp_dense.components_),
densify(rp_sparse.components_))
|
lesteve/scikit-learn
|
sklearn/tests/test_random_projection.py
|
Python
|
bsd-3-clause
| 13,850
|
[
"Gaussian"
] |
595c590633a33e5df64e4723be27494f44c8183afc22a0e9b92012e02972ca60
|
import distutils
import os
from distutils.core import setup
import _version
import pip
pip.main(['install', 'appdirs'])
# from setuptools.command import build_py
__basedir__ = _version.__basedir__
__version__ = _version.__version__
appname = 'pracmln'
appauthor = 'danielnyga'
def iamroot():
'''Checks if this process has admin permissions.'''
try:
return os.getuid() == 0
except AttributeError:
import ctypes
return ctypes.windll.shell32.IsUserAnAdmin() != 0
def basedir(name):
return os.path.join(__basedir__, name)
with open(os.path.join(os.path.dirname(__file__), __basedir__, 'requirements.txt'), 'r') as f:
requirements = [l.strip() for l in f.readlines() if l.strip()]
def datafiles(d):
data_files = []
for root, dirs, files in os.walk(os.path.join(os.path.dirname(__file__), d)):
if not files: continue
root_ = root.replace(os.getcwd() + os.path.sep, '')
data_files.append((root_, [os.path.join(root_, f) for f in files]))
return data_files
def datapath():
'''Returns the path where app data is to be installed.'''
import appdirs
if iamroot():
return appdirs.site_data_dir(appname, appauthor)
else:
return appdirs.user_data_dir(appname, appauthor)
def description():
try:
with open('README.md') as f:
return f.read()
except:
return 'Markov logic networks in Python. Please visit http://www.pracmln.org'
class myinstall(distutils.command.install.install):
def __init__(self, *args, **kwargs):
distutils.command.install.install.__init__(self, *args, **kwargs)
self.distribution.get_command_obj('install_data').install_dir = datapath()
setup(
name='pracmln',
packages=['pracmln', 'pracmln._version', 'pracmln.logic', 'pracmln.mln',
'pracmln.utils', 'pracmln.wcsp', 'pracmln.mln.grounding',
'pracmln.mln.inference', 'pracmln.mln.learning'],
package_dir={
'pracmln': basedir('pracmln'),
'pracmln._version': '_version',
},
data_files=datafiles('examples') + datafiles('3rdparty') + datafiles('libpracmln') + datafiles('etc'),
version=__version__,
description='Markov logic networks in Python',
long_description=description(),
author='Daniel Nyga',
author_email='nyga@cs.uni-bremen.de',
url='http://www.pracmln.org',
download_url='https://github.com/danielnyga/pracmln/archive/%s.tar.gz' % __version__,
keywords=['statistical relational learning', 'mln', 'Markov logic networks', 'reasoning', 'probcog'],
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Scientific/Engineering :: Artificial Intelligence ',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
],
install_requires=requirements,
entry_points={
'console_scripts': [
'mlnlearn=pracmln.mlnlearn:main',
'mlnquery=pracmln.mlnquery:main',
'libpracmln-build=pracmln.libpracmln:createcpplibs',
'pracmlntest=pracmln.test:main',
],
},
cmdclass={'install': myinstall}
)
|
danielnyga/pracmln
|
setup.py
|
Python
|
bsd-2-clause
| 3,823
|
[
"VisIt"
] |
16ee576888ee729a5e29f5d4a9f64f6e6192dfe7a556a38fd7bb39ff2b178819
|
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import sys
if sys.version > '3':
long = int
import numpy as np
import copy
import cPickle
from scipy.stats import chi2
#-----------------------------------------------------------------------
def airtovac(wave_air):
"""
__author__ = 'Kyle B. Westfall'
Wavelengths are corrected for the index of refraction of air under
standard conditions. Wavelength values below 2000 A will not be
altered. Uses formula from Ciddor 1996, Applied Optics 62, 958.
Args:
wave_air (int or float): Wavelength in Angstroms, scalar or
vector. If this is the only parameter supplied, it will be
updated on output to contain double precision vacuum
wavelength(s).
Returns:
numpy.float64 : The wavelength of the line in vacuum.
Example:
If the air wavelength is W = 6056.125 (a Krypton line), then
:func:`airtovac` returns vacuum wavelength of W = 6057.8019.
*Revision history*:
| Written W. Landsman November 1991
| Use Ciddor (1996) formula for better accuracy in the infrared
| Added optional output vector, W Landsman Mar 2011
| Iterate for better precision W.L./D. Schlegel Mar 2011
| Transcribed to python, K.B. Westfall Apr 2015
.. note::
Take care within 1 A of 2000 A. Wavelengths below 2000 A *in
air* are not altered.
"""
# Copy the data
wave_vac = wave_air.astype(np.float64) if hasattr(wave_air, "__len__") else float(wave_air)
g = wave_vac > 2000.0 # Only modify above 2000 A
Ng = np.sum(g)
if Ng > 0:
# Handle both arrays and scalars
if hasattr(wave_air, "__len__"):
_wave_air = wave_air[g].astype(np.float64)
_wave_vac = wave_vac[g]
else:
_wave_air = float(wave_air)
_wave_vac = float(wave_vac)
for i in range(0,2):
sigma2 = np.square(1.0e4/_wave_vac) #Convert to wavenumber squared
fact = 1.0 + 5.792105e-2/(238.0185 - sigma2) + 1.67917e-3/(57.362 - sigma2)
_wave_vac = _wave_air*fact
if hasattr(wave_air, "__len__"): # Save the result
wave_vac[g] = _wave_vac
else:
wave_vac = _wave_vac
return wave_vac
#-----------------------------------------------------------------------
def bisect_array(array):
"""
It takes an array as input and returns the bisected array :
bisected array[i] = (array[i] + array[i+1] )/2. Its lenght is one less than the array.
:param array: input array
"""
bisected_array = np.zeros(len(array) - 1)
for ai in range(len(bisected_array)):
bisected_array[ai] = (array[ai] + array[ai + 1])/2.0
return bisected_array
#-----------------------------------------------------------------------
def max_pdf(probs,property,sampling):
"""
determines the maximum of a pdf of a property for a given sampling
:param probs: probabilities
:param property: property
:param sampling: sampling of the property
"""
lower_limit = np.min(property)
upper_limit = np.max(property)
if upper_limit==lower_limit:
return np.asarray(property),np.ones(len(probs))/np.size(probs)
property_pdf_int= np.arange(lower_limit, upper_limit * 1.001, (upper_limit-lower_limit) /sampling ) + ( upper_limit - lower_limit) * 0.00000001
prob_pdf = np.zeros(len(property_pdf_int))
for p in range(len(property_pdf_int)-1):
match_prop = np.where( (property <= property_pdf_int[p+1]) & (property > property_pdf_int[p]) )
if np.size(match_prop) == 0:
continue
else:
prob_pdf[p] = np.max( probs[match_prop] )
property_pdf = bisect_array(property_pdf_int)
return property_pdf,prob_pdf[:-1]/np.sum(prob_pdf)
#-----------------------------------------------------------------------
def convert_chis_to_probs(chis,dof):
"""
Converts chi squares to probabilities.
:param chis: array containing the chi squares.
:param dof: array of degrees of freedom.
"""
chis = chis / np.min(chis) * dof
prob = 1.0 - chi2.cdf(chis,dof)
prob = prob / np.sum(prob)
return prob
#-----------------------------------------------------------------------
def light_weights_to_mass(light_weights,mass_factors):
"""
Uses the data/model mass-to-light ratio to convert
SSP contribution (weights) by light into
SSP contributions by mass.
:param light_weights: light (luminosity) weights obtained when model fitting
:param mass_factors: mass factors obtained when normalizing the spectrum
"""
mass_weights = np.zeros(np.shape(light_weights))
unnorm_mass = np.zeros(np.shape(light_weights))
for w in range(len(light_weights)):
unnorm_mass[w] = light_weights[w] * mass_factors
mass_weights[w] = unnorm_mass[w] / np.sum(unnorm_mass[w])
return unnorm_mass,mass_weights
#-----------------------------------------------------------------------
def find_closest(A, target):
"""
returns the id of the target in the array A.
:param A: Array, must be sorted
:param target: target value to be located in the array.
"""
idx = A.searchsorted(target)
idx = np.clip(idx, 1, len(A)-1)
left = A[idx-1]
right = A[idx]
idx -= target - left < right - target
return idx
#-----------------------------------------------------------------------
def averages_and_errors(probs,prop,sampling):
"""
determines the average and error of a property for a given sampling
returns : an array with the best fit value, +/- 1, 2, 3 sigma values.
:param probs: probabilities
:param property: property
:param sampling: sampling of the property
"""
xdf,y = max_pdf(probs,prop,sampling)
cdf = np.zeros(np.shape(y))
cdf_probspace = np.zeros(np.shape(y))
for m in range(len(y)):
cdf[m] = np.sum(y[:m])
cdf = cdf / np.max(cdf)
area_probspace = y*(xdf[1]-xdf[0])
area_probspace = area_probspace/np.sum(area_probspace)
indx_probspace = np.argsort(area_probspace)[::-1]
desc_probspace = np.sort(area_probspace)[::-1]
cdf_probspace = np.zeros(np.shape(desc_probspace))
for m in range(len(desc_probspace)):
cdf_probspace[m] = np.sum(desc_probspace[:m])
av_sigs = [0.6827,0.9545,0.9973] # Median, + / - 1 sig, + / - 2 sig, + / - 3 sig
# Sorts results by likelihood and calculates confidence intervals on sorted space
index_close = find_closest(cdf_probspace, av_sigs)
best_fit = xdf[indx_probspace[0]]
upper_onesig,lower_onesig = np.max(xdf[indx_probspace[:index_close[0]]]),np.min(xdf[indx_probspace[:index_close[0]]])
upper_twosig,lower_twosig = np.max(xdf[indx_probspace[:index_close[1]]]),np.min(xdf[indx_probspace[:index_close[1]]])
upper_thrsig,lower_thrsig = np.max(xdf[indx_probspace[:index_close[2]]]),np.min(xdf[indx_probspace[:index_close[2]]])
if np.size(xdf) == 0:
raise Exception('No solutions found??? FIREFLY error (see statistics.py)')
return [best_fit,upper_onesig,lower_onesig,upper_twosig,lower_twosig,upper_thrsig,lower_thrsig]
#-----------------------------------------------------------------------
def calculate_averages_pdf(probs,light_weights,mass_weights,unnorm_mass,age,metal,sampling,dist_lum):
"""
Calculates light- and mass-averaged age and metallicities.
Also outputs stellar mass and mass-to-light ratios.
And errors on all of these properties.
It works by taking the complete set of probs-properties and
maximising over the parameter range (such that solutions with
equivalent values but poorer probabilities are excluded). Then,
we calculate the median and 1/2 sigma confidence intervals from
the derived 'max-pdf'.
NB: Solutions with identical SSP component contributions
are re-scaled such that the sum of probabilities with that
component = the maximum of the probabilities with that component.
i.e. prob_age_ssp1 = max(all prob_age_ssp1) / sum(all prob_age_ssp1)
This is so multiple similar solutions do not count multiple times.
Outputs a dictionary of:
- light_[property], light_[property]_[1/2/3]_sigerror
- mass_[property], mass_[property]_[1/2/3]_sigerror
- stellar_mass, stellar_mass_[1/2/3]_sigerror
- mass_to_light, mass_to_light_[1/2/3]_sigerror
- maxpdf_[property]
- maxpdf_stellar_mass
where [property] = [age] or [metal]
:param probs: probabilities
:param light_weights: light (luminosity) weights obtained when model fitting
:param mass_weights: mass weights obtained when normalizing models to data
:param unnorm_mass: mass weights obtained from the mass to light ratio
:param age: age
:param metal: metallicity
:param sampling: sampling of the property
:param dist_lum: luminosity distance in cm
"""
# Sampling number of max_pdf (100:recommended) from options
log_age = np.log10(age)
log_age[np.isnan(log_age)|np.isinf(log_age)] = 0.0
av = {} # dictionnary where values are stored :
av['light_age'],av['light_age_1_sig_plus'],av['light_age_1_sig_minus'], av['light_age_2_sig_plus'], av['light_age_2_sig_minus'], av['light_age_3_sig_plus'], av['light_age_3_sig_minus'] = averages_and_errors(probs,np.dot(light_weights,log_age),sampling)
av['light_metal'], av['light_metal_1_sig_plus'], av['light_metal_1_sig_minus'], av['light_metal_2_sig_plus'], av['light_metal_2_sig_minus'], av['light_metal_3_sig_plus'], av['light_metal_3_sig_minus'] = averages_and_errors(probs, np.dot(light_weights, metal), sampling)
av['mass_age'], av['mass_age_1_sig_plus'], av['mass_age_1_sig_minus'], av['mass_age_2_sig_plus'], av['mass_age_2_sig_minus'], av['mass_age_3_sig_plus'], av['mass_age_3_sig_minus'] = averages_and_errors(probs, np.dot(mass_weights, log_age), sampling)
av['mass_metal'], av['mass_metal_1_sig_plus'], av['mass_metal_1_sig_minus'], av['mass_metal_2_sig_plus'], av['mass_metal_2_sig_minus'], av['mass_metal_3_sig_plus'], av['mass_metal_3_sig_minus'] = averages_and_errors(probs, np.dot(mass_weights, metal), sampling)
conversion_factor = 10.0**(-17) * 4 * np.pi * dist_lum**2.0 # unit 1e-17 cm2
tot_mass = np.log10(np.sum(unnorm_mass, 1) * conversion_factor)
av['stellar_mass'], av['stellar_mass_1_sig_plus'], av['stellar_mass_1_sig_minus'], av['stellar_mass_2_sig_plus'], av['stellar_mass_2_sig_minus'], av['stellar_mass_3_sig_plus'], av['stellar_mass_3_sig_minus'] = averages_and_errors(probs,tot_mass,sampling)
return av
#-----------------------------------------------------------------------
def normalise_spec(data_flux,model_flux):
"""
Normalises all models to the median value of the spectrum.
Saves the factors for later use.
Outputs : normed models and translation factors.
:param data_flux: observed flux in the data
:param model_flux: flux from the models
"""
data_norm = np.median(data_flux)
num_mods = len(model_flux)
model_norm,mass_factor = np.zeros(num_mods),np.zeros(num_mods)
normed_model_flux = np.zeros((num_mods,len(model_flux[0])))
for m in range(len(model_flux)):
model_norm[m] = np.median(model_flux[m])
mass_factor[m] = data_norm/model_norm[m]
normed_model_flux[m] = model_flux[m] / model_norm[m] * data_norm
return normed_model_flux,mass_factor
#-----------------------------------------------------------------------
def match_data_models( data_wave_int, data_flux_int, data_flags, error_flux_int, model_wave_int, model_flux_int, min_wave_in, max_wave_in, saveDowngradedModel = True, downgradedModelFile = "DGmodel.txt"):
"""
* 0.Take data and models as inputs
* 1. interpolate data and model to the lowest sampled array.
* 1.1. Defines the wavelength range on the model and on the data
* 1.2. Downgrades the array, model or data, that has most sampling
* 1.3. integrate between them to output a matched resolution array for data and model
* 2. Returns the matched wavelength array, the corresponding data, error and model arrays : matched_wave,matched_data,matched_error,matched_model
:param data_wave_int: data wavelength array in the restframe
:param data_flux_int: data flux array
:param data_flags: data quality flag array : 1 for good data
:param error_flux_int: data flux error array
:param model_wave_int: model wavelength array (in the rest frame)
:param model_flux_int: model flux array
:param min_wave_in: minimum wavelength to be considered
:param max_wave_in: maximum wavelength to be considered
:param saveDowngradedModel: if True it will save the downgraded models
:param downgradedModelFile: location where downgreaded models will be saved
"""
# 1. interpolate onto the bisection of lowest sampled array.
num_models = len(model_flux_int)
# 1.1. Defines the wavelength range on the model and on the data
min_wave = np.max([np.min(data_wave_int[np.where(data_flags==1)]), np.min(model_wave_int),min_wave_in])
max_wave = np.min([np.max(data_wave_int[np.where(data_flags==1)]), np.max(model_wave_int),max_wave_in])
#print np.min(data_wave_int[np.where(data_flags==1)]), np.min(model_wave_int), min_wave_in
#print np.max(data_wave_int[np.where(data_flags==1)]), np.max(model_wave_int), max_wave_in
loc_model = np.array(( model_wave_int <= max_wave) & (model_wave_int >= min_wave))
if np.sum(loc_model)==0:
raise ValueError("The wavelength range input is below or above model wavelength coverage!")
model_wave = model_wave_int[loc_model]
num_mod = np.sum(loc_model)
model_flux = np.zeros((num_models,num_mod))
for m in range(num_models):
model_flux[m] = model_flux_int[m][loc_model]
loc_data = np.array(( data_wave_int <= max_wave) & (data_wave_int >= min_wave))
if np.sum(loc_data)==0:
raise ValueError("The wavelength range input is below or above data wavelength coverage!")
num_dat = np.sum(loc_data)
data_wave = data_wave_int[loc_data]
data_flux = data_flux_int[loc_data]
error_flux = error_flux_int[loc_data]
# 1.2. Downgrades the array, model or data, that has most sampling
if num_mod >= num_dat:
#print "More model points than data points! Downgrading models to data sampling ..."
bisect_data = bisect_array(data_wave) + np.min(data_wave)*0.0000000001
matched_model = np.zeros((num_models,len(bisect_data) - 1))
for m in range(num_models):
model_flux_bounds = np.interp(bisect_data, model_wave, model_flux[m])
combined_wave_int = np.concatenate((model_wave,bisect_data))
combined_flux_int = np.concatenate((model_flux[m],model_flux_bounds))
sort_indices = np.argsort(combined_wave_int)
combined_wave = np.sort(combined_wave_int)
boundary_indices = np.searchsorted(combined_wave,bisect_data)
combined_flux = combined_flux_int[sort_indices]
len_combo = len(combined_flux)
# 1.3. produces a matched resolution array
for l in range(len(boundary_indices) - 1):
if boundary_indices[l + 1] >= len_combo:
matched_model[m][l] = matched_model[m][l - 1]
else:
matched_model[m][l] = np.trapz(combined_flux[boundary_indices[l] : boundary_indices[l + 1] + 1], x=combined_wave[boundary_indices[l] :boundary_indices[l + 1] + 1]) / (combined_wave[boundary_indices[l + 1]] - combined_wave[boundary_indices[l] ])
matched_wave = data_wave[1:-1]
matched_data = data_flux[1:-1]
matched_error = error_flux[1:-1]
# OPTION : saves the downgraded models.
if saveDowngradedModel:
#print "saving downgraded models to ",downgradedModelFile
f.open(downgradedModelFile,'w')
cPickle.dump([matched_wave, matched_data, matched_error],f)
f.close()
else:
#print "More data points than model points! Downgrading data to model sampling ..."
bisect_model = bisect_array(model_wave) + np.min(model_wave)*0.0000000001
boundaries = np.searchsorted(data_wave,bisect_model)
data_flux_bounds = np.interp(bisect_model, data_wave, data_flux)
error_flux_bounds = np.interp(bisect_model, data_wave, error_flux)
combined_wave_int = np.concatenate((data_wave,bisect_model))
combined_flux_int = np.concatenate((data_flux,data_flux_bounds))
combined_error_int = np.concatenate((data_flux,error_flux_bounds))
sort_indices = np.argsort(combined_wave_int)
combined_wave = np.sort(combined_wave_int)
boundary_indices = np.searchsorted(combined_wave,bisect_model)
combined_flux = combined_flux_int[sort_indices]
combined_error = combined_error_int[sort_indices]
# 1.3. produces a matched resolution array
matched_data,matched_error= np.zeros(len(boundary_indices) - 1),np.zeros(len(boundary_indices) - 1)
len_combo = len(combined_flux)
for l in range(len(boundary_indices) - 1):
if boundary_indices[l + 1] >= len_combo:
matched_data[l] = matched_data[l - 1]
matched_error[l] = matched_error[l - 1]
else:
matched_data[l] = np.trapz(combined_flux[boundary_indices[l]:boundary_indices[l + 1] + 1], x=combined_wave[boundary_indices[l]: boundary_indices[l + 1] + 1])/ (combined_wave[boundary_indices[l + 1]] - combined_wave[boundary_indices[l]])
matched_error[l] = np.trapz(combined_error[boundary_indices[l]:boundary_indices[l + 1] + 1], x=combined_wave[boundary_indices[l]:boundary_indices[l + 1] + 1])/ (combined_wave[boundary_indices[l + 1]] - combined_wave[boundary_indices[l]])
matched_wave = model_wave[1:-1]
matched_model = np.zeros((num_models,len(matched_wave)))
for m in range(num_models):
matched_model[m][:] = model_flux[m][1:-1]
return matched_wave,matched_data,matched_error,matched_model
|
JohanComparat/pySU
|
spm/python/firefly_library.py
|
Python
|
cc0-1.0
| 17,307
|
[
"Firefly"
] |
095eb4acede1b7d4a3f25bbafd2905e786a1f01eb17b9de0750498ccf32db115
|
from mdtraj import load
from mdtraj.testing import eq
def test_load_single(get_fn):
# Just check for any raised errors coming from loading a single file.
load(get_fn('frame0.pdb'))
def test_load_single_list(get_fn):
# See if a single-element list of files is successfully loaded.
load([get_fn('frame0.pdb')])
def test_load_many_list(get_fn):
# See if a multi-element list of files is successfully loaded.
single = load(get_fn('frame0.pdb'))
double = load(2 * [get_fn('frame0.pdb')], discard_overlapping_frames=False)
assert 2 * single.n_frames == double.n_frames
def test_load_atom_indices_multiple_files(get_fn):
ref_t = load(get_fn('native.pdb'))
t = load([get_fn('native.pdb')]*2, atom_indices=[0])
eq(t.topology, ref_t.topology.subset([0]))
|
dwhswenson/mdtraj
|
tests/test_load.py
|
Python
|
lgpl-2.1
| 796
|
[
"MDTraj"
] |
5bb5987f44dd667e49f27949dfb6eaf9d844662a9e320ec9c9aed68ba33d412c
|
import numpy as np
import neo
def theta_mod_idx(sptr, binsize, time_limit):
'''Theta modulation index as defined in [3]_
Parameters
----------
sptr : array
binsize : float
Temporal binsize of autocorrelogram
time_limit : flaot
Limit of autocorrelogram
References
-----------
.. [3] Cacucci, F., Lever, C., Wills, T. J., Burgess, N., & O'Keefe, J. (2004).
Theta-modulated place-by-direction cells in the hippocampal formation in the rat.
The Journal of Neuroscience, 24(38), 8265-8277.
'''
count, bins = correlogram(
t1=sptr, t2=None, binsize=binsize, limit=time_limit, auto=True)
th = count[(bins[:-1] >= .05) & (bins[:-1] <= .07)].mean()
pk = count[(bins[:-1] >= .1) & (bins[:-1] <= .14)].mean()
return (pk - th)/(pk + th)
def fano_factor(trials, bins=1, return_mean_var=False, return_bins=False):
"""
Calculate binned fano factor over several trials.
Parameters
----------
trials : list
a list with np.arrays of spike times
bins : np.ndarray or int
bins of where to calculate fano factor. Default is 1
return_mean_var : bool
return mean count rate of trials and variance
Returns
-------
out : float, or optional tuple
fano factor, or optional (mean, var) if return_mean_var, or optional
(fano factor, bins).
Note
----
This is a similar method as in [4]_, however there a sliding window was
used.
.. todo::
Sliding window calculation of the Fano factor
window = 50 * pq.ms
step_size = 10 * pq.ms
t_stop = 1 * pq.s
bins = []; i = 0
while i * step_size + window <= t_stop:
bins.extend([i * step_size, i * step_size + window])
i += 1
Examples
--------
>>> t1 = np.arange(0, .5, .1)
>>> t2 = np.arange(0.1, .6, .1)
>>> result = fano_factor([t1, t2], bins=3)
# array([ 0., 0., 0.])
If you want to further work with the means and vars
>>> result = fano_factor([t1, t2], bins=3, return_mean_var=True)
# (array([ 2., 1., 2.]), array([ 0., 0., 0.]))
The fano factor is 1 for Poisson processes
>>> from elephant.spike_train_generation import homogeneous_poisson_process
>>> np.random.seed(12345)
>>> t1 = [homogeneous_poisson_process(
... 10 * pq.Hz, t_start=0.0 * pq.s, t_stop=1 * pq.s) for _ in range(100)]
>>> result = fano_factor(t1)
# array([ 0.95394394])
The Fano factor computed in bins along time can be acheived with including
`bins` which can be `int`
>>> ff, bins = fano_factor(t1, bins=4, return_bins=True)
# TODO fix
# >>> ff
# array([ 0.78505226, 1.16330097, 1.00901961, 0.80781457])
# >>> bins
# array([ 0.06424358, 0.29186518, 0.51948679, 0.74710839, 0.97472999])
To specify bins
# TODO fix
# >>> bins = np.arange(0, 1, .2)
# >>> fano_factor(t1, bins=bins)
# array([ 0.95941748, 1.09 , 1.05650485, 0.72886256])
References
----------
.. [4] Churchland, M. M., Byron, M. Y., Cunningham, J. P., Sugrue, L. P.,
Cohen, M. R., Corrado, G. S., ... & Bradley, D. C. (2010). Stimulus onset
quenches neural variability: a widespread cortical phenomenon. Nature
neuroscience, 13(3), 369-378.
"""
# TODO matching
assert len(trials) > 0, 'trials cannot be empty'
if isinstance(bins, int):
nbins = bins
else:
nbins = len(bins) - 1
hists = np.zeros((len(trials), nbins))
for trial_num, trial in enumerate(trials):
hist, _bins = np.histogram(trial, bins)
hists[trial_num, :] = hist
if len(trials) == 1: # calculate fano over one trial
axis = 1 # cols
else:
axis = 0 # rows
mean = np.mean(hists, axis=axis)
var = np.var(hists, axis=axis)
if return_mean_var:
if return_bins:
return mean, var, bins
else:
return mean, var
else:
fano = var / mean
if return_bins:
return fano, _bins
else:
return fano
def fano_factor_multiunit(unit_trials, bins=1, return_rates=False,
return_bins=False):
'''
Calculate fano factor over several units with several trials as slopes from
linear regression relating the variance to the mean of spike counts; see
[4]_.
Parameters
----------
unit_trials : list of lists with trials
That is unit_trials[0] = first unit, unit_trials[0][0] = first trial of
first unit.
bins : np.ndarray or int
bins of where to calculate fano factor. Default is 1
Returns
-------
(slopes, std_errors) : tuple
Fano factor for each bin with corresponding standard error of the mean.
.. todo::
Weighted regression (binsize/1000) and distribution matching as in [4]_.
See also
--------
:func:`exana.statistics.fano_factor` : The function that calcuates mean
and var.
:func:`scipy.statistics.linregress` : The function that calcuates slopes
and standard error.
Note
----
You need many neurons to get a decent output value as you only have one
datapoint per neuron. If you have some neurons with many trials consider
doing a weighted regression.
To get 95 % confidence interval you may use the standard error of teh mean
by (fano - 2 * std_err, fano + 2 * std_err)
Examples
--------
The fano factor is 1 for Poisson processes, thus we genereate 100 Poisson
spiking neurons with each 10 trials.
>>> from elephant.spike_train_generation import homogeneous_poisson_process
>>> np.random.seed(12345)
>>> units_trials = [
... [homogeneous_poisson_process(
... 10 * pq.Hz, t_start=0.0 * pq.s, t_stop=1 * pq.s)
... for _ in range(10)] for _ in range(100)]
>>> fano, std_err = fano_factor_multiunit(units_trials)
>>> print('{:.2}, {:.2}'.format(fano[0], std_err[0]))
0.92, 0.041
'''
from scipy.stats import linregress
if isinstance(bins, int):
nbins = bins
else:
nbins = len(bins) - 1
nunits = len(unit_trials)
means = np.zeros((nunits, nbins))
varis = np.zeros((nunits, nbins))
for unit_num, trials in enumerate(unit_trials):
if len(trials) == 0:
continue
mean, var, bins = fano_factor(trials, bins, return_mean_var=True,
return_bins=True)
means[unit_num, :] = mean
varis[unit_num, :] = var
fanos = []
std_errs = []
for nb in range(nbins):
slope, intercept, r_value, p_value, std_err = linregress(means[:, nb],
varis[:, nb])
std_errs.append(std_err / np.sqrt(nunits))
fanos.append(slope)
if return_rates:
rates = np.mean(means, axis=0) / (bins[1] - bins[0])
if return_bins:
return fanos, std_errs, rates, bins
else:
return fanos, std_errs, rates
else:
if return_bins:
return fanos, std_errs, bins
else:
return fanos, std_errs
def coeff_var(trials):
"""
Calculate the coefficient of variation in inter spike interval (ISI)
distribution over several trials
Parameters
----------
trials : list of neo.SpikeTrain or array like
Returns
-------
out : list
Coefficient of variations for each trial, nan if len(trial) == 0
Examples
--------
>>> np.random.seed(12345)
>>> trials = [np.arange(10), np.random.random((10))]
>>> print('{d[0]:.2f}, {d[1]:.2f}'.format(d=coeff_var(trials)))
0.00, -9.53
"""
cvs = []
for trial in trials:
isi = np.diff(trial)
if len(isi) > 0:
cvs.append(np.std(isi) / np.mean(isi))
else:
cvs.append(np.nan)
return cvs
def bootstrap(data, num_samples=10000, statistic=None, alpha=0.05):
"""
Returns bootstrap estimate of 100.0*(1-alpha) CI for statistic.
Adapted from http://people.duke.edu/~ccc14/pcfb/analysis.html
Parameters
----------
data : array like
1D array like representation of your data.
num_samples : int
The number of repetitions of random samples of your data.
statistic : function(2darray, axis)
The statistic you want to build the ci. Default is mean
Returns
-------
confidence interval : tuple
The confidence interval for given statistic.
Examples
--------
Unlike using normal assumptions to calculate 95% CI, the
results generated by the bootstrap are robust even if the underlying data
are very far from normal.
Bimodal data of interest
>>> import numpy.random as npr
>>> import numpy as np
>>> npr.seed(12345)
>>> x = np.concatenate([npr.normal(3, 1, 100), npr.normal(6, 2, 200)])
To find the find mean 95% CI by 100 000 bootstrap samples
>>> low, high = bootstrap(data=x, num_samples=100000, statistic=np.mean,
... alpha=0.05)
>>> print('{:.2f}, {:.2f}'.format(low, high))
4.64, 5.12
Historgram of the data with corresponding scatter with mean and it's CI
.. plot::
import matplotlib.pyplot as plt
import numpy.random as npr
import numpy as np
npr.seed(12345)
from exana.statistics import bootstrap
x = np.concatenate([npr.normal(3, 1, 100), npr.normal(6, 2, 200)])
ci = bootstrap(data=x, num_samples=100000, statistic=np.mean, alpha=0.05)
plt.figure(figsize=(8,4))
plt.subplot(121)
plt.hist(x, 50, histtype='step')
plt.title('Historgram of skewed data')
plt.subplot(122)
plt.plot([-0.03,0.03], [np.mean(x), np.mean(x)], 'k', linewidth=2, label='mean')
plt.scatter(0.1*(npr.random(len(x)) - 0.5), x)
plt.plot([0.19,0.21], [ci[0], ci[0]], 'r', linewidth=2, label='95% CI')
plt.plot([0.19,0.21], [ci[1], ci[1]], 'r', linewidth=2)
plt.plot([0.2,0.2], [ci[0], ci[1]], 'r', linewidth=2)
plt.xlim([-0.2, 0.3])
plt.title('Bootstrap 95% CI for mean')
plt.legend()
plt.show()
The bootstrap function is a higher order function, and will return the
boostrap CI for any valid statistical function, not just the mean.
For example, to find the 95% CI for the standard deviation, given
:func:`np.std` as the statistic:
>>> low, high = bootstrap(data=x, num_samples=100000, statistic=np.std,
... alpha=0.05)
>>> print('{:.2f}, {:.2f}'.format(low, high))
1.97, 2.26
"""
data = np.asarray(data)
if np.ndim(data) != 1:
raise ValueError('Data must be 1 dimensional.')
statistic = statistic or np.mean
n = len(data)
idx = np.random.randint(0, n, (num_samples, n))
samples = data[idx]
stat = np.sort(statistic(samples, axis=1))
return (stat[int((alpha / 2.0) * num_samples)],
stat[int((1 - alpha / 2.0) * num_samples)])
def permutation_resampling(case, control, num_samples=10000, statistic=None):
"""
Simulation-based statistical calculation of p-value that statistic for case
is different from statistic for control under the null hypothesis that the
groups are invariant under label permutation. That is, case and control is
combined and shuffeled randomly `num_samples` times and given statistic is
calculated after each shuffle. Given the observed differece as the absulete
differece between the statistic of the case and control. Then the p-value is
calculated as the number of occurences where the shuffled statistic is
greater than the observed differece pluss the number of occurences where
the shuffled statistic is less than the negative observed differece, divided
by the number of shuffles.
For example, in a case-control study, it can be used to find the p-value
under the hypothesis that the mean of the case group is different from that
of the control group, and we cannot use the t-test because the distributions
are highly skewed.
Adapted from http://people.duke.edu/~ccc14/pcfb/analysis.html
Parameters
----------
case : 1D array like
Samples from the case study.
control : 1D array like
Samples from the control study.
num_samples : int
Number of permutations
statistic : function(2darray, axis)
The statistic function to compare case and control. Default is mean
Returns
-------
pval : float
The calculated p-value.
observed_diff : float
Absolute difference between statistic of `case` and statistic of
`control`.
diffs : list
A list of length equal to `num_samples` with differences between
statistic of permutated case and statistic of permutated control.
Examples
--------
Make up some data
>>> np.random.seed(12345)
>>> case = [94, 38, 23, 197, 99, 16, 141]
>>> control = [52, 10, 40, 104, 51, 27, 146, 30, 46]
Find the p-value by permutation resampling
>>> pval, observed_diff, diffs = permutation_resampling(
... case, control, 10000, np.mean)
.. plot::
import matplotlib.pylab as plt
import numpy as np
from exana.statistics import permutation_resampling
case = [94, 38, 23, 197, 99, 16, 141]
control = [52, 10, 40, 104, 51, 27, 146, 30, 46]
pval, observed_diff, diffs = permutation_resampling(
case, control, 10000, np.mean)
plt.title('Empirical null distribution for differences in mean')
plt.hist(diffs, bins=100, histtype='step', normed=True)
plt.axvline(observed_diff, c='red', label='diff')
plt.axvline(-observed_diff, c='green', label='-diff')
plt.text(60, 0.01, 'p = %.3f' % pval, fontsize=16)
plt.legend()
plt.show()
"""
statistic = statistic or np.mean
observed_diff = abs(statistic(case) - statistic(control))
num_case = len(case)
combined = np.concatenate([case, control])
diffs = []
for i in range(num_samples):
xs = np.random.permutation(combined)
diff = np.mean(xs[:num_case]) - np.mean(xs[num_case:])
diffs.append(diff)
pval = (np.sum(diffs > observed_diff) +
np.sum(diffs < -observed_diff))/float(num_samples)
return pval, observed_diff, diffs
def stat_test(tdict, test_func=None, nan_rule='remove', stat_key='statistic'):
'''
A very simple function to performes statistic tests between multiple groups
in `tdict` by given test function.
Parameters
----------
tdict : dict
Dictionary where each key represents a 1D dataset of observations
test_func : statistic, pvalue = function(case, control)
Function that takes in two 1D arrays and returns desired statistic with
corresponding p-value.
nan_rule : str {'remove', None}
What to do with nans
stat_key : str
A textual representation of the returned statistic
Returns
-------
out : pandas.DataFrame
A dataframe describing statistics and pvalue.
Example
-------
>>> tdict = {'group1': [94, 38, 23, 197, 99, 16, 141],
... 'group2': [52, 10, 40, 104, 51, 27, 146, 30, 46],
... 'group3': [3, 10, 40, 0, 51, 27, 1, 30, 46]}
>>> def stat_func(a, b):
... pval, diff, _ = permutation_resampling(a, b, 10000, np.mean)
... return diff, pval
>>> out = stat_test(tdict, test_func=stat_func, stat_key='abs diff mean')
'''
import pandas as pd
if test_func is None:
from scipy import stats
test_func = lambda g1, g2: stats.ttest_ind(g1, g2, equal_var=False)
ps = {}
sts ={}
lib = []
for key1, item1 in tdict.items():
for key2, item2 in tdict.items():
if key1 != key2:
if set([key1, key2]) in lib:
continue
lib.append(set([key1, key2]))
one = np.array(item1, dtype=np.float64)
two = np.array(item2, dtype=np.float64)
if nan_rule == 'remove':
one = one[np.isfinite(one)]
two = two[np.isfinite(two)]
elif nan_rule is None:
pass
else:
raise NotImplementedError
assert len(one) > 0, 'Empty list of values'
assert len(two) > 0, 'Empty list of values'
stat, p = test_func(one, two)
ps[key1+'--'+key2] = p
sts[key1+'--'+key2] = stat
return pd.DataFrame([ps, sts], index=['p-value', stat_key])
def poisson_continuity_correction(n, rate):
"""
n : Likelihood to observe n or more events
rate : float
Rate of Poisson process
References
----------
Stark, E., & Abeles, M. (2009). Unbiased estimation of precise temporal
correlations between spike trains. Journal of neuroscience methods, 179(1),
90-100.
"""
from scipy.stats import poisson
assert np.all(n >= 0)
return_arr = np.zeros(n.shape)
for i, n_i in enumerate(n):
if n_i == 0:
return_arr[i] = 1.
else:
rates = [poisson.pmf(j, rate) for j in range(int(n_i))]
return_arr[i] = 1 - np.sum(rates) - 0.5 * poisson.pmf(n_i, rate)
return return_arr
def hollow_kernel(kernlen, width, hollow_fraction=0.6, kerntype='gaussian'):
'''
Returns a hollow kernel normalized to it's sum
Parameters
----------
kernlen : int
Length of kernel, must be uneven (kernlen % 2 == 1)
width : float
Width of kernel (std if gaussian)
hollow_fraction : float
Fractoin of the central bin to removed.
Returns
-------
kernel : array
'''
if kerntype == 'gaussian':
from scipy.signal import gaussian
assert kernlen % 2 == 1
kernel = gaussian(kernlen, width)
kernel[int(kernlen / 2.)] *= (1 - hollow_fraction)
else:
raise NotImplementedError
return kernel / sum(kernel)
def ccg_significance(t1, t2, binsize, limit, hollow_fraction, width,
kerntype='gaussian'):
"""
Parameters
---------
t1 : np.array, or neo.SpikeTrain
First spiketrain, raw spike times in seconds.
t2 : np.array, or neo.SpikeTrain
Second spiketrain, raw spike times in seconds.
binsize : float, or quantities.Quantity
Width of each bar in histogram in seconds.
limit : float, or quantities.Quantity
Positive and negative extent of histogram, in seconds.
kernlen : int
Length of kernel, must be uneven (kernlen % 2 == 1)
width : float
Width of kernel (std if gaussian)
hollow_fraction : float
Fractoin of the central bin to removed.
References
----------
Stark, E., & Abeles, M. (2009). Unbiased estimation of precise temporal
correlations between spike trains. Journal of neuroscience methods, 179(1),
90-100.
English et al. 2017, Neuron, Pyramidal Cell-Interneuron Circuit Architecture
and Dynamics in Hippocampal Networks
"""
import scipy.signal as scs
ccg, bins = correlogram(t1, t2, binsize=binsize, limit=limit,
density=False)
kernlen = len(ccg) - 1
kernel = hollow_kernel(kernlen, width, hollow_fraction, kerntype)
# padd edges
len_padd = int(kernlen / 2.)
ccg_padded = np.zeros(len(ccg) + 2 * len_padd)
# "firstW/2 bins (excluding the very first bin) are duplicated,
# reversed in time, and prepended to the ccg prior to convolving"
ccg_padded[0:len_padd] = ccg[1:len_padd+1][::-1]
ccg_padded[len_padd: - len_padd] = ccg
# # "Likewise, the lastW/2 bins aresymmetrically appended to the ccg."
ccg_padded[-len_padd:] = ccg[-len_padd-1:-1][::-1]
# convolve ccg with kernel
ccg_smoothed = scs.fftconvolve(ccg_padded, kernel, mode='valid')
pfast = np.zeros(ccg.shape)
assert len(ccg) == len(ccg_smoothed)
for m, (val_m, rate_m) in enumerate(zip(ccg, ccg_smoothed)):
pfast[m] = poisson_continuity_correction(np.array([val_m]), rate_m)
# pcausal describes the probability of obtaining a peak on one side
# of the histogram, that is signficantly larger than the largest peak
# in the anticausal direction. we leave the zero peak empty
pcausal = np.zeros(ccg.shape)
ccg_half_len = int(np.floor(len(ccg) / 2.))
max_pre = np.max(ccg[:ccg_half_len])
max_post = np.max(ccg[ccg_half_len:])
for m, val_m in enumerate(ccg):
if m < ccg_half_len:
pcausal[m] = poisson_continuity_correction(
np.array([val_m]), max_post)
if m > ccg_half_len:
pcausal[m] = poisson_continuity_correction(
np.array([val_m]), max_pre)
return pcausal, pfast, bins, ccg, ccg_smoothed
def correlogram(t1, t2=None, binsize=.001, limit=.02, auto=False,
density=False):
"""Return crosscorrelogram of two spike trains.
Essentially, this algorithm subtracts each spike time in `t1`
from all of `t2` and bins the results with np.histogram, though
several tweaks were made for efficiency.
Originally authored by Chris Rodger, copied from OpenElectrophy, licenced
with CeCill-B. Examples and testing written by exana team.
Parameters
---------
t1 : np.array, or neo.SpikeTrain
First spiketrain, raw spike times in seconds.
t2 : np.array, or neo.SpikeTrain
Second spiketrain, raw spike times in seconds.
binsize : float, or quantities.Quantity
Width of each bar in histogram in seconds.
limit : float, or quantities.Quantity
Positive and negative extent of histogram, in seconds.
auto : bool
If True, then returns autocorrelogram of `t1` and in
this case `t2` can be None. Default is False.
density : bool
If True, then returns the probability density function.
See also
--------
:func:`numpy.histogram` : The histogram function in use.
Returns
-------
(count, bins) : tuple
A tuple containing the bin right edges and the
count/density of spikes in each bin.
Note
----
`bins` are relative to `t1`. That is, if `t1` leads `t2`, then
`count` will peak in a positive time bin.
Examples
--------
>>> t1 = np.arange(0, .5, .1)
>>> t2 = np.arange(0.1, .6, .1)
>>> limit = 1
>>> binsize = .1
>>> counts, bins = correlogram(t1=t1, t2=t2, binsize=binsize,
... limit=limit, auto=False)
>>> counts
array([0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, 0, 0, 0])
The interpretation of this result is that there are 5 occurences where
in the bin 0 to 0.1, i.e.
# TODO fix
# >>> idx = np.argmax(counts)
# >>> '%.1f, %.1f' % (abs(bins[idx - 1]), bins[idx])
# '0.0, 0.1'
The correlogram algorithm is identical to, but computationally faster than
the histogram of differences of each timepoint, i.e.
# TODO Fix the doctest
# >>> diff = [t2 - t for t in t1]
# >>> counts2, bins = np.histogram(diff, bins=bins)
# >>> np.array_equal(counts2, counts)
# True
"""
if auto: t2 = t1
# For auto-CCGs, make sure we use the same exact values
# Otherwise numerical issues may arise when we compensate for zeros later
if not int(limit * 1e10) % int(binsize * 1e10) == 0:
raise ValueError(
'Time limit {} must be a '.format(limit) +
'multiple of binsize {}'.format(binsize) +
' remainder = {}'.format(limit % binsize))
# For efficiency, `t1` should be no longer than `t2`
swap_args = False
if len(t1) > len(t2):
swap_args = True
t1, t2 = t2, t1
# Sort both arguments (this takes negligible time)
t1 = np.sort(t1)
t2 = np.sort(t2)
# Determine the bin edges for the histogram
# Later we will rely on the symmetry of `bins` for undoing `swap_args`
limit = float(limit)
# The numpy.arange method overshoots slightly the edges i.e. binsize + epsilon
# which leads to inclusion of spikes falling on edges.
bins = np.arange(-limit, limit + binsize, binsize)
# Determine the indexes into `t2` that are relevant for each spike in `t1`
ii2 = np.searchsorted(t2, t1 - limit)
jj2 = np.searchsorted(t2, t1 + limit)
# Concatenate the recentered spike times into a big array
# We have excluded spikes outside of the histogram range to limit
# memory use here.
big = np.concatenate([t2[i:j] - t for t, i, j in zip(t1, ii2, jj2)])
# Actually do the histogram. Note that calls to np.histogram are
# expensive because it does not assume sorted data.
count, bins = np.histogram(big, bins=bins, density=density)
if auto:
# Compensate for the peak at time zero that results in autocorrelations
# by subtracting the total number of spikes from that bin. Note
# possible numerical issue here because 0.0 may fall at a bin edge.
c_temp, bins_temp = np.histogram([0.], bins=bins)
bin_containing_zero = np.nonzero(c_temp)[0][0]
count[bin_containing_zero] = 0#-= len(t1)
# Finally compensate for the swapping of t1 and t2
if swap_args:
# Here we rely on being able to simply reverse `counts`. This is only
# possible because of the way `bins` was defined (bins = -bins[::-1])
count = count[::-1]
return count, bins[1:]
|
CINPLA/exana
|
exana/statistics/tools.py
|
Python
|
gpl-3.0
| 25,725
|
[
"Gaussian",
"NEURON"
] |
fc7ef522b6e0ff4a799932d3d144e79773abff7b69a591ddbb152f8e31be67e6
|
'''
This script runs simulations by loading the connection matrices from the network that reproduced the results
shown in the paper and randomly pruning some percentage of one connection type. E.g. A random subset of 50% of the
MLI-MLI connections will be pruned (removed) and the simulation run. The output is firing rate and ISI CV statistics for
each neuron averaged across the entire simulation. This script runs one simulation for each scenario pruning either
MLI-MLI or PKJ-MLI connections by 0%, 25%, 50%, 75%, 100%.
Note: you can use any set of saved connection matrices to run these experiments.
This file dumps the data to disk. A corresponding IPython notebook is used to analyze the data,
"connections_prune_analysis.ipynb".
'''
import datetime
import os
import gc
import multiprocessing
from itertools import repeat
from brian import *
import sys
sys.path.append('../../')
from MLI_PKJ_net import *
import cPickle
import time
from itertools import product
set_global_preferences(useweave=True, usenewpropagate=True, usecodegen=True, usecodegenweave=True)
defaultclock.dt = .25*ms
import random
def prune_synapses(syn,pct):
'''
randomly set 'pct' percent synapse weights to 0 for synapse object 'syn'
'''
N = syn.w[:,:].shape[0]
inds = random.sample(range(N), int(N*pct))
syn.w[inds] = 0.
def run_net((syn_prune,prune_pct)):
'''
sets up a network and simulates it.
syn_prune: which synapse type to prune
prune_pct: percent to prune the synapses by.
'''
seed(int(os.getpid()*time.time()))
print os.getpid()
reinit()
reinit_default_clock()
clear(True)
gc.collect()
T = 60*second
N_MLI = 160
N_PKJ = 16
MLI = MLIGroup(N_MLI)
PKJ = PurkinjeCellGroup(N_PKJ)
# synaptic weights
w_mli_pkj = 1.25
w_mli_mli = 1.
w_pkj_mli = 1.
# Synapses
S_MLI_PKJ = Synapses(MLI,PKJ,model='w:1',pre='g_inh+=PKJ.g_inh_*w')
S_MLI_MLI = Synapses(MLI,MLI,model='w:1',pre='g_inh+=MLI.g_inh_*w')
S_PKJ_MLI = Synapses(PKJ,MLI,model='w:1',pre='g_inh+=MLI.g_inh_*w')
# load saved synapses
syn_dir = '/home/bill/shared_folder/research/paper #1/synapses/'
S_MLI_PKJ = load_synapses(S_MLI_PKJ, 'S_MLI_PKJ', syn_dir)
S_MLI_MLI = load_synapses(S_MLI_MLI, 'S_MLI_MLI', syn_dir)
S_PKJ_MLI = load_synapses(S_PKJ_MLI, 'S_PKJ_MLI', syn_dir)
if syn_prune == 'MLI_PKJ':
prune_synapses(S_MLI_PKJ, prune_pct)
elif syn_prune == 'MLI_MLI':
prune_synapses(S_MLI_MLI, prune_pct)
elif syn_prune == 'PKJ_MLI':
prune_synapses(S_PKJ_MLI, prune_pct)
else:
raise Exception('syn_prune must be MLI_PKJ, MLI_MLI or PKJ_MLI')
@network_operation(Clock(dt=defaultclock.dt))
def random_current():
MLI.I = gamma(3.966333,0.006653,size=len(MLI)) * nA
PKJ.I = gamma(0.430303,0.195962,size=len(PKJ)) * nA
# Monitor
MS_MLI = SpikeMonitor(MLI)
MS_PKJ = SpikeMonitor(PKJ)
start = time.time()
run(T)
print time.time() - start
return syn_prune, prune_pct, fr_stats(MS_MLI), isi_cv_stats(MS_MLI), fr_stats(MS_PKJ), isi_cv_stats(MS_PKJ)
if __name__ == "__main__":
# run the simulations (in parallel if N_cores > 1)
N_cores = 2
pool = multiprocessing.Pool(N_cores)
results = pool.map(run_net, product(['MLI_MLI', 'MLI_PKJ', 'PKJ_MLI'],[0.,.25,.5,.75,1.]))
# save the results to disk
out_dir = '../../results/'
cPickle.dump(results,open(out_dir+'connections_prune_results.pkl','w'))
|
blennon/MLI_PKJ_net
|
MLI_PKJ_net/experiments/MLI_PKJ_net_connections_prune.py
|
Python
|
mit
| 3,519
|
[
"Brian",
"NEURON"
] |
7099cb2930065ae672f0fd559c824a10e9a33e3dccf942b69f2a285c4810163e
|
# Copyright (c) 2012 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.
"""Top-level presubmit script for Chromium.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into depot_tools.
"""
_EXCLUDED_PATHS = (
r"^breakpad[\\\/].*",
r"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_rules.py",
r"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_simple.py",
r"^native_client_sdk[\\\/]src[\\\/]tools[\\\/].*.mk",
r"^net[\\\/]tools[\\\/]spdyshark[\\\/].*",
r"^skia[\\\/].*",
r"^v8[\\\/].*",
r".*MakeFile$",
r".+_autogen\.h$",
r".+[\\\/]pnacl_shim\.c$",
r"^gpu[\\\/]config[\\\/].*_list_json\.cc$",
r"^chrome[\\\/]browser[\\\/]resources[\\\/]pdf[\\\/]index.js"
)
# The NetscapePlugIn library is excluded from pan-project as it will soon
# be deleted together with the rest of the NPAPI and it's not worthwhile to
# update the coding style until then.
_TESTRUNNER_PATHS = (
r"^content[\\\/]shell[\\\/]tools[\\\/]plugin[\\\/].*",
)
# Fragment of a regular expression that matches C++ and Objective-C++
# implementation files.
_IMPLEMENTATION_EXTENSIONS = r'\.(cc|cpp|cxx|mm)$'
# Regular expression that matches code only used for test binaries
# (best effort).
_TEST_CODE_EXCLUDED_PATHS = (
r'.*[\\\/](fake_|test_|mock_).+%s' % _IMPLEMENTATION_EXTENSIONS,
r'.+_test_(base|support|util)%s' % _IMPLEMENTATION_EXTENSIONS,
r'.+_(api|browser|kif|perf|pixel|unit|ui)?test(_[a-z]+)?%s' %
_IMPLEMENTATION_EXTENSIONS,
r'.+profile_sync_service_harness%s' % _IMPLEMENTATION_EXTENSIONS,
r'.*[\\\/](test|tool(s)?)[\\\/].*',
# content_shell is used for running layout tests.
r'content[\\\/]shell[\\\/].*',
# At request of folks maintaining this folder.
r'chrome[\\\/]browser[\\\/]automation[\\\/].*',
# Non-production example code.
r'mojo[\\\/]examples[\\\/].*',
# Launcher for running iOS tests on the simulator.
r'testing[\\\/]iossim[\\\/]iossim\.mm$',
)
_TEST_ONLY_WARNING = (
'You might be calling functions intended only for testing from\n'
'production code. It is OK to ignore this warning if you know what\n'
'you are doing, as the heuristics used to detect the situation are\n'
'not perfect. The commit queue will not block on this warning.')
_INCLUDE_ORDER_WARNING = (
'Your #include order seems to be broken. Remember to use the right '
'collation (LC_COLLATE=C) and check\nhttps://google-styleguide.googlecode'
'.com/svn/trunk/cppguide.html#Names_and_Order_of_Includes')
_BANNED_OBJC_FUNCTIONS = (
(
'addTrackingRect:',
(
'The use of -[NSView addTrackingRect:owner:userData:assumeInside:] is'
'prohibited. Please use CrTrackingArea instead.',
'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
),
False,
),
(
r'/NSTrackingArea\W',
(
'The use of NSTrackingAreas is prohibited. Please use CrTrackingArea',
'instead.',
'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
),
False,
),
(
'convertPointFromBase:',
(
'The use of -[NSView convertPointFromBase:] is almost certainly wrong.',
'Please use |convertPoint:(point) fromView:nil| instead.',
'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
),
True,
),
(
'convertPointToBase:',
(
'The use of -[NSView convertPointToBase:] is almost certainly wrong.',
'Please use |convertPoint:(point) toView:nil| instead.',
'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
),
True,
),
(
'convertRectFromBase:',
(
'The use of -[NSView convertRectFromBase:] is almost certainly wrong.',
'Please use |convertRect:(point) fromView:nil| instead.',
'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
),
True,
),
(
'convertRectToBase:',
(
'The use of -[NSView convertRectToBase:] is almost certainly wrong.',
'Please use |convertRect:(point) toView:nil| instead.',
'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
),
True,
),
(
'convertSizeFromBase:',
(
'The use of -[NSView convertSizeFromBase:] is almost certainly wrong.',
'Please use |convertSize:(point) fromView:nil| instead.',
'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
),
True,
),
(
'convertSizeToBase:',
(
'The use of -[NSView convertSizeToBase:] is almost certainly wrong.',
'Please use |convertSize:(point) toView:nil| instead.',
'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
),
True,
),
)
_BANNED_CPP_FUNCTIONS = (
# Make sure that gtest's FRIEND_TEST() macro is not used; the
# FRIEND_TEST_ALL_PREFIXES() macro from base/gtest_prod_util.h should be
# used instead since that allows for FLAKY_ and DISABLED_ prefixes.
(
'FRIEND_TEST(',
(
'Chromium code should not use gtest\'s FRIEND_TEST() macro. Include',
'base/gtest_prod_util.h and use FRIEND_TEST_ALL_PREFIXES() instead.',
),
False,
(),
),
(
'ScopedAllowIO',
(
'New code should not use ScopedAllowIO. Post a task to the blocking',
'pool or the FILE thread instead.',
),
True,
(
r"^base[\\\/]process[\\\/]process_metrics_linux\.cc$",
r"^chrome[\\\/]browser[\\\/]chromeos[\\\/]boot_times_recorder\.cc$",
r"^chrome[\\\/]browser[\\\/]chromeos[\\\/]"
"customization_document_browsertest\.cc$",
r"^components[\\\/]crash[\\\/]app[\\\/]breakpad_mac\.mm$",
r"^content[\\\/]shell[\\\/]browser[\\\/]shell_browser_main\.cc$",
r"^content[\\\/]shell[\\\/]browser[\\\/]shell_message_filter\.cc$",
r"^mojo[\\\/]edk[\\\/]embedder[\\\/]" +
r"simple_platform_shared_buffer_posix\.cc$",
r"^net[\\\/]disk_cache[\\\/]cache_util\.cc$",
r"^net[\\\/]url_request[\\\/]test_url_fetcher_factory\.cc$",
r"^ui[\\\/]ozone[\\\/]platform[\\\/]drm[\\\/]host[\\\/]"
"drm_display_host_manager\.cc$",
),
),
(
'SkRefPtr',
(
'The use of SkRefPtr is prohibited. ',
'Please use skia::RefPtr instead.'
),
True,
(),
),
(
'SkAutoRef',
(
'The indirect use of SkRefPtr via SkAutoRef is prohibited. ',
'Please use skia::RefPtr instead.'
),
True,
(),
),
(
'SkAutoTUnref',
(
'The use of SkAutoTUnref is dangerous because it implicitly ',
'converts to a raw pointer. Please use skia::RefPtr instead.'
),
True,
(),
),
(
'SkAutoUnref',
(
'The indirect use of SkAutoTUnref through SkAutoUnref is dangerous ',
'because it implicitly converts to a raw pointer. ',
'Please use skia::RefPtr instead.'
),
True,
(),
),
(
r'/HANDLE_EINTR\(.*close',
(
'HANDLE_EINTR(close) is invalid. If close fails with EINTR, the file',
'descriptor will be closed, and it is incorrect to retry the close.',
'Either call close directly and ignore its return value, or wrap close',
'in IGNORE_EINTR to use its return value. See http://crbug.com/269623'
),
True,
(),
),
(
r'/IGNORE_EINTR\((?!.*close)',
(
'IGNORE_EINTR is only valid when wrapping close. To wrap other system',
'calls, use HANDLE_EINTR. See http://crbug.com/269623',
),
True,
(
# Files that #define IGNORE_EINTR.
r'^base[\\\/]posix[\\\/]eintr_wrapper\.h$',
r'^ppapi[\\\/]tests[\\\/]test_broker\.cc$',
),
),
(
r'/v8::Extension\(',
(
'Do not introduce new v8::Extensions into the code base, use',
'gin::Wrappable instead. See http://crbug.com/334679',
),
True,
(
r'extensions[\\\/]renderer[\\\/]safe_builtins\.*',
),
),
(
'\<MessageLoopProxy\>',
(
'MessageLoopProxy is deprecated. ',
'Please use SingleThreadTaskRunner or ThreadTaskRunnerHandle instead.'
),
True,
(
# Internal message_loop related code may still use it.
r'^base[\\\/]message_loop[\\\/].*',
),
),
)
_IPC_ENUM_TRAITS_DEPRECATED = (
'You are using IPC_ENUM_TRAITS() in your code. It has been deprecated.\n'
'See http://www.chromium.org/Home/chromium-security/education/security-tips-for-ipc')
_VALID_OS_MACROS = (
# Please keep sorted.
'OS_ANDROID',
'OS_ANDROID_HOST',
'OS_BSD',
'OS_CAT', # For testing.
'OS_CHROMEOS',
'OS_FREEBSD',
'OS_IOS',
'OS_LINUX',
'OS_MACOSX',
'OS_NACL',
'OS_NACL_NONSFI',
'OS_NACL_SFI',
'OS_OPENBSD',
'OS_POSIX',
'OS_QNX',
'OS_SOLARIS',
'OS_WIN',
)
def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
"""Attempts to prevent use of functions intended only for testing in
non-testing code. For now this is just a best-effort implementation
that ignores header files and may have some false positives. A
better implementation would probably need a proper C++ parser.
"""
# We only scan .cc files and the like, as the declaration of
# for-testing functions in header files are hard to distinguish from
# calls to such functions without a proper C++ parser.
file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
base_function_pattern = r'[ :]test::[^\s]+|ForTest(ing)?|for_test(ing)?'
inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
comment_pattern = input_api.re.compile(r'//.*(%s)' % base_function_pattern)
exclusion_pattern = input_api.re.compile(
r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
base_function_pattern, base_function_pattern))
def FilterFile(affected_file):
black_list = (_EXCLUDED_PATHS +
_TEST_CODE_EXCLUDED_PATHS +
input_api.DEFAULT_BLACK_LIST)
return input_api.FilterSourceFile(
affected_file,
white_list=(file_inclusion_pattern, ),
black_list=black_list)
problems = []
for f in input_api.AffectedSourceFiles(FilterFile):
local_path = f.LocalPath()
for line_number, line in f.ChangedContents():
if (inclusion_pattern.search(line) and
not comment_pattern.search(line) and
not exclusion_pattern.search(line)):
problems.append(
'%s:%d\n %s' % (local_path, line_number, line.strip()))
if problems:
return [output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)]
else:
return []
def _CheckNoIOStreamInHeaders(input_api, output_api):
"""Checks to make sure no .h files include <iostream>."""
files = []
pattern = input_api.re.compile(r'^#include\s*<iostream>',
input_api.re.MULTILINE)
for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
if not f.LocalPath().endswith('.h'):
continue
contents = input_api.ReadFile(f)
if pattern.search(contents):
files.append(f)
if len(files):
return [ output_api.PresubmitError(
'Do not #include <iostream> in header files, since it inserts static '
'initialization into every file including the header. Instead, '
'#include <ostream>. See http://crbug.com/94794',
files) ]
return []
def _CheckNoUNIT_TESTInSourceFiles(input_api, output_api):
"""Checks to make sure no source files use UNIT_TEST"""
problems = []
for f in input_api.AffectedFiles():
if (not f.LocalPath().endswith(('.cc', '.mm'))):
continue
for line_num, line in f.ChangedContents():
if 'UNIT_TEST ' in line or line.endswith('UNIT_TEST'):
problems.append(' %s:%d' % (f.LocalPath(), line_num))
if not problems:
return []
return [output_api.PresubmitPromptWarning('UNIT_TEST is only for headers.\n' +
'\n'.join(problems))]
def _FindHistogramNameInLine(histogram_name, line):
"""Tries to find a histogram name or prefix in a line."""
if not "affected-histogram" in line:
return histogram_name in line
# A histogram_suffixes tag type has an affected-histogram name as a prefix of
# the histogram_name.
if not '"' in line:
return False
histogram_prefix = line.split('\"')[1]
return histogram_prefix in histogram_name
def _CheckUmaHistogramChanges(input_api, output_api):
"""Check that UMA histogram names in touched lines can still be found in other
lines of the patch or in histograms.xml. Note that this check would not catch
the reverse: changes in histograms.xml not matched in the code itself."""
touched_histograms = []
histograms_xml_modifications = []
pattern = input_api.re.compile('UMA_HISTOGRAM.*\("(.*)"')
for f in input_api.AffectedFiles():
# If histograms.xml itself is modified, keep the modified lines for later.
if f.LocalPath().endswith(('histograms.xml')):
histograms_xml_modifications = f.ChangedContents()
continue
if not f.LocalPath().endswith(('cc', 'mm', 'cpp')):
continue
for line_num, line in f.ChangedContents():
found = pattern.search(line)
if found:
touched_histograms.append([found.group(1), f, line_num])
# Search for the touched histogram names in the local modifications to
# histograms.xml, and, if not found, on the base histograms.xml file.
unmatched_histograms = []
for histogram_info in touched_histograms:
histogram_name_found = False
for line_num, line in histograms_xml_modifications:
histogram_name_found = _FindHistogramNameInLine(histogram_info[0], line)
if histogram_name_found:
break
if not histogram_name_found:
unmatched_histograms.append(histogram_info)
histograms_xml_path = 'tools/metrics/histograms/histograms.xml'
problems = []
if unmatched_histograms:
with open(histograms_xml_path) as histograms_xml:
for histogram_name, f, line_num in unmatched_histograms:
histograms_xml.seek(0)
histogram_name_found = False
for line in histograms_xml:
histogram_name_found = _FindHistogramNameInLine(histogram_name, line)
if histogram_name_found:
break
if not histogram_name_found:
problems.append(' [%s:%d] %s' %
(f.LocalPath(), line_num, histogram_name))
if not problems:
return []
return [output_api.PresubmitPromptWarning('Some UMA_HISTOGRAM lines have '
'been modified and the associated histogram name has no match in either '
'%s or the modifications of it:' % (histograms_xml_path), problems)]
def _CheckNoNewWStrings(input_api, output_api):
"""Checks to make sure we don't introduce use of wstrings."""
problems = []
for f in input_api.AffectedFiles():
if (not f.LocalPath().endswith(('.cc', '.h')) or
f.LocalPath().endswith(('test.cc', '_win.cc', '_win.h')) or
'/win/' in f.LocalPath()):
continue
allowWString = False
for line_num, line in f.ChangedContents():
if 'presubmit: allow wstring' in line:
allowWString = True
elif not allowWString and 'wstring' in line:
problems.append(' %s:%d' % (f.LocalPath(), line_num))
allowWString = False
else:
allowWString = False
if not problems:
return []
return [output_api.PresubmitPromptWarning('New code should not use wstrings.'
' If you are calling a cross-platform API that accepts a wstring, '
'fix the API.\n' +
'\n'.join(problems))]
def _CheckNoDEPSGIT(input_api, output_api):
"""Make sure .DEPS.git is never modified manually."""
if any(f.LocalPath().endswith('.DEPS.git') for f in
input_api.AffectedFiles()):
return [output_api.PresubmitError(
'Never commit changes to .DEPS.git. This file is maintained by an\n'
'automated system based on what\'s in DEPS and your changes will be\n'
'overwritten.\n'
'See https://sites.google.com/a/chromium.org/dev/developers/how-tos/get-the-code#Rolling_DEPS\n'
'for more information')]
return []
def _CheckValidHostsInDEPS(input_api, output_api):
"""Checks that DEPS file deps are from allowed_hosts."""
# Run only if DEPS file has been modified to annoy fewer bystanders.
if all(f.LocalPath() != 'DEPS' for f in input_api.AffectedFiles()):
return []
# Outsource work to gclient verify
try:
input_api.subprocess.check_output(['gclient', 'verify'])
return []
except input_api.subprocess.CalledProcessError, error:
return [output_api.PresubmitError(
'DEPS file must have only git dependencies.',
long_text=error.output)]
def _CheckNoBannedFunctions(input_api, output_api):
"""Make sure that banned functions are not used."""
warnings = []
errors = []
file_filter = lambda f: f.LocalPath().endswith(('.mm', '.m', '.h'))
for f in input_api.AffectedFiles(file_filter=file_filter):
for line_num, line in f.ChangedContents():
for func_name, message, error in _BANNED_OBJC_FUNCTIONS:
matched = False
if func_name[0:1] == '/':
regex = func_name[1:]
if input_api.re.search(regex, line):
matched = True
elif func_name in line:
matched = True
if matched:
problems = warnings;
if error:
problems = errors;
problems.append(' %s:%d:' % (f.LocalPath(), line_num))
for message_line in message:
problems.append(' %s' % message_line)
file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm', '.h'))
for f in input_api.AffectedFiles(file_filter=file_filter):
for line_num, line in f.ChangedContents():
for func_name, message, error, excluded_paths in _BANNED_CPP_FUNCTIONS:
def IsBlacklisted(affected_file, blacklist):
local_path = affected_file.LocalPath()
for item in blacklist:
if input_api.re.match(item, local_path):
return True
return False
if IsBlacklisted(f, excluded_paths):
continue
matched = False
if func_name[0:1] == '/':
regex = func_name[1:]
if input_api.re.search(regex, line):
matched = True
elif func_name in line:
matched = True
if matched:
problems = warnings;
if error:
problems = errors;
problems.append(' %s:%d:' % (f.LocalPath(), line_num))
for message_line in message:
problems.append(' %s' % message_line)
result = []
if (warnings):
result.append(output_api.PresubmitPromptWarning(
'Banned functions were used.\n' + '\n'.join(warnings)))
if (errors):
result.append(output_api.PresubmitError(
'Banned functions were used.\n' + '\n'.join(errors)))
return result
def _CheckNoPragmaOnce(input_api, output_api):
"""Make sure that banned functions are not used."""
files = []
pattern = input_api.re.compile(r'^#pragma\s+once',
input_api.re.MULTILINE)
for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
if not f.LocalPath().endswith('.h'):
continue
contents = input_api.ReadFile(f)
if pattern.search(contents):
files.append(f)
if files:
return [output_api.PresubmitError(
'Do not use #pragma once in header files.\n'
'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
files)]
return []
def _CheckNoTrinaryTrueFalse(input_api, output_api):
"""Checks to make sure we don't introduce use of foo ? true : false."""
problems = []
pattern = input_api.re.compile(r'\?\s*(true|false)\s*:\s*(true|false)')
for f in input_api.AffectedFiles():
if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
continue
for line_num, line in f.ChangedContents():
if pattern.match(line):
problems.append(' %s:%d' % (f.LocalPath(), line_num))
if not problems:
return []
return [output_api.PresubmitPromptWarning(
'Please consider avoiding the "? true : false" pattern if possible.\n' +
'\n'.join(problems))]
def _CheckUnwantedDependencies(input_api, output_api):
"""Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning.
"""
import sys
# We need to wait until we have an input_api object and use this
# roundabout construct to import checkdeps because this file is
# eval-ed and thus doesn't have __file__.
original_sys_path = sys.path
try:
sys.path = sys.path + [input_api.os_path.join(
input_api.PresubmitLocalPath(), 'buildtools', 'checkdeps')]
import checkdeps
from cpp_checker import CppChecker
from rules import Rule
finally:
# Restore sys.path to what it was before.
sys.path = original_sys_path
added_includes = []
for f in input_api.AffectedFiles():
if not CppChecker.IsCppFile(f.LocalPath()):
continue
changed_lines = [line for line_num, line in f.ChangedContents()]
added_includes.append([f.LocalPath(), changed_lines])
deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
error_descriptions = []
warning_descriptions = []
for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
added_includes):
description_with_path = '%s\n %s' % (path, rule_description)
if rule_type == Rule.DISALLOW:
error_descriptions.append(description_with_path)
else:
warning_descriptions.append(description_with_path)
results = []
if error_descriptions:
results.append(output_api.PresubmitError(
'You added one or more #includes that violate checkdeps rules.',
error_descriptions))
if warning_descriptions:
results.append(output_api.PresubmitPromptOrNotify(
'You added one or more #includes of files that are temporarily\n'
'allowed but being removed. Can you avoid introducing the\n'
'#include? See relevant DEPS file(s) for details and contacts.',
warning_descriptions))
return results
def _CheckFilePermissions(input_api, output_api):
"""Check that all files have their permissions properly set."""
if input_api.platform == 'win32':
return []
args = [input_api.python_executable, 'tools/checkperms/checkperms.py',
'--root', input_api.change.RepositoryRoot()]
for f in input_api.AffectedFiles():
args += ['--file', f.LocalPath()]
checkperms = input_api.subprocess.Popen(args,
stdout=input_api.subprocess.PIPE)
errors = checkperms.communicate()[0].strip()
if errors:
return [output_api.PresubmitError('checkperms.py failed.',
errors.splitlines())]
return []
def _CheckNoAuraWindowPropertyHInHeaders(input_api, output_api):
"""Makes sure we don't include ui/aura/window_property.h
in header files.
"""
pattern = input_api.re.compile(r'^#include\s*"ui/aura/window_property.h"')
errors = []
for f in input_api.AffectedFiles():
if not f.LocalPath().endswith('.h'):
continue
for line_num, line in f.ChangedContents():
if pattern.match(line):
errors.append(' %s:%d' % (f.LocalPath(), line_num))
results = []
if errors:
results.append(output_api.PresubmitError(
'Header files should not include ui/aura/window_property.h', errors))
return results
def _CheckIncludeOrderForScope(scope, input_api, file_path, changed_linenums):
"""Checks that the lines in scope occur in the right order.
1. C system files in alphabetical order
2. C++ system files in alphabetical order
3. Project's .h files
"""
c_system_include_pattern = input_api.re.compile(r'\s*#include <.*\.h>')
cpp_system_include_pattern = input_api.re.compile(r'\s*#include <.*>')
custom_include_pattern = input_api.re.compile(r'\s*#include ".*')
C_SYSTEM_INCLUDES, CPP_SYSTEM_INCLUDES, CUSTOM_INCLUDES = range(3)
state = C_SYSTEM_INCLUDES
previous_line = ''
previous_line_num = 0
problem_linenums = []
out_of_order = " - line belongs before previous line"
for line_num, line in scope:
if c_system_include_pattern.match(line):
if state != C_SYSTEM_INCLUDES:
problem_linenums.append((line_num, previous_line_num,
" - C system include file in wrong block"))
elif previous_line and previous_line > line:
problem_linenums.append((line_num, previous_line_num,
out_of_order))
elif cpp_system_include_pattern.match(line):
if state == C_SYSTEM_INCLUDES:
state = CPP_SYSTEM_INCLUDES
elif state == CUSTOM_INCLUDES:
problem_linenums.append((line_num, previous_line_num,
" - c++ system include file in wrong block"))
elif previous_line and previous_line > line:
problem_linenums.append((line_num, previous_line_num, out_of_order))
elif custom_include_pattern.match(line):
if state != CUSTOM_INCLUDES:
state = CUSTOM_INCLUDES
elif previous_line and previous_line > line:
problem_linenums.append((line_num, previous_line_num, out_of_order))
else:
problem_linenums.append((line_num, previous_line_num,
"Unknown include type"))
previous_line = line
previous_line_num = line_num
warnings = []
for (line_num, previous_line_num, failure_type) in problem_linenums:
if line_num in changed_linenums or previous_line_num in changed_linenums:
warnings.append(' %s:%d:%s' % (file_path, line_num, failure_type))
return warnings
def _CheckIncludeOrderInFile(input_api, f, changed_linenums):
"""Checks the #include order for the given file f."""
system_include_pattern = input_api.re.compile(r'\s*#include \<.*')
# Exclude the following includes from the check:
# 1) #include <.../...>, e.g., <sys/...> includes often need to appear in a
# specific order.
# 2) <atlbase.h>, "build/build_config.h"
excluded_include_pattern = input_api.re.compile(
r'\s*#include (\<.*/.*|\<atlbase\.h\>|"build/build_config.h")')
custom_include_pattern = input_api.re.compile(r'\s*#include "(?P<FILE>.*)"')
# Match the final or penultimate token if it is xxxtest so we can ignore it
# when considering the special first include.
test_file_tag_pattern = input_api.re.compile(
r'_[a-z]+test(?=(_[a-zA-Z0-9]+)?\.)')
if_pattern = input_api.re.compile(
r'\s*#\s*(if|elif|else|endif|define|undef).*')
# Some files need specialized order of includes; exclude such files from this
# check.
uncheckable_includes_pattern = input_api.re.compile(
r'\s*#include '
'("ipc/.*macros\.h"|<windows\.h>|".*gl.*autogen.h")\s*')
contents = f.NewContents()
warnings = []
line_num = 0
# Handle the special first include. If the first include file is
# some/path/file.h, the corresponding including file can be some/path/file.cc,
# some/other/path/file.cc, some/path/file_platform.cc, some/path/file-suffix.h
# etc. It's also possible that no special first include exists.
# If the included file is some/path/file_platform.h the including file could
# also be some/path/file_xxxtest_platform.h.
including_file_base_name = test_file_tag_pattern.sub(
'', input_api.os_path.basename(f.LocalPath()))
for line in contents:
line_num += 1
if system_include_pattern.match(line):
# No special first include -> process the line again along with normal
# includes.
line_num -= 1
break
match = custom_include_pattern.match(line)
if match:
match_dict = match.groupdict()
header_basename = test_file_tag_pattern.sub(
'', input_api.os_path.basename(match_dict['FILE'])).replace('.h', '')
if header_basename not in including_file_base_name:
# No special first include -> process the line again along with normal
# includes.
line_num -= 1
break
# Split into scopes: Each region between #if and #endif is its own scope.
scopes = []
current_scope = []
for line in contents[line_num:]:
line_num += 1
if uncheckable_includes_pattern.match(line):
continue
if if_pattern.match(line):
scopes.append(current_scope)
current_scope = []
elif ((system_include_pattern.match(line) or
custom_include_pattern.match(line)) and
not excluded_include_pattern.match(line)):
current_scope.append((line_num, line))
scopes.append(current_scope)
for scope in scopes:
warnings.extend(_CheckIncludeOrderForScope(scope, input_api, f.LocalPath(),
changed_linenums))
return warnings
def _CheckIncludeOrder(input_api, output_api):
"""Checks that the #include order is correct.
1. The corresponding header for source files.
2. C system files in alphabetical order
3. C++ system files in alphabetical order
4. Project's .h files in alphabetical order
Each region separated by #if, #elif, #else, #endif, #define and #undef follows
these rules separately.
"""
def FileFilterIncludeOrder(affected_file):
black_list = (_EXCLUDED_PATHS + input_api.DEFAULT_BLACK_LIST)
return input_api.FilterSourceFile(affected_file, black_list=black_list)
warnings = []
for f in input_api.AffectedFiles(file_filter=FileFilterIncludeOrder):
if f.LocalPath().endswith(('.cc', '.h', '.mm')):
changed_linenums = set(line_num for line_num, _ in f.ChangedContents())
warnings.extend(_CheckIncludeOrderInFile(input_api, f, changed_linenums))
results = []
if warnings:
results.append(output_api.PresubmitPromptOrNotify(_INCLUDE_ORDER_WARNING,
warnings))
return results
def _CheckForVersionControlConflictsInFile(input_api, f):
pattern = input_api.re.compile('^(?:<<<<<<<|>>>>>>>) |^=======$')
errors = []
for line_num, line in f.ChangedContents():
if f.LocalPath().endswith('.md'):
# First-level headers in markdown look a lot like version control
# conflict markers. http://daringfireball.net/projects/markdown/basics
continue
if pattern.match(line):
errors.append(' %s:%d %s' % (f.LocalPath(), line_num, line))
return errors
def _CheckForVersionControlConflicts(input_api, output_api):
"""Usually this is not intentional and will cause a compile failure."""
errors = []
for f in input_api.AffectedFiles():
errors.extend(_CheckForVersionControlConflictsInFile(input_api, f))
results = []
if errors:
results.append(output_api.PresubmitError(
'Version control conflict markers found, please resolve.', errors))
return results
def _CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api):
def FilterFile(affected_file):
"""Filter function for use with input_api.AffectedSourceFiles,
below. This filters out everything except non-test files from
top-level directories that generally speaking should not hard-code
service URLs (e.g. src/android_webview/, src/content/ and others).
"""
return input_api.FilterSourceFile(
affected_file,
white_list=(r'^(android_webview|base|content|net)[\\\/].*', ),
black_list=(_EXCLUDED_PATHS +
_TEST_CODE_EXCLUDED_PATHS +
input_api.DEFAULT_BLACK_LIST))
base_pattern = '"[^"]*google\.com[^"]*"'
comment_pattern = input_api.re.compile('//.*%s' % base_pattern)
pattern = input_api.re.compile(base_pattern)
problems = [] # items are (filename, line_number, line)
for f in input_api.AffectedSourceFiles(FilterFile):
for line_num, line in f.ChangedContents():
if not comment_pattern.search(line) and pattern.search(line):
problems.append((f.LocalPath(), line_num, line))
if problems:
return [output_api.PresubmitPromptOrNotify(
'Most layers below src/chrome/ should not hardcode service URLs.\n'
'Are you sure this is correct?',
[' %s:%d: %s' % (
problem[0], problem[1], problem[2]) for problem in problems])]
else:
return []
def _CheckNoAbbreviationInPngFileName(input_api, output_api):
"""Makes sure there are no abbreviations in the name of PNG files.
The native_client_sdk directory is excluded because it has auto-generated PNG
files for documentation.
"""
errors = []
white_list = (r'.*_[a-z]_.*\.png$|.*_[a-z]\.png$',)
black_list = (r'^native_client_sdk[\\\/]',)
file_filter = lambda f: input_api.FilterSourceFile(
f, white_list=white_list, black_list=black_list)
for f in input_api.AffectedFiles(include_deletes=False,
file_filter=file_filter):
errors.append(' %s' % f.LocalPath())
results = []
if errors:
results.append(output_api.PresubmitError(
'The name of PNG files should not have abbreviations. \n'
'Use _hover.png, _center.png, instead of _h.png, _c.png.\n'
'Contact oshima@chromium.org if you have questions.', errors))
return results
def _FilesToCheckForIncomingDeps(re, changed_lines):
"""Helper method for _CheckAddedDepsHaveTargetApprovals. Returns
a set of DEPS entries that we should look up.
For a directory (rather than a specific filename) we fake a path to
a specific filename by adding /DEPS. This is chosen as a file that
will seldom or never be subject to per-file include_rules.
"""
# We ignore deps entries on auto-generated directories.
AUTO_GENERATED_DIRS = ['grit', 'jni']
# This pattern grabs the path without basename in the first
# parentheses, and the basename (if present) in the second. It
# relies on the simple heuristic that if there is a basename it will
# be a header file ending in ".h".
pattern = re.compile(
r"""['"]\+([^'"]+?)(/[a-zA-Z0-9_]+\.h)?['"].*""")
results = set()
for changed_line in changed_lines:
m = pattern.match(changed_line)
if m:
path = m.group(1)
if path.split('/')[0] not in AUTO_GENERATED_DIRS:
if m.group(2):
results.add('%s%s' % (path, m.group(2)))
else:
results.add('%s/DEPS' % path)
return results
def _CheckAddedDepsHaveTargetApprovals(input_api, output_api):
"""When a dependency prefixed with + is added to a DEPS file, we
want to make sure that the change is reviewed by an OWNER of the
target file or directory, to avoid layering violations from being
introduced. This check verifies that this happens.
"""
changed_lines = set()
for f in input_api.AffectedFiles():
filename = input_api.os_path.basename(f.LocalPath())
if filename == 'DEPS':
changed_lines |= set(line.strip()
for line_num, line
in f.ChangedContents())
if not changed_lines:
return []
virtual_depended_on_files = _FilesToCheckForIncomingDeps(input_api.re,
changed_lines)
if not virtual_depended_on_files:
return []
if input_api.is_committing:
if input_api.tbr:
return [output_api.PresubmitNotifyResult(
'--tbr was specified, skipping OWNERS check for DEPS additions')]
if not input_api.change.issue:
return [output_api.PresubmitError(
"DEPS approval by OWNERS check failed: this change has "
"no Rietveld issue number, so we can't check it for approvals.")]
output = output_api.PresubmitError
else:
output = output_api.PresubmitNotifyResult
owners_db = input_api.owners_db
owner_email, reviewers = input_api.canned_checks._RietveldOwnerAndReviewers(
input_api,
owners_db.email_regexp,
approval_needed=input_api.is_committing)
owner_email = owner_email or input_api.change.author_email
reviewers_plus_owner = set(reviewers)
if owner_email:
reviewers_plus_owner.add(owner_email)
missing_files = owners_db.files_not_covered_by(virtual_depended_on_files,
reviewers_plus_owner)
# We strip the /DEPS part that was added by
# _FilesToCheckForIncomingDeps to fake a path to a file in a
# directory.
def StripDeps(path):
start_deps = path.rfind('/DEPS')
if start_deps != -1:
return path[:start_deps]
else:
return path
unapproved_dependencies = ["'+%s'," % StripDeps(path)
for path in missing_files]
if unapproved_dependencies:
output_list = [
output('Missing LGTM from OWNERS of dependencies added to DEPS:\n %s' %
'\n '.join(sorted(unapproved_dependencies)))]
if not input_api.is_committing:
suggested_owners = owners_db.reviewers_for(missing_files, owner_email)
output_list.append(output(
'Suggested missing target path OWNERS:\n %s' %
'\n '.join(suggested_owners or [])))
return output_list
return []
def _CheckSpamLogging(input_api, output_api):
file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
black_list = (_EXCLUDED_PATHS +
_TEST_CODE_EXCLUDED_PATHS +
input_api.DEFAULT_BLACK_LIST +
(r"^base[\\\/]logging\.h$",
r"^base[\\\/]logging\.cc$",
r"^chrome[\\\/]app[\\\/]chrome_main_delegate\.cc$",
r"^chrome[\\\/]browser[\\\/]chrome_browser_main\.cc$",
r"^chrome[\\\/]browser[\\\/]ui[\\\/]startup[\\\/]"
r"startup_browser_creator\.cc$",
r"^chrome[\\\/]installer[\\\/]setup[\\\/].*",
r"chrome[\\\/]browser[\\\/]diagnostics[\\\/]" +
r"diagnostics_writer\.cc$",
r"^chrome_elf[\\\/]dll_hash[\\\/]dll_hash_main\.cc$",
r"^chromecast[\\\/]",
r"^cloud_print[\\\/]",
r"^content[\\\/]common[\\\/]gpu[\\\/]client[\\\/]"
r"gl_helper_benchmark\.cc$",
r"^courgette[\\\/]courgette_tool\.cc$",
r"^extensions[\\\/]renderer[\\\/]logging_native_handler\.cc$",
r"^ipc[\\\/]ipc_logging\.cc$",
r"^native_client_sdk[\\\/]",
r"^remoting[\\\/]base[\\\/]logging\.h$",
r"^remoting[\\\/]host[\\\/].*",
r"^sandbox[\\\/]linux[\\\/].*",
r"^tools[\\\/]",
r"^ui[\\\/]aura[\\\/]bench[\\\/]bench_main\.cc$",
r"^storage[\\\/]browser[\\\/]fileapi[\\\/]" +
r"dump_file_system.cc$",))
source_file_filter = lambda x: input_api.FilterSourceFile(
x, white_list=(file_inclusion_pattern,), black_list=black_list)
log_info = []
printf = []
for f in input_api.AffectedSourceFiles(source_file_filter):
contents = input_api.ReadFile(f, 'rb')
if input_api.re.search(r"\bD?LOG\s*\(\s*INFO\s*\)", contents):
log_info.append(f.LocalPath())
elif input_api.re.search(r"\bD?LOG_IF\s*\(\s*INFO\s*,", contents):
log_info.append(f.LocalPath())
if input_api.re.search(r"\bprintf\(", contents):
printf.append(f.LocalPath())
elif input_api.re.search(r"\bfprintf\((stdout|stderr)", contents):
printf.append(f.LocalPath())
if log_info:
return [output_api.PresubmitError(
'These files spam the console log with LOG(INFO):',
items=log_info)]
if printf:
return [output_api.PresubmitError(
'These files spam the console log with printf/fprintf:',
items=printf)]
return []
def _CheckForAnonymousVariables(input_api, output_api):
"""These types are all expected to hold locks while in scope and
so should never be anonymous (which causes them to be immediately
destroyed)."""
they_who_must_be_named = [
'base::AutoLock',
'base::AutoReset',
'base::AutoUnlock',
'SkAutoAlphaRestore',
'SkAutoBitmapShaderInstall',
'SkAutoBlitterChoose',
'SkAutoBounderCommit',
'SkAutoCallProc',
'SkAutoCanvasRestore',
'SkAutoCommentBlock',
'SkAutoDescriptor',
'SkAutoDisableDirectionCheck',
'SkAutoDisableOvalCheck',
'SkAutoFree',
'SkAutoGlyphCache',
'SkAutoHDC',
'SkAutoLockColors',
'SkAutoLockPixels',
'SkAutoMalloc',
'SkAutoMaskFreeImage',
'SkAutoMutexAcquire',
'SkAutoPathBoundsUpdate',
'SkAutoPDFRelease',
'SkAutoRasterClipValidate',
'SkAutoRef',
'SkAutoTime',
'SkAutoTrace',
'SkAutoUnref',
]
anonymous = r'(%s)\s*[({]' % '|'.join(they_who_must_be_named)
# bad: base::AutoLock(lock.get());
# not bad: base::AutoLock lock(lock.get());
bad_pattern = input_api.re.compile(anonymous)
# good: new base::AutoLock(lock.get())
good_pattern = input_api.re.compile(r'\bnew\s*' + anonymous)
errors = []
for f in input_api.AffectedFiles():
if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
continue
for linenum, line in f.ChangedContents():
if bad_pattern.search(line) and not good_pattern.search(line):
errors.append('%s:%d' % (f.LocalPath(), linenum))
if errors:
return [output_api.PresubmitError(
'These lines create anonymous variables that need to be named:',
items=errors)]
return []
def _CheckCygwinShell(input_api, output_api):
source_file_filter = lambda x: input_api.FilterSourceFile(
x, white_list=(r'.+\.(gyp|gypi)$',))
cygwin_shell = []
for f in input_api.AffectedSourceFiles(source_file_filter):
for linenum, line in f.ChangedContents():
if 'msvs_cygwin_shell' in line:
cygwin_shell.append(f.LocalPath())
break
if cygwin_shell:
return [output_api.PresubmitError(
'These files should not use msvs_cygwin_shell (the default is 0):',
items=cygwin_shell)]
return []
def _CheckUserActionUpdate(input_api, output_api):
"""Checks if any new user action has been added."""
if any('actions.xml' == input_api.os_path.basename(f) for f in
input_api.LocalPaths()):
# If actions.xml is already included in the changelist, the PRESUBMIT
# for actions.xml will do a more complete presubmit check.
return []
file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm'))
action_re = r'[^a-zA-Z]UserMetricsAction\("([^"]*)'
current_actions = None
for f in input_api.AffectedFiles(file_filter=file_filter):
for line_num, line in f.ChangedContents():
match = input_api.re.search(action_re, line)
if match:
# Loads contents in tools/metrics/actions/actions.xml to memory. It's
# loaded only once.
if not current_actions:
with open('tools/metrics/actions/actions.xml') as actions_f:
current_actions = actions_f.read()
# Search for the matched user action name in |current_actions|.
for action_name in match.groups():
action = 'name="{0}"'.format(action_name)
if action not in current_actions:
return [output_api.PresubmitPromptWarning(
'File %s line %d: %s is missing in '
'tools/metrics/actions/actions.xml. Please run '
'tools/metrics/actions/extract_actions.py to update.'
% (f.LocalPath(), line_num, action_name))]
return []
def _GetJSONParseError(input_api, filename, eat_comments=True):
try:
contents = input_api.ReadFile(filename)
if eat_comments:
json_comment_eater = input_api.os_path.join(
input_api.PresubmitLocalPath(),
'tools', 'json_comment_eater', 'json_comment_eater.py')
process = input_api.subprocess.Popen(
[input_api.python_executable, json_comment_eater],
stdin=input_api.subprocess.PIPE,
stdout=input_api.subprocess.PIPE,
universal_newlines=True)
(contents, _) = process.communicate(input=contents)
input_api.json.loads(contents)
except ValueError as e:
return e
return None
def _GetIDLParseError(input_api, filename):
try:
contents = input_api.ReadFile(filename)
idl_schema = input_api.os_path.join(
input_api.PresubmitLocalPath(),
'tools', 'json_schema_compiler', 'idl_schema.py')
process = input_api.subprocess.Popen(
[input_api.python_executable, idl_schema],
stdin=input_api.subprocess.PIPE,
stdout=input_api.subprocess.PIPE,
stderr=input_api.subprocess.PIPE,
universal_newlines=True)
(_, error) = process.communicate(input=contents)
return error or None
except ValueError as e:
return e
def _CheckParseErrors(input_api, output_api):
"""Check that IDL and JSON files do not contain syntax errors."""
actions = {
'.idl': _GetIDLParseError,
'.json': _GetJSONParseError,
}
# These paths contain test data and other known invalid JSON files.
excluded_patterns = [
r'test[\\\/]data[\\\/]',
r'^components[\\\/]policy[\\\/]resources[\\\/]policy_templates\.json$',
]
# Most JSON files are preprocessed and support comments, but these do not.
json_no_comments_patterns = [
r'^testing[\\\/]',
]
# Only run IDL checker on files in these directories.
idl_included_patterns = [
r'^chrome[\\\/]common[\\\/]extensions[\\\/]api[\\\/]',
r'^extensions[\\\/]common[\\\/]api[\\\/]',
]
def get_action(affected_file):
filename = affected_file.LocalPath()
return actions.get(input_api.os_path.splitext(filename)[1])
def MatchesFile(patterns, path):
for pattern in patterns:
if input_api.re.search(pattern, path):
return True
return False
def FilterFile(affected_file):
action = get_action(affected_file)
if not action:
return False
path = affected_file.LocalPath()
if MatchesFile(excluded_patterns, path):
return False
if (action == _GetIDLParseError and
not MatchesFile(idl_included_patterns, path)):
return False
return True
results = []
for affected_file in input_api.AffectedFiles(
file_filter=FilterFile, include_deletes=False):
action = get_action(affected_file)
kwargs = {}
if (action == _GetJSONParseError and
MatchesFile(json_no_comments_patterns, affected_file.LocalPath())):
kwargs['eat_comments'] = False
parse_error = action(input_api,
affected_file.AbsoluteLocalPath(),
**kwargs)
if parse_error:
results.append(output_api.PresubmitError('%s could not be parsed: %s' %
(affected_file.LocalPath(), parse_error)))
return results
def _CheckJavaStyle(input_api, output_api):
"""Runs checkstyle on changed java files and returns errors if any exist."""
import sys
original_sys_path = sys.path
try:
sys.path = sys.path + [input_api.os_path.join(
input_api.PresubmitLocalPath(), 'tools', 'android', 'checkstyle')]
import checkstyle
finally:
# Restore sys.path to what it was before.
sys.path = original_sys_path
return checkstyle.RunCheckstyle(
input_api, output_api, 'tools/android/checkstyle/chromium-style-5.0.xml',
black_list=_EXCLUDED_PATHS + input_api.DEFAULT_BLACK_LIST)
def _CheckAndroidCrLogUsage(input_api, output_api):
"""Checks that new logs using org.chromium.base.Log:
- Are using 'TAG' as variable name for the tags (warn)
- Are using the suggested name format for the tags: "cr.<PackageTag>" (warn)
- Are using a tag that is shorter than 23 characters (error)
"""
cr_log_import_pattern = input_api.re.compile(
r'^import org\.chromium\.base\.Log;$', input_api.re.MULTILINE)
class_in_base_pattern = input_api.re.compile(
r'^package org\.chromium\.base;$', input_api.re.MULTILINE)
has_some_log_import_pattern = input_api.re.compile(
r'^import .*\.Log;$', input_api.re.MULTILINE)
# Extract the tag from lines like `Log.d(TAG, "*");` or `Log.d("TAG", "*");`
log_call_pattern = input_api.re.compile(r'^\s*Log\.\w\((?P<tag>\"?\w+\"?)\,')
log_decl_pattern = input_api.re.compile(
r'^\s*private static final String TAG = "(?P<name>(.*)")',
input_api.re.MULTILINE)
log_name_pattern = input_api.re.compile(r'^cr[.\w]*')
REF_MSG = ('See base/android/java/src/org/chromium/base/README_logging.md '
'or contact dgn@chromium.org for more info.')
sources = lambda x: input_api.FilterSourceFile(x, white_list=(r'.*\.java$',))
tag_decl_errors = []
tag_length_errors = []
tag_errors = []
util_log_errors = []
for f in input_api.AffectedSourceFiles(sources):
file_content = input_api.ReadFile(f)
has_modified_logs = False
# Per line checks
if (cr_log_import_pattern.search(file_content) or
(class_in_base_pattern.search(file_content) and
not has_some_log_import_pattern.search(file_content))):
# Checks to run for files using cr log
for line_num, line in f.ChangedContents():
# Check if the new line is doing some logging
match = log_call_pattern.search(line)
if match:
has_modified_logs = True
# Make sure it uses "TAG"
if not match.group('tag') == 'TAG':
tag_errors.append("%s:%d" % (f.LocalPath(), line_num))
else:
# Report non cr Log function calls in changed lines
for line_num, line in f.ChangedContents():
if log_call_pattern.search(line):
util_log_errors.append("%s:%d" % (f.LocalPath(), line_num))
# Per file checks
if has_modified_logs:
# Make sure the tag is using the "cr" prefix and is not too long
match = log_decl_pattern.search(file_content)
tag_name = match.group('name') if match else ''
if not log_name_pattern.search(tag_name ):
tag_decl_errors.append(f.LocalPath())
if len(tag_name) > 23:
tag_length_errors.append(f.LocalPath())
results = []
if tag_decl_errors:
results.append(output_api.PresubmitPromptWarning(
'Please define your tags using the suggested format: .\n'
'"private static final String TAG = "cr.<package tag>".\n' + REF_MSG,
tag_decl_errors))
if tag_length_errors:
results.append(output_api.PresubmitError(
'The tag length is restricted by the system to be at most '
'23 characters.\n' + REF_MSG,
tag_length_errors))
if tag_errors:
results.append(output_api.PresubmitPromptWarning(
'Please use a variable named "TAG" for your log tags.\n' + REF_MSG,
tag_errors))
if util_log_errors:
results.append(output_api.PresubmitPromptWarning(
'Please use org.chromium.base.Log for new logs.\n' + REF_MSG,
util_log_errors))
return results
def _CheckForCopyrightedCode(input_api, output_api):
"""Verifies that newly added code doesn't contain copyrighted material
and is properly licensed under the standard Chromium license.
As there can be false positives, we maintain a whitelist file. This check
also verifies that the whitelist file is up to date.
"""
import sys
original_sys_path = sys.path
try:
sys.path = sys.path + [input_api.os_path.join(
input_api.PresubmitLocalPath(), 'tools')]
from copyright_scanner import copyright_scanner
finally:
# Restore sys.path to what it was before.
sys.path = original_sys_path
return copyright_scanner.ScanAtPresubmit(input_api, output_api)
def _CheckSingletonInHeaders(input_api, output_api):
"""Checks to make sure no header files have |Singleton<|."""
def FileFilter(affected_file):
# It's ok for base/memory/singleton.h to have |Singleton<|.
black_list = (_EXCLUDED_PATHS +
input_api.DEFAULT_BLACK_LIST +
(r"^base[\\\/]memory[\\\/]singleton\.h$",))
return input_api.FilterSourceFile(affected_file, black_list=black_list)
pattern = input_api.re.compile(r'(?<!class\s)Singleton\s*<')
files = []
for f in input_api.AffectedSourceFiles(FileFilter):
if (f.LocalPath().endswith('.h') or f.LocalPath().endswith('.hxx') or
f.LocalPath().endswith('.hpp') or f.LocalPath().endswith('.inl')):
contents = input_api.ReadFile(f)
for line in contents.splitlines(False):
if (not input_api.re.match(r'//', line) and # Strip C++ comment.
pattern.search(line)):
files.append(f)
break
if files:
return [ output_api.PresubmitError(
'Found Singleton<T> in the following header files.\n' +
'Please move them to an appropriate source file so that the ' +
'template gets instantiated in a single compilation unit.',
files) ]
return []
_DEPRECATED_CSS = [
# Values
( "-webkit-box", "flex" ),
( "-webkit-inline-box", "inline-flex" ),
( "-webkit-flex", "flex" ),
( "-webkit-inline-flex", "inline-flex" ),
( "-webkit-min-content", "min-content" ),
( "-webkit-max-content", "max-content" ),
# Properties
( "-webkit-background-clip", "background-clip" ),
( "-webkit-background-origin", "background-origin" ),
( "-webkit-background-size", "background-size" ),
( "-webkit-box-shadow", "box-shadow" ),
# Functions
( "-webkit-gradient", "gradient" ),
( "-webkit-repeating-gradient", "repeating-gradient" ),
( "-webkit-linear-gradient", "linear-gradient" ),
( "-webkit-repeating-linear-gradient", "repeating-linear-gradient" ),
( "-webkit-radial-gradient", "radial-gradient" ),
( "-webkit-repeating-radial-gradient", "repeating-radial-gradient" ),
]
def _CheckNoDeprecatedCSS(input_api, output_api):
""" Make sure that we don't use deprecated CSS
properties, functions or values. Our external
documentation and iOS CSS for dom distiller
(reader mode) are ignored by the hooks as it
needs to be consumed by WebKit. """
results = []
file_inclusion_pattern = (r".+\.css$",)
black_list = (_EXCLUDED_PATHS +
_TEST_CODE_EXCLUDED_PATHS +
input_api.DEFAULT_BLACK_LIST +
(r"^chrome/common/extensions/docs",
r"^chrome/docs",
r"^components/dom_distiller/core/css/distilledpage_ios.css",
r"^native_client_sdk"))
file_filter = lambda f: input_api.FilterSourceFile(
f, white_list=file_inclusion_pattern, black_list=black_list)
for fpath in input_api.AffectedFiles(file_filter=file_filter):
for line_num, line in fpath.ChangedContents():
for (deprecated_value, value) in _DEPRECATED_CSS:
if deprecated_value in line:
results.append(output_api.PresubmitError(
"%s:%d: Use of deprecated CSS %s, use %s instead" %
(fpath.LocalPath(), line_num, deprecated_value, value)))
return results
_DEPRECATED_JS = [
( "__lookupGetter__", "Object.getOwnPropertyDescriptor" ),
( "__defineGetter__", "Object.defineProperty" ),
( "__defineSetter__", "Object.defineProperty" ),
]
def _CheckNoDeprecatedJS(input_api, output_api):
"""Make sure that we don't use deprecated JS in Chrome code."""
results = []
file_inclusion_pattern = (r".+\.js$",) # TODO(dbeam): .html?
black_list = (_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
input_api.DEFAULT_BLACK_LIST)
file_filter = lambda f: input_api.FilterSourceFile(
f, white_list=file_inclusion_pattern, black_list=black_list)
for fpath in input_api.AffectedFiles(file_filter=file_filter):
for lnum, line in fpath.ChangedContents():
for (deprecated, replacement) in _DEPRECATED_JS:
if deprecated in line:
results.append(output_api.PresubmitError(
"%s:%d: Use of deprecated JS %s, use %s instead" %
(fpath.LocalPath(), lnum, deprecated, replacement)))
return results
def _AndroidSpecificOnUploadChecks(input_api, output_api):
"""Groups checks that target android code."""
results = []
results.extend(_CheckAndroidCrLogUsage(input_api, output_api))
return results
def _CommonChecks(input_api, output_api):
"""Checks common to both upload and commit."""
results = []
results.extend(input_api.canned_checks.PanProjectChecks(
input_api, output_api,
excluded_paths=_EXCLUDED_PATHS + _TESTRUNNER_PATHS))
results.extend(_CheckAuthorizedAuthor(input_api, output_api))
results.extend(
_CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
results.extend(_CheckNoIOStreamInHeaders(input_api, output_api))
results.extend(_CheckNoUNIT_TESTInSourceFiles(input_api, output_api))
results.extend(_CheckNoNewWStrings(input_api, output_api))
results.extend(_CheckNoDEPSGIT(input_api, output_api))
results.extend(_CheckNoBannedFunctions(input_api, output_api))
results.extend(_CheckNoPragmaOnce(input_api, output_api))
results.extend(_CheckNoTrinaryTrueFalse(input_api, output_api))
results.extend(_CheckUnwantedDependencies(input_api, output_api))
results.extend(_CheckFilePermissions(input_api, output_api))
results.extend(_CheckNoAuraWindowPropertyHInHeaders(input_api, output_api))
results.extend(_CheckIncludeOrder(input_api, output_api))
results.extend(_CheckForVersionControlConflicts(input_api, output_api))
results.extend(_CheckPatchFiles(input_api, output_api))
results.extend(_CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api))
results.extend(_CheckNoAbbreviationInPngFileName(input_api, output_api))
results.extend(_CheckForInvalidOSMacros(input_api, output_api))
results.extend(_CheckForInvalidIfDefinedMacros(input_api, output_api))
# TODO(danakj): Remove this when base/move.h is removed.
results.extend(_CheckForUsingSideEffectsOfPass(input_api, output_api))
results.extend(_CheckAddedDepsHaveTargetApprovals(input_api, output_api))
results.extend(
input_api.canned_checks.CheckChangeHasNoTabs(
input_api,
output_api,
source_file_filter=lambda x: x.LocalPath().endswith('.grd')))
results.extend(_CheckSpamLogging(input_api, output_api))
results.extend(_CheckForAnonymousVariables(input_api, output_api))
results.extend(_CheckCygwinShell(input_api, output_api))
results.extend(_CheckUserActionUpdate(input_api, output_api))
results.extend(_CheckNoDeprecatedCSS(input_api, output_api))
results.extend(_CheckNoDeprecatedJS(input_api, output_api))
results.extend(_CheckParseErrors(input_api, output_api))
results.extend(_CheckForIPCRules(input_api, output_api))
results.extend(_CheckForCopyrightedCode(input_api, output_api))
results.extend(_CheckForWindowsLineEndings(input_api, output_api))
results.extend(_CheckSingletonInHeaders(input_api, output_api))
if any('PRESUBMIT.py' == f.LocalPath() for f in input_api.AffectedFiles()):
results.extend(input_api.canned_checks.RunUnitTestsInDirectory(
input_api, output_api,
input_api.PresubmitLocalPath(),
whitelist=[r'^PRESUBMIT_test\.py$']))
return results
def _CheckAuthorizedAuthor(input_api, output_api):
"""For non-googler/chromites committers, verify the author's email address is
in AUTHORS.
"""
# TODO(maruel): Add it to input_api?
import fnmatch
author = input_api.change.author_email
if not author:
input_api.logging.info('No author, skipping AUTHOR check')
return []
authors_path = input_api.os_path.join(
input_api.PresubmitLocalPath(), 'AUTHORS')
valid_authors = (
input_api.re.match(r'[^#]+\s+\<(.+?)\>\s*$', line)
for line in open(authors_path))
valid_authors = [item.group(1).lower() for item in valid_authors if item]
if not any(fnmatch.fnmatch(author.lower(), valid) for valid in valid_authors):
input_api.logging.info('Valid authors are %s', ', '.join(valid_authors))
return [output_api.PresubmitPromptWarning(
('%s is not in AUTHORS file. If you are a new contributor, please visit'
'\n'
'http://www.chromium.org/developers/contributing-code and read the '
'"Legal" section\n'
'If you are a chromite, verify the contributor signed the CLA.') %
author)]
return []
def _CheckPatchFiles(input_api, output_api):
problems = [f.LocalPath() for f in input_api.AffectedFiles()
if f.LocalPath().endswith(('.orig', '.rej'))]
if problems:
return [output_api.PresubmitError(
"Don't commit .rej and .orig files.", problems)]
else:
return []
def _DidYouMeanOSMacro(bad_macro):
try:
return {'A': 'OS_ANDROID',
'B': 'OS_BSD',
'C': 'OS_CHROMEOS',
'F': 'OS_FREEBSD',
'L': 'OS_LINUX',
'M': 'OS_MACOSX',
'N': 'OS_NACL',
'O': 'OS_OPENBSD',
'P': 'OS_POSIX',
'S': 'OS_SOLARIS',
'W': 'OS_WIN'}[bad_macro[3].upper()]
except KeyError:
return ''
def _CheckForInvalidOSMacrosInFile(input_api, f):
"""Check for sensible looking, totally invalid OS macros."""
preprocessor_statement = input_api.re.compile(r'^\s*#')
os_macro = input_api.re.compile(r'defined\((OS_[^)]+)\)')
results = []
for lnum, line in f.ChangedContents():
if preprocessor_statement.search(line):
for match in os_macro.finditer(line):
if not match.group(1) in _VALID_OS_MACROS:
good = _DidYouMeanOSMacro(match.group(1))
did_you_mean = ' (did you mean %s?)' % good if good else ''
results.append(' %s:%d %s%s' % (f.LocalPath(),
lnum,
match.group(1),
did_you_mean))
return results
def _CheckForInvalidOSMacros(input_api, output_api):
"""Check all affected files for invalid OS macros."""
bad_macros = []
for f in input_api.AffectedFiles():
if not f.LocalPath().endswith(('.py', '.js', '.html', '.css')):
bad_macros.extend(_CheckForInvalidOSMacrosInFile(input_api, f))
if not bad_macros:
return []
return [output_api.PresubmitError(
'Possibly invalid OS macro[s] found. Please fix your code\n'
'or add your macro to src/PRESUBMIT.py.', bad_macros)]
def _CheckForInvalidIfDefinedMacrosInFile(input_api, f):
"""Check all affected files for invalid "if defined" macros."""
ALWAYS_DEFINED_MACROS = (
"TARGET_CPU_PPC",
"TARGET_CPU_PPC64",
"TARGET_CPU_68K",
"TARGET_CPU_X86",
"TARGET_CPU_ARM",
"TARGET_CPU_MIPS",
"TARGET_CPU_SPARC",
"TARGET_CPU_ALPHA",
"TARGET_IPHONE_SIMULATOR",
"TARGET_OS_EMBEDDED",
"TARGET_OS_IPHONE",
"TARGET_OS_MAC",
"TARGET_OS_UNIX",
"TARGET_OS_WIN32",
)
ifdef_macro = input_api.re.compile(r'^\s*#.*(?:ifdef\s|defined\()([^\s\)]+)')
results = []
for lnum, line in f.ChangedContents():
for match in ifdef_macro.finditer(line):
if match.group(1) in ALWAYS_DEFINED_MACROS:
always_defined = ' %s is always defined. ' % match.group(1)
did_you_mean = 'Did you mean \'#if %s\'?' % match.group(1)
results.append(' %s:%d %s\n\t%s' % (f.LocalPath(),
lnum,
always_defined,
did_you_mean))
return results
def _CheckForInvalidIfDefinedMacros(input_api, output_api):
"""Check all affected files for invalid "if defined" macros."""
bad_macros = []
for f in input_api.AffectedFiles():
if f.LocalPath().endswith(('.h', '.c', '.cc', '.m', '.mm')):
bad_macros.extend(_CheckForInvalidIfDefinedMacrosInFile(input_api, f))
if not bad_macros:
return []
return [output_api.PresubmitError(
'Found ifdef check on always-defined macro[s]. Please fix your code\n'
'or check the list of ALWAYS_DEFINED_MACROS in src/PRESUBMIT.py.',
bad_macros)]
def _CheckForUsingSideEffectsOfPass(input_api, output_api):
"""Check all affected files for using side effects of Pass."""
errors = []
for f in input_api.AffectedFiles():
if f.LocalPath().endswith(('.h', '.c', '.cc', '.m', '.mm')):
for lnum, line in f.ChangedContents():
# Disallow Foo(*my_scoped_thing.Pass()); See crbug.com/418297.
if input_api.re.search(r'\*[a-zA-Z0-9_]+\.Pass\(\)', line):
errors.append(output_api.PresubmitError(
('%s:%d uses *foo.Pass() to delete the contents of scoped_ptr. ' +
'See crbug.com/418297.') % (f.LocalPath(), lnum)))
return errors
def _CheckForIPCRules(input_api, output_api):
"""Check for same IPC rules described in
http://www.chromium.org/Home/chromium-security/education/security-tips-for-ipc
"""
base_pattern = r'IPC_ENUM_TRAITS\('
inclusion_pattern = input_api.re.compile(r'(%s)' % base_pattern)
comment_pattern = input_api.re.compile(r'//.*(%s)' % base_pattern)
problems = []
for f in input_api.AffectedSourceFiles(None):
local_path = f.LocalPath()
if not local_path.endswith('.h'):
continue
for line_number, line in f.ChangedContents():
if inclusion_pattern.search(line) and not comment_pattern.search(line):
problems.append(
'%s:%d\n %s' % (local_path, line_number, line.strip()))
if problems:
return [output_api.PresubmitPromptWarning(
_IPC_ENUM_TRAITS_DEPRECATED, problems)]
else:
return []
def _CheckForWindowsLineEndings(input_api, output_api):
"""Check source code and known ascii text files for Windows style line
endings.
"""
known_text_files = r'.*\.(txt|html|htm|mhtml|py|gyp|gypi|gn|isolate)$'
file_inclusion_pattern = (
known_text_files,
r'.+%s' % _IMPLEMENTATION_EXTENSIONS
)
filter = lambda f: input_api.FilterSourceFile(
f, white_list=file_inclusion_pattern, black_list=None)
files = [f.LocalPath() for f in
input_api.AffectedSourceFiles(filter)]
problems = []
for file in files:
fp = open(file, 'r')
for line in fp:
if line.endswith('\r\n'):
problems.append(file)
break
fp.close()
if problems:
return [output_api.PresubmitPromptWarning('Are you sure that you want '
'these files to contain Windows style line endings?\n' +
'\n'.join(problems))]
return []
def CheckChangeOnUpload(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckValidHostsInDEPS(input_api, output_api))
results.extend(_CheckJavaStyle(input_api, output_api))
results.extend(
input_api.canned_checks.CheckGNFormatted(input_api, output_api))
results.extend(_CheckUmaHistogramChanges(input_api, output_api))
results.extend(_AndroidSpecificOnUploadChecks(input_api, output_api))
return results
def GetTryServerMasterForBot(bot):
"""Returns the Try Server master for the given bot.
It tries to guess the master from the bot name, but may still fail
and return None. There is no longer a default master.
"""
# Potentially ambiguous bot names are listed explicitly.
master_map = {
'chromium_presubmit': 'tryserver.chromium.linux',
'blink_presubmit': 'tryserver.chromium.linux',
'tools_build_presubmit': 'tryserver.chromium.linux',
}
master = master_map.get(bot)
if not master:
if 'linux' in bot or 'android' in bot or 'presubmit' in bot:
master = 'tryserver.chromium.linux'
elif 'win' in bot:
master = 'tryserver.chromium.win'
elif 'mac' in bot or 'ios' in bot:
master = 'tryserver.chromium.mac'
return master
def GetDefaultTryConfigs(bots):
"""Returns a list of ('bot', set(['tests']), filtered by [bots].
"""
builders_and_tests = dict((bot, set(['defaulttests'])) for bot in bots)
# Build up the mapping from tryserver master to bot/test.
out = dict()
for bot, tests in builders_and_tests.iteritems():
out.setdefault(GetTryServerMasterForBot(bot), {})[bot] = tests
return out
def CheckChangeOnCommit(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
# TODO(thestig) temporarily disabled, doesn't work in third_party/
#results.extend(input_api.canned_checks.CheckSvnModifiedDirectories(
# input_api, output_api, sources))
# Make sure the tree is 'open'.
results.extend(input_api.canned_checks.CheckTreeIsOpen(
input_api,
output_api,
json_url='http://chromium-status.appspot.com/current?format=json'))
results.extend(input_api.canned_checks.CheckChangeHasBugField(
input_api, output_api))
results.extend(input_api.canned_checks.CheckChangeHasDescription(
input_api, output_api))
return results
def GetPreferredTryMasters(project, change):
import json
import os.path
import platform
import subprocess
cq_config_path = os.path.join(
change.RepositoryRoot(), 'infra', 'config', 'cq.cfg')
# commit_queue.py below is a script in depot_tools directory, which has a
# 'builders' command to retrieve a list of CQ builders from the CQ config.
is_win = platform.system() == 'Windows'
masters = json.loads(subprocess.check_output(
['commit_queue', 'builders', cq_config_path], shell=is_win))
try_config = {}
for master in masters:
try_config.setdefault(master, {})
for builder in masters[master]:
# Do not trigger presubmit builders, since they're likely to fail
# (e.g. OWNERS checks before finished code review), and we're
# running local presubmit anyway.
if 'presubmit' not in builder:
try_config[master][builder] = ['defaulttests']
return try_config
|
SaschaMester/delicium
|
PRESUBMIT.py
|
Python
|
bsd-3-clause
| 69,588
|
[
"VisIt"
] |
1ff4c03f5fb3e7efb1d706ac78c16e7cc6edd83cee940992a0abcfdc8a685f64
|
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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.
"""
Perform static analysis of test case code modules to determine parameters used by the test.
This should simplify maintenance by further automating the test case managment.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import sys
import imp
import ast
from pycopia import module
def get_ast(modname):
"""Return an AST given a module path name."""
fo, path, (suffix, mode, mtype) = module.find_module(modname)
try:
if mtype == imp.PY_SOURCE:
tree = ast.parse(fo.read(), filename=path, mode='exec')
else:
raise ValueError("{!r} is not a python source code module.".format(modname))
finally:
fo.close()
return tree
class TestmoduleVisitor(ast.NodeVisitor):
def __init__(self, findall=True):
self._classes = {}
self._currentclass = None
self.findall = findall
def visit_ClassDef(self, node):
#print((node.body[0]))
if not self.findall:
pass
self._currentclass = node.name
self._classes[node.name] = []
self.generic_visit(node)
def visit_Assign(self, node):
"""Looking for 'p1 = self.config.get("param1", "default1")'
This is the canonical form of getting test case parameters in a test
implementation. This ends up with an AST looking like:
Assign(targets=[Name(id='p1', ctx=Store())],
value=Call(func=Attribute(value=Attribute(value=Name(id='self',
ctx=Load()), attr='config', ctx=Load()), attr='get', ctx=Load()),
args=[Str(s='param1'), Str(s='default1')], keywords=[], starargs=None, kwargs=None))
"""
if isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Attribute):
try:
if (node.value.func.value.value.id == "self" and
node.value.func.value.attr == "config" and
node.value.func.attr == "get"):
lhs = node.targets[0].id
param = node.value.args[0].s
default = node.value.args[1].s
if self._currentclass is not None:
self._classes.setdefault(self._currentclass, []).append( (lhs, param, default) )
else:
raise ValueError("Didn't see class before config get")
except AttributeError:
return
def find_classes(modname, findall=True):
ast = get_ast(modname)
nv = TestmoduleVisitor(findall)
nv.visit(ast)
return nv._classes
def get_class(cls):
"""Return TestModuleVisitor report from a class instance."""
ast = get_ast(cls.__module__)
nv = TestmoduleVisitor()
nv.visit(ast)
return nv._classes[cls.__name__]
if __name__ == "__main__":
from pycopia import autodebug
modname = "testcases.unittests.QA.core.params"
print(find_classes(modname))
|
kdart/pycopia
|
QA/pycopia/QA/testinspector.py
|
Python
|
apache-2.0
| 3,624
|
[
"VisIt"
] |
84824f72b5ac2eec9fe87366bfe0265d40305a9f201d9a253bd4fd7c13c98153
|
"""
FileCatalogClientBase is a base class for the clients of file catalog-like
services built within the DIRAC framework.
"""
__RCSID__ = "$Id$"
from DIRAC.Core.Base.Client import Client
class FileCatalogClientBase( Client ):
""" Client code to the DIRAC File Catalogue
"""
def __init__( self, url = None, **kwargs ):
""" Constructor function.
"""
super( FileCatalogClientBase, self ).__init__( **kwargs )
if url:
self.serverURL = url
self.available = False
def isOK( self, timeout = 120 ):
""" Check that the service is OK
"""
if not self.available:
rpcClient = self._getRPC( timeout = timeout )
res = rpcClient.isOK()
if not res['OK']:
self.available = False
else:
self.available = True
return S_OK( self.available )
#######################################################################################
# The following methods must be implemented in derived classes
#######################################################################################
def getInterfaceMethods( self ):
""" Get the methods implemented by the File Catalog client
:return tuple: ( read_methods_list, write_methods_list, nolfn_methods_list )
"""
raise AttributeError( "getInterfaceMethods must be implemented in the FC derived class" )
def hasCatalogMethod( self, methodName ):
""" Check of a method with the given name is implemented
:param str methodName: the name of the method to check
:return: boolean Flag True if the method is implemented
"""
raise AttributeError( "hasCatalogMethod must be implemented in the FC derived class" )
|
vmendez/DIRAC
|
Resources/Catalog/FileCatalogClientBase.py
|
Python
|
gpl-3.0
| 1,668
|
[
"DIRAC"
] |
f9249b38874a6d83464157315a9901bcac8e00f677edcfb59c086225c65e5101
|
from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from numpy.polynomial.hermite_e import HermiteE
from scipy.misc import factorial
from scipy.stats import rv_continuous
import scipy.special as special
# TODO:
# * actually solve (31) of Blinnikov & Moessner
# * numerical stability: multiply factorials in logspace?
# * ppf & friends: Cornish & Fisher series, or tabulate/solve
_faa_di_bruno_cache = {
1: [[(1, 1)]],
2: [[(1, 2)], [(2, 1)]],
3: [[(1, 3)], [(2, 1), (1, 1)], [(3, 1)]],
4: [[(1, 4)], [(1, 2), (2, 1)], [(2, 2)], [(3, 1), (1, 1)], [(4, 1)]]}
def _faa_di_bruno_partitions(n):
""" Return all non-negative integer solutions of the diophantine equation::
n*k_n + ... + 2*k_2 + 1*k_1 = n (1)
Parameters
----------
n: int
the r.h.s. of Eq. (1)
Returns
-------
partitions: a list of solutions of (1). Each solution is itself
a list of the form `[(m, k_m), ...]` for non-zero `k_m`.
Notice that the index `m` is 1-based.
Examples:
---------
>>> _faa_di_bruno_partitions(2)
[[(1, 2)], [(2, 1)]]
>>> for p in _faa_di_bruno_partitions(4):
... assert 4 == sum(m * k for (m, k) in p)
"""
if n < 1:
raise ValueError("Expected a positive integer; got %s instead" % n)
try:
return _faa_di_bruno_cache[n]
except KeyError:
# TODO: higher order terms
# solve Eq. (31) from Blinninkov & Moessner here
raise NotImplementedError('Higher order terms not yet implemented.')
def cumulant_from_moments(momt, n):
"""Compute n-th cumulant given moments.
Parameters
----------
momt: array_like
`momt[j]` contains `(j+1)`-th moment.
These can be raw moments around zero, or central moments
(in which case, `momt[0]` == 0).
n: integer
which cumulant to calculate (must be >1)
Returns
-------
kappa: float
n-th cumulant.
"""
if n < 1:
raise ValueError("Expected a positive integer. Got %s instead." % n)
if len(momt) < n:
raise ValueError("%s-th cumulant requires %s moments, "
"only got %s." % (n, n, len(momt)))
kappa = 0.
for p in _faa_di_bruno_partitions(n):
r = sum(k for (m, k) in p)
term = (-1)**(r - 1) * factorial(r - 1)
for (m, k) in p:
term *= np.power(momt[m - 1] / factorial(m), k) / factorial(k)
kappa += term
kappa *= factorial(n)
return kappa
## copied from scipy.stats.distributions to avoid the overhead of
## the public methods
_norm_pdf_C = np.sqrt(2*np.pi)
def _norm_pdf(x):
return np.exp(-x**2/2.0) / _norm_pdf_C
def _norm_cdf(x):
return special.ndtr(x)
def _norm_sf(x):
return special.ndtr(-x)
class ExpandedNormal(rv_continuous):
"""Construct the Edgeworth expansion pdf given cumulants.
Parameters
----------
cum: array_like
`cum[j]` contains `(j+1)`-th cumulant: cum[0] is the mean,
cum[1] is the variance and so on.
Notes
-----
This is actually an asymptotic rather than convergent series, hence
higher orders of the expansion may or may not improve the result.
In a strongly non-Gaussian case, it is possible that the density
becomes negative, especially far out in the tails.
Examples
--------
Construct the 4th order expansion for the chi-square distribution using
the known values of the cumulants:
>>> import matplotlib.pyplot as plt
>>> from scipy import stats
>>> from scipy.misc import factorial
>>> df = 12
>>> chi2_c = [2**(j-1) * factorial(j-1) * df for j in range(1, 5)]
>>> edgw_chi2 = ExpandedNormal(chi2_c, name='edgw_chi2', momtype=0)
Calculate several moments:
>>> m, v = edgw_chi2.stats(moments='mv')
>>> np.allclose([m, v], [df, 2 * df])
True
Plot the density function:
>>> mu, sigma = df, np.sqrt(2*df)
>>> x = np.linspace(mu - 3*sigma, mu + 3*sigma)
>>> fig1 = plt.plot(x, stats.chi2.pdf(x, df=df), 'g-', lw=4, alpha=0.5)
>>> fig2 = plt.plot(x, stats.norm.pdf(x, mu, sigma), 'b--', lw=4, alpha=0.5)
>>> fig3 = plt.plot(x, edgw_chi2.pdf(x), 'r-', lw=2)
>>> plt.show()
References
----------
.. [1] E.A. Cornish and R.A. Fisher, Moments and cumulants in the
specification of distributions, Revue de l'Institut Internat.
de Statistique. 5: 307 (1938), reprinted in
R.A. Fisher, Contributions to Mathematical Statistics. Wiley, 1950.
.. [2] http://en.wikipedia.org/wiki/Edgeworth_series
.. [3] S. Blinnikov and R. Moessner, Expansions for nearly Gaussian
distributions, Astron. Astrophys. Suppl. Ser. 130, 193 (1998)
"""
def __init__(self, cum, name='Edgeworth expanded normal', **kwds):
if len(cum) < 2:
raise ValueError("At least two cumulants are needed.")
self._coef, self._mu, self._sigma = self._compute_coefs_pdf(cum)
self._herm_pdf = HermiteE(self._coef)
if self._coef.size > 2:
self._herm_cdf = HermiteE(-self._coef[1:])
else:
self._herm_cdf = lambda x: 0.
# warn if pdf(x) < 0 for some values of x within 4 sigma
r = np.real_if_close(self._herm_pdf.roots())
r = (r - self._mu) / self._sigma
if r[(np.imag(r) == 0) & (np.abs(r) < 4)].any():
mesg = 'PDF has zeros at %s ' % r
warnings.warn(mesg, RuntimeWarning)
kwds.update({'name': name,
'momtype': 0}) # use pdf, not ppf in self.moment()
super(ExpandedNormal, self).__init__(**kwds)
def _pdf(self, x):
y = (x - self._mu) / self._sigma
return self._herm_pdf(y) * _norm_pdf(y) / self._sigma
def _cdf(self, x):
y = (x - self._mu) / self._sigma
return (_norm_cdf(y) +
self._herm_cdf(y) * _norm_pdf(y))
def _sf(self, x):
y = (x - self._mu) / self._sigma
return (_norm_sf(y) -
self._herm_cdf(y) * _norm_pdf(y))
def _compute_coefs_pdf(self, cum):
# scale cumulants by \sigma
mu, sigma = cum[0], np.sqrt(cum[1])
lam = np.asarray(cum)
for j, l in enumerate(lam):
lam[j] /= cum[1]**j
coef = np.zeros(lam.size * 3 - 5)
coef[0] = 1.
for s in range(lam.size - 2):
for p in _faa_di_bruno_partitions(s+1):
term = sigma**(s+1)
for (m, k) in p:
term *= np.power(lam[m+1] / factorial(m+2), k) / factorial(k)
r = sum(k for (m, k) in p)
coef[s + 1 + 2*r] += term
return coef, mu, sigma
if __name__ == "__main__":
cum =[1, 1, 1, 1]
en = ExpandedNormal(cum)
|
phobson/statsmodels
|
statsmodels/distributions/edgeworth.py
|
Python
|
bsd-3-clause
| 6,840
|
[
"Gaussian"
] |
448a15703a11732e822bbc98e80f3c99a9bc2d80b71a4e44f3b53e966e9c656a
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('visit', '0020_auto_20150505_0334'),
]
operations = [
migrations.CreateModel(
name='ContactAttempt',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('result', models.CharField(max_length=255)),
('date', models.DateField()),
('created', models.DateTimeField(auto_now_add=True)),
('student', models.ForeignKey(related_name='contactattempts', to='visit.Student')),
],
options={
'ordering': ('student',),
},
),
migrations.AlterModelOptions(
name='visit',
options={'ordering': ('staff1', 'date')},
),
]
|
koebbe/homeworks
|
visit/migrations/0021_auto_20150515_0131.py
|
Python
|
mit
| 962
|
[
"VisIt"
] |
0c4de05b3a3530e9cac2151d908275a1a9d574d6fbf24d9b6b76b0512b505a22
|
# -*- coding: utf-8 -*-
# vispy: testskip
# -----------------------------------------------------------------------------
# A Galaxy Simulator based on the density wave theory
# (c) 2012 Ingo Berg
#
# Simulating a Galaxy with the density wave theory
# http://beltoforion.de/galaxy/galaxy_en.html
#
# Python version(c) 2014 Nicolas P.Rougier
# -----------------------------------------------------------------------------
import math
import numpy as np
class Galaxy(object):
""" Galaxy simulation using the density wave theory """
def __init__(self, n=20000):
""" Initialize galaxy """
# Eccentricity of the innermost ellipse
self._inner_eccentricity = 0.8
# Eccentricity of the outermost ellipse
self._outer_eccentricity = 1.0
# Velocity at the innermost core in km/s
self._center_velocity = 30
# Velocity at the core edge in km/s
self._inner_velocity = 200
# Velocity at the edge of the disk in km/s
self._outer_velocity = 300
# Angular offset per parsec
self._angular_offset = 0.019
# Inner core radius
self._core_radius = 6000
# Galaxy radius
self._galaxy_radius = 15000
# The radius after which all density waves must have circular shape
self._distant_radius = 0
# Distribution of stars
self._star_distribution = 0.45
# Angular velocity of the density waves
self._angular_velocity = 0.000001
# Number of stars
self._stars_count = n
# Number of dust particles
self._dust_count = int(self._stars_count * 0.75)
# Number of H-II regions
self._h2_count = 200
# Particles
dtype = [('theta', np.float32, 1),
('velocity', np.float32, 1),
('angle', np.float32, 1),
('m_a', np.float32, 1),
('m_b', np.float32, 1),
('size', np.float32, 1),
('type', np.float32, 1),
('temperature', np.float32, 1),
('brightness', np.float32, 1),
('position', np.float32, 2)]
n = self._stars_count + self._dust_count + 2*self._h2_count
self._particles = np.zeros(n, dtype=dtype)
i0 = 0
i1 = i0 + self._stars_count
self._stars = self._particles[i0:i1]
self._stars['size'] = 3.
self._stars['type'] = 0
i0 = i1
i1 = i0 + self._dust_count
self._dust = self._particles[i0:i1]
self._dust['size'] = 64
self._dust['type'] = 1
i0 = i1
i1 = i0 + self._h2_count
self._h2a = self._particles[i0:i1]
self._h2a['size'] = 0
self._h2a['type'] = 2
i0 = i1
i1 = i0 + self._h2_count
self._h2b = self._particles[i0:i1]
self._h2b['size'] = 0
self._h2b['type'] = 3
def __len__(self):
""" Number of particles """
if self._particles is not None:
return len(self._particles)
return 0
def __getitem__(self, key):
""" x.__getitem__(y) <==> x[y] """
if self._particles is not None:
return self._particles[key]
return None
def reset(self, rad, radCore, deltaAng,
ex1, ex2, sigma, velInner, velOuter):
# Initialize parameters
# ---------------------
self._inner_eccentricity = ex1
self._outer_eccentricity = ex2
self._inner_velocity = velInner
self._outer_velocity = velOuter
self._angular_offset = deltaAng
self._core_radius = radCore
self._galaxy_radius = rad
self._distant_radius = self._galaxy_radius * 2
self.m_sigma = sigma
# Initialize stars
# ----------------
stars = self._stars
R = np.random.normal(0, sigma, len(stars)) * self._galaxy_radius
stars['m_a'] = R
stars['angle'] = 90 - R * self._angular_offset
stars['theta'] = np.random.uniform(0, 360, len(stars))
stars['temperature'] = np.random.uniform(3000, 9000, len(stars))
stars['brightness'] = np.random.uniform(0.05, 0.25, len(stars))
stars['velocity'] = 0.000005
for i in range(len(stars)):
stars['m_b'][i] = R[i] * self.eccentricity(R[i])
# Initialize dust
# ---------------
dust = self._dust
X = np.random.uniform(0, 2*self._galaxy_radius, len(dust))
Y = np.random.uniform(-self._galaxy_radius, self._galaxy_radius,
len(dust))
R = np.sqrt(X*X+Y*Y)
dust['m_a'] = R
dust['angle'] = R * self._angular_offset
dust['theta'] = np.random.uniform(0, 360, len(dust))
dust['velocity'] = 0.000005
dust['temperature'] = 6000 + R/4
dust['brightness'] = np.random.uniform(0.01, 0.02)
for i in range(len(dust)):
dust['m_b'][i] = R[i] * self.eccentricity(R[i])
# Initialise H-II
# ---------------
h2a, h2b = self._h2a, self._h2b
X = np.random.uniform(-self._galaxy_radius, self._galaxy_radius,
len(h2a))
Y = np.random.uniform(-self._galaxy_radius, self._galaxy_radius,
len(h2a))
R = np.sqrt(X*X+Y*Y)
h2a['m_a'] = R
h2b['m_a'] = R + 1000
h2a['angle'] = R * self._angular_offset
h2b['angle'] = h2a['angle']
h2a['theta'] = np.random.uniform(0, 360, len(h2a))
h2b['theta'] = h2a['theta']
h2a['velocity'] = 0.000005
h2b['velocity'] = 0.000005
h2a['temperature'] = np.random.uniform(3000, 9000, len(h2a))
h2b['temperature'] = h2a['temperature']
h2a['brightness'] = np.random.uniform(0.005, 0.010, len(h2a))
h2b['brightness'] = h2a['brightness']
for i in range(len(h2a)):
h2a['m_b'][i] = R[i] * self.eccentricity(R[i])
h2b['m_b'] = h2a['m_b']
def update(self, timestep=100000):
""" Update simulation """
self._particles['theta'] += self._particles['velocity'] * timestep
P = self._particles
a, b = P['m_a'], P['m_b']
theta, beta = P['theta'], -P['angle']
alpha = theta * math.pi / 180.0
cos_alpha = np.cos(alpha)
sin_alpha = np.sin(alpha)
cos_beta = np.cos(beta)
sin_beta = np.sin(beta)
P['position'][:, 0] = a*cos_alpha*cos_beta - b*sin_alpha*sin_beta
P['position'][:, 1] = a*cos_alpha*sin_beta + b*sin_alpha*cos_beta
D = np.sqrt(((self._h2a['position'] -
self._h2b['position'])**2).sum(axis=1))
S = np.maximum(1, ((1000-D)/10) - 50)
self._h2a['size'] = 2.0*S
self._h2b['size'] = S/6.0
def eccentricity(self, r):
# Core region of the galaxy. Innermost part is round
# eccentricity increasing linear to the border of the core.
if r < self._core_radius:
return 1 + (r / self._core_radius) * (self._inner_eccentricity-1)
elif r > self._core_radius and r <= self._galaxy_radius:
a = self._galaxy_radius - self._core_radius
b = self._outer_eccentricity - self._inner_eccentricity
return self._inner_eccentricity + (r - self._core_radius) / a * b
# Eccentricity is slowly reduced to 1.
elif r > self._galaxy_radius and r < self._distant_radius:
a = self._distant_radius - self._galaxy_radius
b = 1 - self._outer_eccentricity
return self._outer_eccentricity + (r - self._galaxy_radius) / a * b
else:
return 1
|
sh4wn/vispy
|
examples/demo/gloo/galaxy/galaxy_simulation.py
|
Python
|
bsd-3-clause
| 7,753
|
[
"Galaxy"
] |
84279caf919b99b745340895c257a1a09aad694218e5e7210725abef2e1a63ad
|
""" Principal Component Analysis
"""
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Olivier Grisel <olivier.grisel@ensta.org>
# Mathieu Blondel <mathieu@mblondel.org>
# Denis A. Engemann <denis-alexander.engemann@inria.fr>
# Michael Eickenberg <michael.eickenberg@inria.fr>
# Giorgio Patrini <giorgio.patrini@anu.edu.au>
#
# License: BSD 3 clause
from math import log, sqrt
import numbers
import numpy as np
from scipy import linalg
from scipy.special import gammaln
from scipy.sparse import issparse
from scipy.sparse.linalg import svds
from .base import _BasePCA
from ..utils import check_random_state
from ..utils import check_array
from ..utils.extmath import fast_logdet, randomized_svd, svd_flip
from ..utils.extmath import stable_cumsum
from ..utils.validation import check_is_fitted
def _assess_dimension_(spectrum, rank, n_samples, n_features):
"""Compute the likelihood of a rank ``rank`` dataset
The dataset is assumed to be embedded in gaussian noise of shape(n,
dimf) having spectrum ``spectrum``.
Parameters
----------
spectrum : array of shape (n)
Data spectrum.
rank : int
Tested rank value.
n_samples : int
Number of samples.
n_features : int
Number of features.
Returns
-------
ll : float,
The log-likelihood
Notes
-----
This implements the method of `Thomas P. Minka:
Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604`
"""
if rank > len(spectrum):
raise ValueError("The tested rank cannot exceed the rank of the"
" dataset")
pu = -rank * log(2.)
for i in range(rank):
pu += (gammaln((n_features - i) / 2.) -
log(np.pi) * (n_features - i) / 2.)
pl = np.sum(np.log(spectrum[:rank]))
pl = -pl * n_samples / 2.
if rank == n_features:
pv = 0
v = 1
else:
v = np.sum(spectrum[rank:]) / (n_features - rank)
pv = -np.log(v) * n_samples * (n_features - rank) / 2.
m = n_features * rank - rank * (rank + 1.) / 2.
pp = log(2. * np.pi) * (m + rank + 1.) / 2.
pa = 0.
spectrum_ = spectrum.copy()
spectrum_[rank:n_features] = v
for i in range(rank):
for j in range(i + 1, len(spectrum)):
pa += log((spectrum[i] - spectrum[j]) *
(1. / spectrum_[j] - 1. / spectrum_[i])) + log(n_samples)
ll = pu + pl + pv + pp - pa / 2. - rank * log(n_samples) / 2.
return ll
def _infer_dimension_(spectrum, n_samples, n_features):
"""Infers the dimension of a dataset of shape (n_samples, n_features)
The dataset is described by its spectrum `spectrum`.
"""
n_spectrum = len(spectrum)
ll = np.empty(n_spectrum)
for rank in range(n_spectrum):
ll[rank] = _assess_dimension_(spectrum, rank, n_samples, n_features)
return ll.argmax()
class PCA(_BasePCA):
"""Principal component analysis (PCA)
Linear dimensionality reduction using Singular Value Decomposition of the
data to project it to a lower dimensional space. The input data is centered
but not scaled for each feature before applying the SVD.
It uses the LAPACK implementation of the full SVD or a randomized truncated
SVD by the method of Halko et al. 2009, depending on the shape of the input
data and the number of components to extract.
It can also use the scipy.sparse.linalg ARPACK implementation of the
truncated SVD.
Notice that this class does not support sparse input. See
:class:`TruncatedSVD` for an alternative with sparse data.
Read more in the :ref:`User Guide <PCA>`.
Parameters
----------
n_components : int, float, None or string
Number of components to keep.
if n_components is not set all components are kept::
n_components == min(n_samples, n_features)
If ``n_components == 'mle'`` and ``svd_solver == 'full'``, Minka's
MLE is used to guess the dimension. Use of ``n_components == 'mle'``
will interpret ``svd_solver == 'auto'`` as ``svd_solver == 'full'``.
If ``0 < n_components < 1`` and ``svd_solver == 'full'``, select the
number of components such that the amount of variance that needs to be
explained is greater than the percentage specified by n_components.
If ``svd_solver == 'arpack'``, the number of components must be
strictly less than the minimum of n_features and n_samples.
Hence, the None case results in::
n_components == min(n_samples, n_features) - 1
copy : bool (default True)
If False, data passed to fit are overwritten and running
fit(X).transform(X) will not yield the expected results,
use fit_transform(X) instead.
whiten : bool, optional (default False)
When True (False by default) the `components_` vectors are multiplied
by the square root of n_samples and then divided by the singular values
to ensure uncorrelated outputs with unit component-wise variances.
Whitening will remove some information from the transformed signal
(the relative variance scales of the components) but can sometime
improve the predictive accuracy of the downstream estimators by
making their data respect some hard-wired assumptions.
svd_solver : string {'auto', 'full', 'arpack', 'randomized'}
auto :
the solver is selected by a default policy based on `X.shape` and
`n_components`: if the input data is larger than 500x500 and the
number of components to extract is lower than 80% of the smallest
dimension of the data, then the more efficient 'randomized'
method is enabled. Otherwise the exact full SVD is computed and
optionally truncated afterwards.
full :
run exact full SVD calling the standard LAPACK solver via
`scipy.linalg.svd` and select the components by postprocessing
arpack :
run SVD truncated to n_components calling ARPACK solver via
`scipy.sparse.linalg.svds`. It requires strictly
0 < n_components < min(X.shape)
randomized :
run randomized SVD by the method of Halko et al.
.. versionadded:: 0.18.0
tol : float >= 0, optional (default .0)
Tolerance for singular values computed by svd_solver == 'arpack'.
.. versionadded:: 0.18.0
iterated_power : int >= 0, or 'auto', (default 'auto')
Number of iterations for the power method computed by
svd_solver == 'randomized'.
.. versionadded:: 0.18.0
random_state : int, RandomState instance or None, optional (default None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`. Used when ``svd_solver`` == 'arpack' or 'randomized'.
.. versionadded:: 0.18.0
Attributes
----------
components_ : array, shape (n_components, n_features)
Principal axes in feature space, representing the directions of
maximum variance in the data. The components are sorted by
``explained_variance_``.
explained_variance_ : array, shape (n_components,)
The amount of variance explained by each of the selected components.
Equal to n_components largest eigenvalues
of the covariance matrix of X.
.. versionadded:: 0.18
explained_variance_ratio_ : array, shape (n_components,)
Percentage of variance explained by each of the selected components.
If ``n_components`` is not set then all components are stored and the
sum of the ratios is equal to 1.0.
singular_values_ : array, shape (n_components,)
The singular values corresponding to each of the selected components.
The singular values are equal to the 2-norms of the ``n_components``
variables in the lower-dimensional space.
.. versionadded:: 0.19
mean_ : array, shape (n_features,)
Per-feature empirical mean, estimated from the training set.
Equal to `X.mean(axis=0)`.
n_components_ : int
The estimated number of components. When n_components is set
to 'mle' or a number between 0 and 1 (with svd_solver == 'full') this
number is estimated from input data. Otherwise it equals the parameter
n_components, or the lesser value of n_features and n_samples
if n_components is None.
n_features_ : int
Number of features in the training data.
n_samples_ : int
Number of samples in the training data.
noise_variance_ : float
The estimated noise covariance following the Probabilistic PCA model
from Tipping and Bishop 1999. See "Pattern Recognition and
Machine Learning" by C. Bishop, 12.2.1 p. 574 or
http://www.miketipping.com/papers/met-mppca.pdf. It is required to
compute the estimated data covariance and score samples.
Equal to the average of (min(n_features, n_samples) - n_components)
smallest eigenvalues of the covariance matrix of X.
References
----------
For n_components == 'mle', this class uses the method of *Minka, T. P.
"Automatic choice of dimensionality for PCA". In NIPS, pp. 598-604*
Implements the probabilistic PCA model from:
Tipping, M. E., and Bishop, C. M. (1999). "Probabilistic principal
component analysis". Journal of the Royal Statistical Society:
Series B (Statistical Methodology), 61(3), 611-622.
via the score and score_samples methods.
See http://www.miketipping.com/papers/met-mppca.pdf
For svd_solver == 'arpack', refer to `scipy.sparse.linalg.svds`.
For svd_solver == 'randomized', see:
*Halko, N., Martinsson, P. G., and Tropp, J. A. (2011).
"Finding structure with randomness: Probabilistic algorithms for
constructing approximate matrix decompositions".
SIAM review, 53(2), 217-288.* and also
*Martinsson, P. G., Rokhlin, V., and Tygert, M. (2011).
"A randomized algorithm for the decomposition of matrices".
Applied and Computational Harmonic Analysis, 30(1), 47-68.*
Examples
--------
>>> import numpy as np
>>> from sklearn.decomposition import PCA
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> pca = PCA(n_components=2)
>>> pca.fit(X)
PCA(n_components=2)
>>> print(pca.explained_variance_ratio_)
[0.9924... 0.0075...]
>>> print(pca.singular_values_)
[6.30061... 0.54980...]
>>> pca = PCA(n_components=2, svd_solver='full')
>>> pca.fit(X)
PCA(n_components=2, svd_solver='full')
>>> print(pca.explained_variance_ratio_)
[0.9924... 0.00755...]
>>> print(pca.singular_values_)
[6.30061... 0.54980...]
>>> pca = PCA(n_components=1, svd_solver='arpack')
>>> pca.fit(X)
PCA(n_components=1, svd_solver='arpack')
>>> print(pca.explained_variance_ratio_)
[0.99244...]
>>> print(pca.singular_values_)
[6.30061...]
See also
--------
KernelPCA
SparsePCA
TruncatedSVD
IncrementalPCA
"""
def __init__(self, n_components=None, copy=True, whiten=False,
svd_solver='auto', tol=0.0, iterated_power='auto',
random_state=None):
self.n_components = n_components
self.copy = copy
self.whiten = whiten
self.svd_solver = svd_solver
self.tol = tol
self.iterated_power = iterated_power
self.random_state = random_state
def fit(self, X, y=None):
"""Fit the model with X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
y : Ignored
Returns
-------
self : object
Returns the instance itself.
"""
self._fit(X)
return self
def fit_transform(self, X, y=None):
"""Fit the model with X and apply the dimensionality reduction on X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
y : Ignored
Returns
-------
X_new : array-like, shape (n_samples, n_components)
"""
U, S, V = self._fit(X)
U = U[:, :self.n_components_]
if self.whiten:
# X_new = X * V / S * sqrt(n_samples) = U * sqrt(n_samples)
U *= sqrt(X.shape[0] - 1)
else:
# X_new = X * V = U * S * V^T * V = U * S
U *= S[:self.n_components_]
return U
def _fit(self, X):
"""Dispatch to the right submethod depending on the chosen solver."""
# Raise an error for sparse input.
# This is more informative than the generic one raised by check_array.
if issparse(X):
raise TypeError('PCA does not support sparse input. See '
'TruncatedSVD for a possible alternative.')
X = check_array(X, dtype=[np.float64, np.float32], ensure_2d=True,
copy=self.copy)
# Handle n_components==None
if self.n_components is None:
if self.svd_solver != 'arpack':
n_components = min(X.shape)
else:
n_components = min(X.shape) - 1
else:
n_components = self.n_components
# Handle svd_solver
self._fit_svd_solver = self.svd_solver
if self._fit_svd_solver == 'auto':
# Small problem or n_components == 'mle', just call full PCA
if max(X.shape) <= 500 or n_components == 'mle':
self._fit_svd_solver = 'full'
elif n_components >= 1 and n_components < .8 * min(X.shape):
self._fit_svd_solver = 'randomized'
# This is also the case of n_components in (0,1)
else:
self._fit_svd_solver = 'full'
# Call different fits for either full or truncated SVD
if self._fit_svd_solver == 'full':
return self._fit_full(X, n_components)
elif self._fit_svd_solver in ['arpack', 'randomized']:
return self._fit_truncated(X, n_components, self._fit_svd_solver)
else:
raise ValueError("Unrecognized svd_solver='{0}'"
"".format(self._fit_svd_solver))
def _fit_full(self, X, n_components):
"""Fit the model by computing full SVD on X"""
n_samples, n_features = X.shape
if n_components == 'mle':
if n_samples < n_features:
raise ValueError("n_components='mle' is only supported "
"if n_samples >= n_features")
elif not 0 <= n_components <= min(n_samples, n_features):
raise ValueError("n_components=%r must be between 0 and "
"min(n_samples, n_features)=%r with "
"svd_solver='full'"
% (n_components, min(n_samples, n_features)))
elif n_components >= 1:
if not isinstance(n_components, numbers.Integral):
raise ValueError("n_components=%r must be of type int "
"when greater than or equal to 1, "
"was of type=%r"
% (n_components, type(n_components)))
# Center data
self.mean_ = np.mean(X, axis=0)
X -= self.mean_
U, S, V = linalg.svd(X, full_matrices=False)
# flip eigenvectors' sign to enforce deterministic output
U, V = svd_flip(U, V)
components_ = V
# Get variance explained by singular values
explained_variance_ = (S ** 2) / (n_samples - 1)
total_var = explained_variance_.sum()
explained_variance_ratio_ = explained_variance_ / total_var
singular_values_ = S.copy() # Store the singular values.
# Postprocess the number of components required
if n_components == 'mle':
n_components = \
_infer_dimension_(explained_variance_, n_samples, n_features)
elif 0 < n_components < 1.0:
# number of components for which the cumulated explained
# variance percentage is superior to the desired threshold
ratio_cumsum = stable_cumsum(explained_variance_ratio_)
n_components = np.searchsorted(ratio_cumsum, n_components) + 1
# Compute noise covariance using Probabilistic PCA model
# The sigma2 maximum likelihood (cf. eq. 12.46)
if n_components < min(n_features, n_samples):
self.noise_variance_ = explained_variance_[n_components:].mean()
else:
self.noise_variance_ = 0.
self.n_samples_, self.n_features_ = n_samples, n_features
self.components_ = components_[:n_components]
self.n_components_ = n_components
self.explained_variance_ = explained_variance_[:n_components]
self.explained_variance_ratio_ = \
explained_variance_ratio_[:n_components]
self.singular_values_ = singular_values_[:n_components]
return U, S, V
def _fit_truncated(self, X, n_components, svd_solver):
"""Fit the model by computing truncated SVD (by ARPACK or randomized)
on X
"""
n_samples, n_features = X.shape
if isinstance(n_components, str):
raise ValueError("n_components=%r cannot be a string "
"with svd_solver='%s'"
% (n_components, svd_solver))
elif not 1 <= n_components <= min(n_samples, n_features):
raise ValueError("n_components=%r must be between 1 and "
"min(n_samples, n_features)=%r with "
"svd_solver='%s'"
% (n_components, min(n_samples, n_features),
svd_solver))
elif not isinstance(n_components, numbers.Integral):
raise ValueError("n_components=%r must be of type int "
"when greater than or equal to 1, was of type=%r"
% (n_components, type(n_components)))
elif svd_solver == 'arpack' and n_components == min(n_samples,
n_features):
raise ValueError("n_components=%r must be strictly less than "
"min(n_samples, n_features)=%r with "
"svd_solver='%s'"
% (n_components, min(n_samples, n_features),
svd_solver))
random_state = check_random_state(self.random_state)
# Center data
self.mean_ = np.mean(X, axis=0)
X -= self.mean_
if svd_solver == 'arpack':
# random init solution, as ARPACK does it internally
v0 = random_state.uniform(-1, 1, size=min(X.shape))
U, S, V = svds(X, k=n_components, tol=self.tol, v0=v0)
# svds doesn't abide by scipy.linalg.svd/randomized_svd
# conventions, so reverse its outputs.
S = S[::-1]
# flip eigenvectors' sign to enforce deterministic output
U, V = svd_flip(U[:, ::-1], V[::-1])
elif svd_solver == 'randomized':
# sign flipping is done inside
U, S, V = randomized_svd(X, n_components=n_components,
n_iter=self.iterated_power,
flip_sign=True,
random_state=random_state)
self.n_samples_, self.n_features_ = n_samples, n_features
self.components_ = V
self.n_components_ = n_components
# Get variance explained by singular values
self.explained_variance_ = (S ** 2) / (n_samples - 1)
total_var = np.var(X, ddof=1, axis=0)
self.explained_variance_ratio_ = \
self.explained_variance_ / total_var.sum()
self.singular_values_ = S.copy() # Store the singular values.
if self.n_components_ < min(n_features, n_samples):
self.noise_variance_ = (total_var.sum() -
self.explained_variance_.sum())
self.noise_variance_ /= min(n_features, n_samples) - n_components
else:
self.noise_variance_ = 0.
return U, S, V
def score_samples(self, X):
"""Return the log-likelihood of each sample.
See. "Pattern Recognition and Machine Learning"
by C. Bishop, 12.2.1 p. 574
or http://www.miketipping.com/papers/met-mppca.pdf
Parameters
----------
X : array, shape(n_samples, n_features)
The data.
Returns
-------
ll : array, shape (n_samples,)
Log-likelihood of each sample under the current model
"""
check_is_fitted(self, 'mean_')
X = check_array(X)
Xr = X - self.mean_
n_features = X.shape[1]
precision = self.get_precision()
log_like = -.5 * (Xr * (np.dot(Xr, precision))).sum(axis=1)
log_like -= .5 * (n_features * log(2. * np.pi) -
fast_logdet(precision))
return log_like
def score(self, X, y=None):
"""Return the average log-likelihood of all samples.
See. "Pattern Recognition and Machine Learning"
by C. Bishop, 12.2.1 p. 574
or http://www.miketipping.com/papers/met-mppca.pdf
Parameters
----------
X : array, shape(n_samples, n_features)
The data.
y : Ignored
Returns
-------
ll : float
Average log-likelihood of the samples under the current model
"""
return np.mean(self.score_samples(X))
|
chrsrds/scikit-learn
|
sklearn/decomposition/pca.py
|
Python
|
bsd-3-clause
| 22,371
|
[
"Gaussian"
] |
152ff6fb41a48efdece58059a615907562c01ea87be8b821822f2295580400ab
|
"""
This module contains information about files present on common Workbench
disks. The data is used when creating a Workbench environment on demand.
Some files are removed because they differ between Cloanto WB floppies and
original WB floppies.
"""
import hashlib
import os
import sys
import traceback
from fsgamesys.amiga.adffile import ADFFile
wb_133_startup_sequence = """\
c:SetPatch >NIL: ;patch system functions
Addbuffers df0: 10
cd c:
echo "A500/A2000 Workbench disk. Release 1.3.3 version 34.34*N"
Sys:System/FastMemFirst ; move C00000 memory to last in list
BindDrivers
SetClock load ;load system time from real time clock (A1000 owners should
;replace the SetClock load with Date
FF >NIL: -0 ;speed up Text
resident CLI L:Shell-Seg SYSTEM pure add; activate Shell
resident c:Execute pure
mount newcon:
;
failat 11
run execute s:StartupII ;This lets resident be used for rest of script
wait >NIL: 5 mins ;wait for StartupII to complete (will signal when done)
;
SYS:System/SetMap usa1 ;Activate the ()/* on keypad
path ram: c: sys:utilities sys:system s: sys:prefs add ;set path for Workbench
LoadWB delay ;wait for inhibit to end before continuing
endcli >NIL:
"""
wb_204_startup_sequence = """\
c:setpatch >NIL:
c:version >NIL:
addbuffers >NIL: df0: 15
Failat 21
Resident >NIL: C:Execute PURE ADD
makedir ram:T ram:Clipboards ram:env ram:env/sys
copy >NIL: ENVARC: ram:env all quiet noreq
assign ENV: ram:env
assign T: ram:t ;set up T: directory for scripts
assign CLIPS: ram:clipboards
assign REXX: s:
if exists sys:Monitors
join >NIL: sys:monitors/~(#?.info) as t:mon-start
execute t:mon-start
delete >NIL: t:mon-start
endif
BindDrivers
setenv Workbench $Workbench
setenv Kickstart $Kickstart
IPrefs
echo "Amiga Release 2. Kickstart $Kickstart, Workbench $Workbench"
conclip
mount speak:
mount aux:
mount pipe:
path ram: c: sys:utilities sys:rexxc sys:system s: sys:prefs sys:wbstartup add
if exists sys:tools
path sys:tools add
if exists sys:tools/commodities
path sys:tools/commodities add
endif
endif
; If this is the initial boot (i.e. keyboard env variable is not set)
; then execute PickMap which will query for a keymap and set the
; keyboard env variable.
;
; if keyboard env variable is set, set the keymap
if ${sys/keyboard} NOT EQ "*${sys/keyboard}"
setmap ${sys/keyboard}
else
PickMap sys: initial
endif
if exists s:user-startup
execute s:user-startup
endif
LoadWB
endcli >NIL:
"""
wb_300_startup_sequence = """\
; $VER: startup-sequence 39.9 (9.8.92)
C:SetPatch QUIET
C:Version >NIL:
C:AddBuffers >NIL: DF0: 15
FailAt 21
C:MakeDir RAM:T RAM:Clipboards RAM:ENV RAM:ENV/Sys
C:Copy >NIL: ENVARC: RAM:ENV ALL NOREQ
Resident >NIL: C:Assign PURE
Resident >NIL: C:Execute PURE
Assign >NIL: ENV: RAM:ENV
Assign >NIL: T: RAM:T
Assign >NIL: CLIPS: RAM:Clipboards
Assign >NIL: REXX: S:
Assign >NIL: PRINTERS: DEVS:Printers
Assign >NIL: KEYMAPS: DEVS:Keymaps
Assign >NIL: LOCALE: SYS:Locale
Assign >NIL: LIBS: SYS:Classes ADD
Assign >NIL: HELP: LOCALE:Help DEFER
IF NOT EXISTS SYS:Fonts
Assign FONTS:
EndIF
BindDrivers
C:Mount >NIL: DEVS:DOSDrivers/~(#?.info)
IF EXISTS DEVS:Monitors
IF EXISTS DEVS:Monitors/VGAOnly
DEVS:Monitors/VGAOnly
EndIF
C:List >NIL: DEVS:Monitors/~(#?.info|VGAOnly) TO T:M LFORMAT "DEVS:Monitors/%s"
Execute T:M
C:Delete >NIL: T:M
EndIF
SetEnv Workbench $Workbench
SetEnv Kickstart $Kickstart
UnSet Workbench
UnSet Kickstart
C:IPrefs
C:ConClip
Path >NIL: RAM: C: SYS:Utilities SYS:Rexxc SYS:System S: SYS:Prefs SYS:WBStartup SYS:Tools SYS:Tools/Commodities
IF EXISTS S:User-Startup
Execute S:User-Startup
EndIF
Resident Execute REMOVE
Resident Assign REMOVE
C:LoadWB
EndCLI >NIL:
"""
# noinspection SpellCheckingInspection
wb_133_files = {
"c/": "",
"c/AddBuffers": "b4935ca3f55fbf53db41a61d32cee48d93d1c431",
"c/Ask": "20156be306fadfe45b8fde83bbc90258f371a00c",
"c/Assign": "52579fe27010466442e928cb2a62cecc20f9f184",
"c/Avail": "9d3d8ff67cfc4d7e220db53268830b0a5b5f0a2b",
"c/Binddrivers": "0f7eaf913a9a8d50af3573a695a8f4af3b8f0ad6",
"c/Break": "7c1cb7e382d36feb70b773b6cfd030ff853057e1",
"c/CD": "9f4c181e7d5e3c0e103f462ba1420570499ca922",
"c/ChangeTaskPri": "f63a5652aacd198b6ee25a2aefa3518a53f14ab6",
"c/Copy": "ef236641b73d0b849f6ceb4a218469ea8f1d06f2",
"c/Date": "287859f1c0fc0f1772c9e9c4f767bd523515b194",
"c/Delete": "d6304c0e704c94073ad67edd19725a4742697ef6",
"c/Dir": "c4c80a92749862fe8fe877dff0d7ab88a824026d",
"c/DiskChange": "37665418b614fb1d768ea85c32a165cfaec146c1",
# "c/DiskDoctor": "c801fbdcc4b04ff492a67cfeaee0036fce70bb85",
"c/Echo": "b43fc80f2fb23af7c3ee14c8e1b5eecfc3c587ee",
# "c/Ed": "dad70eb4a65febb74283c2a189d6bb95b22b0886",
"c/Edit": "d83ee8a2e1f9d1697875366dafc329f8e8e4d7e9",
"c/Else": "8f64d3d3fc7c84e02c4211e68ca74b2fa528df7b",
"c/EndCLI": "24a5167194970a0188c00b234a12d2fba4308478",
"c/EndIf": "7f15af4934c472489f278268667c2788c2a7021b",
"c/EndSkip": "7f15af4934c472489f278268667c2788c2a7021b",
"c/Eval": "5af8c120e9cf1399740dab3eca367af242d015cc",
"c/Execute": "29b7093beae26deab1bd66a98167bfdb96aa7cf7",
"c/Failat": "49918ba167529cef1320452d7442eac73712e0e7",
"c/Fault": "e7f20bbe32843bca9c206cab8be50ae1d77b680f",
# "c/FF": "dc9b9750c2a38546f7be2dbe983ae258f2496b98",
"c/FileNote": "36d14d7468eb136b1179f04fa3c218832638e960",
"c/GetEnv": "be841e3d1794a11b9af1b299ff1d8c9be85d8338",
"c/IconX": "442df04019ae6ff426c3464f8be8c523ad292830",
"c/If": "e0f0c4880f33ab782d903663535812f777362983",
"c/Info": "a22a7a4aa07bad698b725253bd796c6fbdca9eb8",
"c/Install": "1792a60e0564098429838d8db592b6297769d6f9",
"c/Join": "0e8d276bb1f70a52c608cd8c8315ef8e84cceaef",
"c/Lab": "7f15af4934c472489f278268667c2788c2a7021b",
"c/List": "0d5c1cddab2af3e41bfe485e4a8cb76dc99c4bc4",
"c/LoadWB": "13f61f0d60028256cc790f4cef3bcca83fb20259",
"c/Lock": "f8a6d2e97b637c1ac1be97eaf77e3f12c79154ac",
"c/Makedir": "d01c425e8af0f4f4084a6b2ee13780240db4f027",
"c/Mount": "4f18b1c83c0f7a59eaa11c08e7a82cb7941740b3",
"c/NewCLI": "9298e77f0adaa7a789d6e5f9f3035f24e60364d6",
"c/NewShell": "7b827b5fa5456c9e1d722f2611437864be1bfdec",
"c/Path": "770f775d73fdd8df8c1890be2ba2f9fbd388c06b",
"c/Prompt": "5bb558e3f2ed62d5f676e84bc23f70ed913b4412",
"c/Protect": "fec1b09d6a808b0e101ee2ed923a7f0e60597caa",
"c/Quit": "e8f9244859b2e55e5c10304b1ca35e5801265c23",
"c/Relabel": "496bc49e1488e8276e2074063b839269b34d1889",
"c/RemRAD": "bca2dbf0ea2a8885fd976c04d421b884796d070a",
"c/Rename": "b94baf0954756f75272576c7b34cdd6859d896d3",
"c/Resident": "70c21c5a6add12526b29690f8bde0327f91b6f78",
"c/Run": "caf92a05af573c54a1c9044e51ac6aeaab534e23",
"c/Search": "0359aa4849bb1e7f7fa37862a4ab2f34b6d3b6fb",
# "c/SetClock": "95d98f533207f53c1d90ddc57f2815db56d9bba7",
"c/SetDate": "cca8245571bd7ffc4ddd46e87441b2600bf8be74",
"c/SetEnv": "ac8df5ae6adfc7d68e5a3f514b935bd5293b09b7",
"c/SetPatch": "3b36ee49e10626594545c564957fb4882ac2bfc3",
"c/Skip": "15c513c48b568dc77593c13bf593fc6f8e0bcdb8",
"c/Sort": "39f4a8a41ec5ab3cb030be579b49b6a3a7046f5a",
"c/Stack": "d48dc30db5f9d6c7c04259444ba74b7c2f3dffd0",
"c/Status": "08fffe1acc5dec49345e188eaba1f2fa74cd7424",
"c/Type": "afb53409c675bac58048e8e76d403d61e91c1fc9",
"c/Version": "bfa3c28746dc9a56df4569e687d0c7f6bb7e5b80",
"c/Wait": "c893b36bd2376c003e3d2b2f5791d757c5fa33f9",
"c/Which": "d1c3a0b2d9a0bcc3db3580182b75961981e9d38d",
"c/Why": "84d318064b8374399bad8139c5f8f6046aa0b6e0",
"devs/": "",
"devs/clipboard.device": "d1708898f40bdb4f525e615e833e7f109331ac56",
"devs/clipboards/": "",
"devs/keymaps/": "",
"devs/keymaps/usa1": "39d79e8a775260c13df0f657ee20e5f3e742de9e",
"devs/MountList": "b85692e12b2fc7eaa02e4d211b043b5cd6272200",
"devs/narrator.device": "d51631238dc07925b89e57ebe9d2e412400a0384",
"devs/parallel.device": "861b780af555f52088adf5106bb62c05444dba82",
"devs/printer.device": "5f06ec8cd7c32c40d78af95c8953ec527647a861",
"devs/printers/": "",
"devs/printers/generic": "aaaab28025bef46e5c01dde3d01d2f03fc63df2b",
"devs/ramdrive.device": "ca60b73bc779d95cdcf23ec5e92b44dc21b1b472",
"devs/serial.device": "55df2ec0a1d9dc6a03c9335737e23a38b2d73213",
"devs/system-configuration": "f4e0ca14cbfb69c78c491d4cb4253a9a8ba9a78b",
"Empty/": "",
"Expansion/": "",
"fonts/": "",
"fonts/diamond.font": "cfe171bc8ab48615c6ac8fdfc5cd9da098f35e66",
"fonts/diamond/": "",
"fonts/diamond/12": "e6634c30e031dae19428423952f0abbe75d84559",
"fonts/diamond/20": "75cb8014065834d1be7261a265bf0939e95d483a",
"fonts/emerald.font": "98d935aa47ca406384bb6c592c63549f2d43d604",
"fonts/emerald/": "",
"fonts/emerald/17": "359d8c7da2e5ff4c157eed528c8c41a5ea09530a",
"fonts/emerald/20": "de377bd498532ff4d3aa92e60fae8a029e7fc608",
"fonts/garnet.font": "57e054da85337f25d660d2eb983dcf924a44ca4d",
"fonts/garnet/": "",
"fonts/garnet/16": "e99e9fde239b557ba181d91261f84abfda6f8bcb",
"fonts/garnet/9": "5705e5553c85dc2e6573e4420d704e9fca5efe25",
"fonts/opal.font": "dc66cd2d713f027b22539c503c5a5647e1f29fbf",
"fonts/opal/": "",
"fonts/opal/12": "ebb7b174ba5f215172921ec7e8cb3774eb21c90b",
"fonts/opal/9": "0cea9720d43e2280b6fa8583fcefa364b9540446",
"fonts/ruby.font": "314e2c9ca75cb75cadca1038d19a5ab92f2ed656",
"fonts/ruby/": "",
"fonts/ruby/12": "c5b1fd7d3834ebd2a26fc23c42f174451ddea1c7",
"fonts/ruby/15": "58e3f44c65d75c9bff0a9992536c084c2572dbc9",
"fonts/ruby/8": "a09b9ce5bd1c4a68773e6abfccc5218d0ddd066d",
"fonts/sapphire.font": "18f992c2fef46fd408b272f07f9d5598c5e61bcb",
"fonts/sapphire/": "",
"fonts/sapphire/14": "fb0da752206e8b29e94f6e3d68492c2f794c54d5",
"fonts/sapphire/19": "250e989ac01401b10773ad11cf9e45ad83437fe6",
"fonts/topaz.font": "66b2ef88f256216f340a2130920c3dafdc5b3038",
"fonts/topaz/": "",
"fonts/topaz/11": "be925d2d0a61962ff1de9deb742747a356fc2b87",
"l/": "",
"l/Aux-Handler": "2e621414176ce93959e066cacc86f16c70bb7f80",
"l/Disk-Validator": "30ede410472723c95338ed2c870916ad275e9706",
"l/FastFileSystem": "cc14a3ce4805d4e3a0397fe6997ff5428d90ecdf",
"l/Newcon-Handler": "c530e2ce63f2c6203526345fb2d434f2d4a9f49d",
"l/Pipe-Handler": "4e73c34bcf73ab5b590c7b016dc1176673322077",
"l/Port-Handler": "d7e4ddab8cbd94f751a6ffd4bc93cfe07cb4cae2",
"l/Ram-Handler": "c0b036019fbffc46b417a72dd296f8d33b19a308",
"l/Shell-Seg": "4bbe3ccb55fab49c83ff7ab52b2af277e6d92429",
"l/Speak-Handler": "1b3b3dcd0b46cc6dbf98467e319d0d396e7df22f",
"libs/": "",
"libs/diskfont.library": "f1a4d45d97f2df1cff6b83a4392c34cc7ac18bbc",
"libs/icon.library": "4c9b95e6f786f707aa51b2483a9f21ac5e66d7c9",
"libs/info.library": "aa46c186d762dc68d2e799a5d13cad6745b55d10",
"libs/mathieeedoubbas.library": "cf565b2b7a9f6e8aae030e32490346589f90b780",
"libs/mathieeedoubtrans.library": "29f906dc50594aca3a91cfb69bd3f332fdb1671f",
"libs/mathtrans.library": "65bae4aac804fb4db79a427f12b6ef1e16d22882",
"libs/translator.library": "6ddc4462f261317a61f3c371091021b243df562c",
"libs/version.library": "8f062571cac294bf5556b5bdc9d48da2c2f21fae",
"Prefs/": "",
"Prefs/CopyPrefs": "0af96045315193d4ec4f6c40d5ea6c3765d3fb04",
"Prefs/Preferences": "e8b98bbb4cc3a04cf31855d4dcf6c292d02a48b4",
"s/": "",
"s/CLI-Startup": "c9abb720ab20b5976e18c45dd6eee46187b367f9",
"s/DPAT": "bd0ee7066b43ef7df98db2801a75ab4f79f13098",
"s/PCD": "d6ff57db9f9cd193d99aa64581ca964494b5e430",
# "s/Shell-Startup": "25ee071ea6069e7fb10ac23bef1bbb24426b1bf1",
"s/SPAT": "208cd7d832fb8a0d81d45fc3db7bc31c12727b3f",
"s/Startup-Sequence.HD": "0d3caa59e5f867a6f9f8c68d318a16da1bf60fd6",
# "s/StartupII": "dae0c0aeb988f27c5a9a85dcdf502998570b3b45",
"Shell": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
"System/": "",
"System/CLI": "a6e7eb1585e4ebd6f4ed606eb18d8f23af184bea",
"System/Diskcopy": "009cfa0952888c059da450b46d731d7f1779ae63",
"System/FastMemFirst": "5fd51854d5b109fcdbf52809497e642036aa4722",
"System/FixFonts": "3fc2dfbc62326678c3daf9ee860bac6330666999",
# "System/Format": "972bbf474d471bec395d19f6d737908542055d70",
"System/InitPrinter": "6d35a5215846acef053211dfcd6563054b51da10",
"System/MergeMem": "04c018c68442187d292c0a57e1686bc8269f2ac4",
"System/NoFastMem": "87e8c332e69a5446535923157cb6678ccb992614",
"System/SetMap": "6d6c0ca1163c9d921b193d0e3c04722800c8c88d",
"t/": "",
"Trashcan/": "",
"Utilities/": "",
"Utilities/Calculator": "66d0b0fcb4795517c6d30cb96662afce68d81585",
"Utilities/Clock": "ca791b988dd647432dd36dcc519bc5ce7d2e0bd2",
"Utilities/ClockPtr": "47c191dd0edeccbf80cb5402002101bcc791e171",
"Utilities/CMD": "7e0917b6fbf4152fd9167af0eee2118b35d48fe7",
"Utilities/GraphicDump": "b82aa41aa1d602a1e1452d757797dd22b97dc75a",
"Utilities/InstallPrinter": "05f57e5ffc717c7a4eb80bb3917be6006ebdc0b0",
"Utilities/More": "2eb6ab87d1ee9bf28bea826e2481dd3c4f6c1447",
"Utilities/Notepad": "ca9e25cd122dc01a28b66eb8f3ebc3395504e6b7",
"Utilities/PrintFiles": "66d70dae78836d1aa198b9fd46492f204be0459f",
"Utilities/Say": "3f845bf4d06c680c960847115449adb4819cd8b7",
}
# noinspection SpellCheckingInspection
wb_204_files = {
"C/": "",
"C/AddBuffers": "6ed1a3f24a1f605aa7234410faebbfbb3fda3ee6",
"C/Assign": "b5b7edb67f578019d46af425a16458ec0cdb1c2e",
"C/Avail": "5e62c202fe3cb447a19c39efb43c935eed139a66",
"C/BindDrivers": "7534362e5def2eb32819be52f242d28ebdc05a26",
"C/Break": "97ca2404e17fc78e3d988131bb17183c5c3aa15a",
"C/ChangeTaskPri": "66533bb2cee36475b03cd73ae8ab198889e81be3",
"C/ConClip": "96dd0671b40743c18f9ec2b58b2ccb731092e29f",
"C/Copy": "628a17ad2b883565a1312d105a65764076c42013",
"C/CPU": "40bcedc1af7677096cb1e5f5e41e147cf4c952fc",
"C/Date": "0d190c0ce0b99cd653a8f982964eed110ac540eb",
"C/Delete": "0597fd916dd28850ef68bb904937cad0d347cf5a",
"C/Dir": "184eef562670fd6b22b3025e385f992469fa50d4",
"C/DiskChange": "2cae12bfbb1cc98348e7afabf0f48b09cadbaf5e",
"C/DiskDoctor": "c801fbdcc4b04ff492a67cfeaee0036fce70bb85",
"C/Ed": "077483aacde3b40eeeb7b2b08cff3c18d6174e1c",
"C/Edit": "14a1b22e4d72f85cd64b49cfdc8380b294f2da15",
"C/Eval": "fae9792514d07b6fbb5b04d778492941dee5c448",
"C/Execute": "ef1e6f6db0f3a513e0dc98add537e1db87b1856a",
"C/Filenote": "6c263e034a3aca677467d410e410ba808a5f2b8d",
"C/IconX": "9a2088f98175b3341f8bf4831599d54832430c35",
"C/Info": "d12eea32aef864fcb4717ee8447c01d5900c94f1",
"C/Install": "b5e1a2ea287c29390d38e47ccb3749f7c449bd4e",
"C/IPrefs": "f3eb8607aaac99043020f0a9a1156dec4f941a11",
"C/Join": "da8d787eadd16e682216c808cbbd1427acde7280",
"C/List": "74a07847e45f8ae61daa029dd21775f438013a08",
"C/LoadWB": "c705d1579c04505819a6bc3c6c29ae8d2610da66",
"C/Lock": "a671aabf698196baa6a237601d07fb49b7f64f60",
"C/MagTape": "8d14c533f6fb73286a642bb208151c36da3af2c9",
"C/MakeDir": "3e00b210538357ff2ca9f0bc16471f06fb994282",
"C/MakeLink": "da8472a553ece5484d7ba1290884ad5d59db5770",
"C/Mount": "b2f1e59e977cec1c83166977cd4350f5388c3c9f",
"C/Protect": "e95073c0169dd7c7ca39b9842b339a1288ca3016",
"C/Relabel": "056cb6a12033f5638b1353be1007106fd9267a6e",
"C/RemRAD": "7e5d53c865debaa9d752f96ef818320248332ef6",
"C/Rename": "d1cb2ab35c8fa0dc912b98dbcf002c2c3b220988",
"C/Search": "89c1dd049ca2fff58269fd44af2705abdedff112",
"C/SetClock": "0c166dd6f8baa45eda766f3b41a0f799f8e7f388",
"C/SetDate": "d7a78803ade6e09dbbba051ab6d4fbcb923527eb",
"C/SetFont": "8b5bd918009242703f5f8ae9237199bd35ef0efe",
"C/SetPatch": "309db203c5c88d2867d9d6f75e5ef67d2c558a95",
"C/Sort": "d886f81bdc74f4942acb52680e56d8bf50a0be8a",
"C/Status": "71e09cfc79d8ede0721ba4a01e1cd43a6318a99f",
"C/Type": "00917f88e78770f6b28562bede2cf64718325553",
"C/Version": "86dcf19836869c7319a1b89083a0529d1ee0d049",
"C/Wait": "a0d503a136dad028ec51e33cfd57d130c1b4b807",
"C/Which": "22952cce8446a1405b1b22d057ec19614e38c366",
"Devs/": "",
"Devs/clipboard.device": "83f3490b6480a0515b37e6f926ab48daf9cad61e",
"Devs/Keymaps/": "",
"Devs/MountList": "b32b62007cbfd4e5412f003f3fd83a183845b447",
# "Devs/narrator.device": "c5a35d605c39b9c59542d71883238a02e92d726d",
"Devs/parallel.device": "88c8c2bae625caf7b2bdbea9688a763f035bc199",
"Devs/printer.device": "b13d1ec922deafa5a479fc1c591f911ff95559eb",
"Devs/Printers/": "",
"Devs/Printers/generic": "11473c5271b970e36c70b408aac7c67fff7d97b6",
"Devs/serial.device": "d814d6ce8efb4a87966dae581eddf4dca528094a",
"Devs/system-configuration": "4be3d7e8395a5827085f57cb6cdbf5e88fa78506",
"Expansion/": "",
"Fonts/": "",
"L/": "",
"L/aux-handler": "5a20c44cdcba0793fd292e3f951832ad4670f65e",
"L/port-handler": "d7e4ddab8cbd94f751a6ffd4bc93cfe07cb4cae2",
"L/queue-handler": "a458c6935c90d8a9422600c84875237e0558f89b",
# "L/speak-handler": "d577708e1a0be7566885824349102025f1a250c4",
"Libs/": "",
"Libs/asl.library": "8d1fd81d7c128c397443f0ceb696dab3fecc5828",
"Libs/commodities.library": "eaa02d69480d8df876f3932bf13f7c6e6ebc6c78",
"Libs/diskfont.library": "97022049498794fe8f6135b53ed01d0688903499",
"Libs/iffparse.library": "32eb189c8c003e8bdb1c836fa0ffd12a5d2c9f17",
"Libs/mathieeedoubbas.library": "ce7888086d9749d738e1141e7b7e200f5eb780a9",
"Libs/mathieeedoubtrans.library": "6d6e29a25f7bc87d26a56d437441d3a2c789b126",
"Libs/mathieeesingtrans.library": "b9b164b6a7bff61ffd703999c93f756ea447452f",
"Libs/mathtrans.library": "92d5888b3d2d3bb83c66cc6e486d303821c518c9",
"Libs/rexxsupport.library": "7ae7acdd99a89d00b706060f818ad340869827a2",
"Libs/rexxsyslib.library": "b74995c09a0d6350498579b8ff406477ae5b9566",
# "Libs/translator.library": "e99c035faf5184a3397c89a3df1a7606c8417be6",
"Libs/version.library": "ac699c82157ccc204aaf1eb78e3c53c4a8f13bf5",
"Monitors/": "",
"Prefs/": "",
"Prefs/Env-Archive/": "",
"Prefs/Env-Archive/sys/": "",
"Prefs/Env-Archive/sys/wbconfig.prefs": "9658314fdb2a32286dba8830cf701469ac0089d3",
"Prefs/Font": "c8d0f7bd565fb151ff0738e9df9f063cd43cf244",
"Prefs/IControl": "c3d984f4ca7213194c8bfa5cb20ef8487c107e7a",
"Prefs/Input": "37b19e8dd679c1d901c6620d0635cd9a56b92ab9",
"Prefs/Overscan": "d15843c3147bff57f3dd4ffc2303d1609ca0eb12",
"Prefs/Palette": "3d8712e5b337e8a02c5e786975b5724bd9716f8e",
"Prefs/Pointer": "79c013f9d2065b7c2f824e530c05e65b182c00de",
"Prefs/Presets/": "",
"Prefs/Printer": "89a003a1b26c5a0b9eb2fdf6ddd53cb5368445cb",
"Prefs/PrinterGfx": "84d71c99acac85cf65cf073e736b55871e286d2c",
"Prefs/ScreenMode": "640adc69430a72f08a42761b4d3740840d95a834",
"Prefs/Serial": "8b7e24eb43396dc0fc5a341a2425213fb7d77ac3",
"Prefs/Time": "bb07a47dbb7453fbeb61ecae5ba9459f33b4217c",
"Prefs/WBPattern": "42b809a0d4f02ea5e7f720df3e7a5e97827a1689",
"Rexxc/": "",
"Rexxc/HI": "d3934c81b5a7832f0cdd64650f7c74eacc608a0a",
"Rexxc/RX": "527adec943412976b2d40c4556ca48e0a5b0abee",
"Rexxc/RXC": "b42afa06c53df3221683a2d42b2b2ce4f38a4525",
"Rexxc/RXLIB": "04b10ce3d05feb2fdbd722e5a275a0c844e7d86e",
"Rexxc/RXSET": "702b4613236e8faba2270744229171dc46a0d5ed",
"Rexxc/TCC": "473c7136e636b9505332118cd69a3ba29db0dbbe",
"Rexxc/TCO": "f8b901a6ec8c6844a7205f5ceec5aad6e6261531",
"Rexxc/TE": "2f89c6cd66e559b6f3cf5a0783b14fb18236931d",
"Rexxc/TS": "45a5aa31dd4d42099d41948ef976599fa221938d",
"Rexxc/WaitForPort": "f3fea65223cb028f479d1831237385812675a065",
"S/": "",
"S/BRUtab": "36cad75345610b07e447edb5000a368ce14de0df",
"S/DPat": "4c8aac6a4989201c01d36247a9622288beb6d291",
"S/Ed-startup": "298221ea95f4bfa2cc9b0cec4d8643f708a16abc",
"S/HDBackup.config": "5284e3e2897148a373da769df16530cd1fff45c6",
"S/PCD": "d6ff57db9f9cd193d99aa64581ca964494b5e430",
"S/PickMap": "0b9ca76ba793031e11dfd14cf26b1257f9b24d89",
"S/Shell-startup": "3d50527c6c17256f50d04d212d97d0fb27bf862f",
"S/SPat": "870ac2f50dbb2a75989c5418a2012df81455bea8",
"S/Startup-sequence.HD": "d66c044a25bc4235ec1d2479f368aca733a4d77d",
"System/": "",
"System/AddMonitor": "9ef54a726a70298608654a8be35388adbbd4a5eb",
"System/BindMonitor": "5bafd3b20970c9cb05e9619f28091d56ad1dc2c8",
"System/CLI": "1d22d9100a26d12d375fe1fd938f46b5c09017f1",
"System/DiskCopy": "c91ae2a853c386c6c4c2c5dbed394bc69074f552",
"System/FixFonts": "5f093b674d951599af5b5b2f82f3007cfdfa2902",
"System/Format": "e8f87083aefbaf68f03947accca10278b95ad9d5",
"System/NoFastMem": "abb2cff5c39351d111bce07c22585d58219b31a1",
"System/RexxMast": "6f64f8bc51aec68344fae4151697976f59946b8e",
"System/Setmap": "859abaaab6de713c2a46043f5f5421d54b79d88f",
"t/": "",
"Trashcan/": "",
"Utilities/": "",
"Utilities/Clock": "079dadb61258bbb07112a4109b58552fe61f5741",
"Utilities/Display": "5c21232ceea79568d915d2d9d0a96e80e01fd4cb",
"Utilities/Exchange": "b227f5823b2b07f92670f2628426645fbfa4ec40",
"Utilities/More": "39d44f82ad645b9b1cd2931125c5b340613f7e29",
"Utilities/Say": "79614ec17080d87d580f6cd1e20e74f53c1b5174",
"WBStartup/": "",
}
# noinspection SpellCheckingInspection
wb_300_files = {
"C/": "",
"C/AddBuffers": "6ed1a3f24a1f605aa7234410faebbfbb3fda3ee6",
"C/AddDataTypes": "e8bbd0b50fb5de6fa2382e845e1d67011a1ddd2a",
"C/Assign": "b5b7edb67f578019d46af425a16458ec0cdb1c2e",
"C/Avail": "5e62c202fe3cb447a19c39efb43c935eed139a66",
"C/BindDrivers": "be270c04b4591f10da960231e488929d67e58135",
"C/Break": "97ca2404e17fc78e3d988131bb17183c5c3aa15a",
"C/ChangeTaskPri": "66533bb2cee36475b03cd73ae8ab198889e81be3",
"C/ConClip": "956fd130af649ac441d4b68ea9b01e29d4861357",
"C/Copy": "0c5f9470fbcb36fdbcdf970fd1b22aa627328a24",
"C/CPU": "0191712ede6348b8e1803f5807a941a85c12bd0a",
"C/Date": "0d190c0ce0b99cd653a8f982964eed110ac540eb",
"C/Delete": "0597fd916dd28850ef68bb904937cad0d347cf5a",
"C/Dir": "184eef562670fd6b22b3025e385f992469fa50d4",
"C/DiskChange": "2cae12bfbb1cc98348e7afabf0f48b09cadbaf5e",
"C/Ed": "077483aacde3b40eeeb7b2b08cff3c18d6174e1c",
"C/Edit": "14a1b22e4d72f85cd64b49cfdc8380b294f2da15",
"C/Eval": "fae9792514d07b6fbb5b04d778492941dee5c448",
"C/Execute": "ef1e6f6db0f3a513e0dc98add537e1db87b1856a",
"C/Filenote": "6c263e034a3aca677467d410e410ba808a5f2b8d",
"C/IconX": "09bd52d33b700538e9bed493f245a3ffce944ad3",
"C/Info": "3f5f37e405ca929cf0b4c6ac6abbf7f8d4f19892",
"C/Install": "b4bf5e4ecda66c6a66e1780d1143f632e573ed3b",
"C/IPrefs": "5b5b70ec7b06a6fa142d01372a4e0fce1bff5461",
"C/Join": "da8d787eadd16e682216c808cbbd1427acde7280",
"C/List": "86c0a28542939ea5e0d2075f9db337d93b139fb7",
"C/LoadWB": "e663a715c6ad69a7d3882b4772cbdc9de835e791",
"C/Lock": "a671aabf698196baa6a237601d07fb49b7f64f60",
# "C/MagTape": "8d14c533f6fb73286a642bb208151c36da3af2c9",
"C/MakeDir": "3e00b210538357ff2ca9f0bc16471f06fb994282",
"C/MakeLink": "da8472a553ece5484d7ba1290884ad5d59db5770",
"C/Mount": "c691df2ceb10c6dccd4f735dea0f07c199e09074",
"C/Protect": "e95073c0169dd7c7ca39b9842b339a1288ca3016",
"C/Relabel": "056cb6a12033f5638b1353be1007106fd9267a6e",
"C/RemRAD": "7e5d53c865debaa9d752f96ef818320248332ef6",
"C/Rename": "d1cb2ab35c8fa0dc912b98dbcf002c2c3b220988",
"C/RequestChoice": "5198856e4ebc9c88e5799627aeceaa42866f6525",
"C/RequestFile": "46a45ca9906b52a215161c2141193fe740f41d71",
"C/Search": "89c1dd049ca2fff58269fd44af2705abdedff112",
"C/SetClock": "0c166dd6f8baa45eda766f3b41a0f799f8e7f388",
"C/SetDate": "d7a78803ade6e09dbbba051ab6d4fbcb923527eb",
"C/SetFont": "3b2bb7bb70d84a230a4614dae34c064b7cfc315d",
"C/SetKeyboard": "d32a3aed9f10fdcbb4335296be50f70f2f15438e",
"C/SetPatch": "4d4aae988310b07726329e436b2250c0f769ddff",
"C/Sort": "d886f81bdc74f4942acb52680e56d8bf50a0be8a",
"C/Status": "71e09cfc79d8ede0721ba4a01e1cd43a6318a99f",
"C/Type": "00917f88e78770f6b28562bede2cf64718325553",
"C/Version": "5a698d6494fa50fd3faa7e532def17b6c561d217",
"C/Wait": "a0d503a136dad028ec51e33cfd57d130c1b4b807",
"C/Which": "22952cce8446a1405b1b22d057ec19614e38c366",
"Classes/": "",
"Classes/DataTypes/": "",
"Classes/DataTypes/8svx.datatype": "dae1f0ff6171479b27c21d3e32f7d4e383f969ab",
"Classes/DataTypes/amigaguide.datatype": "d53c3e6abd119a3ca7c15805642a1e6ec96d374c",
"Classes/DataTypes/ascii.datatype": "6f54362a5ce75221a62e0f1fd3a5d23fabc0f2bd",
"Classes/DataTypes/ilbm.datatype": "c8251ed31ad79aa71cf6d3c134815c8f38c70226",
"Classes/DataTypes/picture.datatype": "8028e6782c4069c45ffc4b51cef493f8339a1be9",
"Classes/DataTypes/sound.datatype": "e4fbdbc5e55ddc4635dcd2e76e5623217c4a41a2",
"Classes/DataTypes/text.datatype": "e6b80a188123cb397f7a79a1b580206bb369f2e2",
"Classes/Gadgets/": "",
"Classes/Gadgets/colorwheel.gadget": "7bbfccb8fd5d68b2ae8aac226eff877e8ebc9734",
"Classes/Gadgets/gradientslider.gadget": "a54f39e9098f2c58e892b9183b555fe0a8574191",
"Devs/": "",
"Devs/clipboard.device": "c8d85bd384ea5033d5474283e83c02ad6cdaf32b",
"Devs/DataTypes/": "",
"Devs/DataTypes/8SVX": "b9116bb7654e12f7d281d32ca333a0f283e15532",
"Devs/DataTypes/AmigaGuide": "e89b0bf0d75585b8f27e40d711164ab9e2a0c222",
"Devs/DataTypes/FTXT": "cee60b9550ace3d44ba1d214ed350b05587c3919",
"Devs/DataTypes/ILBM": "1cf3598ca839c554e6a7acc333ddd8327f8ac5d3",
"Devs/DOSDrivers/": "",
"Devs/DOSDrivers/PIPE": "624dd68e9a2794bf5bd60e58c1b3679a1dfd273c",
"Devs/Keymaps/": "",
# "Devs/mfm.device": "63b150010e420f96304375badca126812daa2255",
"Devs/Monitors/": "",
"Devs/parallel.device": "88c8c2bae625caf7b2bdbea9688a763f035bc199",
"Devs/postscript_init.ps": "3c0bc3408a4ac929936f647637a04f45d227cca0",
"Devs/printer.device": "aaf3970e54bedaf84cd69268fc6cf3730c395ba1",
"Devs/Printers/": "",
"Devs/Printers/Generic": "11473c5271b970e36c70b408aac7c67fff7d97b6",
"Devs/serial.device": "d814d6ce8efb4a87966dae581eddf4dca528094a",
"Devs/system-configuration": "4be3d7e8395a5827085f57cb6cdbf5e88fa78506",
"Expansion/": "",
"L/": "",
# "L/aux-handler": "5a20c44cdcba0793fd292e3f951832ad4670f65e",
# "L/CrossDOSFileSystem": "9f05f997b3aa0c3a431bea96cc4bbc153ba48814",
# "L/FileSystem_Trans/": "",
# "L/FileSystem_Trans/DANSK.crossdos":
# "3db3dbfdb9f6d874368f12152944b00099fd9943",
# "L/FileSystem_Trans/INTL.crossdos":
# "6d803e82923564dd2f12b68836b2356282edfd93",
"L/port-handler": "d7e4ddab8cbd94f751a6ffd4bc93cfe07cb4cae2",
"L/queue-handler": "a458c6935c90d8a9422600c84875237e0558f89b",
"Libs/": "",
"Libs/amigaguide.library": "42b1ea9b94f12f4ad5275bb29a8a49fb977f1910",
"Libs/asl.library": "ae59765242d7d1fc022d819a980652463e72688a",
"Libs/bullet.library": "efffa71e955805d543842cbd0c67e75b591fe567",
"Libs/commodities.library": "e52e0a7e2fb653a6895fb1cf15d0b37aed18f909",
"Libs/datatypes.library": "1ea18282089ae14620c1fc71e82592d52217ff2a",
"Libs/diskfont.library": "15d9765f1b66c4a3068d11186ea5bf41a8c8ad3b",
"Libs/iffparse.library": "946ef60b4ba9f63593dbadfbc447546d7ab9725c",
"Libs/locale.library": "a12b91f662a1c527ff6411b43555bc7eaeb370b4",
"Libs/mathieeedoubbas.library": "08d8508cdcb77ad421a6dd6f80721b727c09d96b",
"Libs/mathieeedoubtrans.library": "6d6e29a25f7bc87d26a56d437441d3a2c789b126",
"Libs/mathieeesingtrans.library": "b9b164b6a7bff61ffd703999c93f756ea447452f",
"Libs/mathtrans.library": "92d5888b3d2d3bb83c66cc6e486d303821c518c9",
"Libs/rexxsupport.library": "7ae7acdd99a89d00b706060f818ad340869827a2",
"Libs/rexxsyslib.library": "b74995c09a0d6350498579b8ff406477ae5b9566",
"Libs/version.library": "9af4fa21ce77ca97b4604ffb095a9b2488295c85",
"Prefs/": "",
"Prefs/Env-Archive/": "",
"Prefs/Env-Archive/Sys/": "",
"Prefs/Env-Archive/Sys/wbconfig.prefs": "9658314fdb2a32286dba8830cf701469ac0089d3",
"Prefs/Presets/": "",
"Rexxc/": "",
"Rexxc/HI": "d3934c81b5a7832f0cdd64650f7c74eacc608a0a",
"Rexxc/RX": "527adec943412976b2d40c4556ca48e0a5b0abee",
"Rexxc/RXC": "b42afa06c53df3221683a2d42b2b2ce4f38a4525",
"Rexxc/RXLIB": "04b10ce3d05feb2fdbd722e5a275a0c844e7d86e",
"Rexxc/RXSET": "702b4613236e8faba2270744229171dc46a0d5ed",
"Rexxc/TCC": "473c7136e636b9505332118cd69a3ba29db0dbbe",
"Rexxc/TCO": "f8b901a6ec8c6844a7205f5ceec5aad6e6261531",
"Rexxc/TE": "2f89c6cd66e559b6f3cf5a0783b14fb18236931d",
"Rexxc/TS": "45a5aa31dd4d42099d41948ef976599fa221938d",
"Rexxc/WaitForPort": "f3fea65223cb028f479d1831237385812675a065",
"S/": "",
# "S/DPat": "227c6ed4ae33850577a0b03e22b7dfd966b421c4",
"S/Ed-startup": "2a4e2dd940726199aea3c5cab73dcc527b624fb8",
# "S/PCD": "02d4b5292a9ea3b56d68ca7bba3d1df5055b3a25",
"S/Shell-Startup": "d039a940c89ec6c30a1b3568bfd6afe626a28b6d",
# "S/SPat": "4f63e17cb9ca68b5dc5eb37fd02508f4c5ae0761",
"System/": "",
"System/CLI": "9f25538fd0a6b134dd7a094350731cdc1e9234e3",
"System/DiskCopy": "902aa22b272961911a279bba4aca1fd7ba9c537b",
"System/FixFonts": "86757c1120ce2137e3c72024fa9de898de8a7b24",
"System/Format": "76918338279f5c1a2b86405f39d9e9c8e9ac0981",
"System/NoFastMem": "6295d9937d3eb3370af14bf510c9ad02f687bd4b",
"System/RexxMast": "6f64f8bc51aec68344fae4151697976f59946b8e",
"T/": "",
"Utilities/": "",
"Utilities/Clock": "fda1ad2f1bfb730d9c0dbda4b1141935b67f65ae",
"Utilities/More": "daced6e93fce3bf91a659ea161e343b87233cc54",
"Utilities/MultiView": "c8e7b9f35907e168a03f5b46c9890b4094077750",
"WBStartup/": "",
}
# noinspection SpellCheckingInspection
wb_133_floppies = [
# Workbench v1.3.3 rev 34.34 (1990)(Commodore)(A500-A2000)
# (Disk 1 of 2)(Workbench).adf
"86cb4e007f9fdcf6c5eda6adba3f60f188063875",
# Workbench v1.3.3 rev 34.34 (1990)(Commodore)(A500-A2000)(Dk)
# (Disk 1 of 2)(Workbench)[m].adf
"8d8314faa3b5fbc472c11d5fc669358522c1d00b",
# amiga-os-134-workbench.adf
"42c5af6554212e9d381f7535c3951ee284e127b2",
]
# noinspection SpellCheckingInspection
wb_204_floppies = [
# Workbench v2.04 rev 37.67 (1991)(Commodore)
# (Disk 1 of 4)(Workbench).adf
"8d5c0310a86f14fb3e6a1da001ceb50b9a592c51",
# Workbench v2.04 rev 37.67 (1991)(Commodore)
# (Disk 1 of 4)(Workbench)[m].adf
"d9d8bc1964d9159b3669fadedcd140ead197b0b7",
# Workbench v2.04 rev 37.67 (1991)(Commodore)
# (Disk 1 of 4)(Workbench)[m4].adf
"21a4363e236011f0173c393207a2225a0a3002b0",
# Workbench v2.04 rev 37.67 (1991)(Commodore)
# (Disk 1 of 4)(Workbench)[m2].adf
"898c0c372c476d8410890388b81ca642cc0b381d",
# Workbench v2.04 rev 37.67 (1991)(Commodore)
# (Disk 1 of 4)(Workbench)[m3].adf
"5913fa0fb6cfa74ae9c80870f6ab8a4289036788",
# amiga-os-204-workbench.adf
"898c0c372c476d8410890388b81ca642cc0b381d",
]
# noinspection SpellCheckingInspection
wb_300_floppies = [
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[!].adf
"e663c92a9c88fa38d02bbb299bea8ce70c56b417",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[m2].adf
"cf2f24cf5f5065479476a38ec8f1016b1f746884",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[m5].adf
"4f4770caae5950eca4a2720e0424df052ced6a32",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[a].adf
"9496daa66e6b2f4ddde4fa2580bb3983a25e3cd2",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[m3].adf
"0e7f30223af254df0e2b91ea409f35c56d6164a6",
# amiga-os-300-workbench.adf
"4f4770caae5950eca4a2720e0424df052ced6a32",
]
# noinspection SpellCheckingInspection
workbench_disks_with_setpatch_39_6 = [
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 1 of 6)(Install).adf
"ba24b4172339b9198e4f724a6804d0c6eb5e394b",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 1 of 6)(Install)[a].adf
"c0781dece2486b54e15ce54a9b24dec6d9429421",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 1 of 6)(Install)[m drive definitions].adf
"7eeb2511ce34f8d3f09efe82b290bddeb899d237",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 1 of 6)(Install)[m2].adf
"7271d7db4472e10fbe4b266278e16f03336c14e3",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 1 of 6)(Install)[m3].adf
"92c2f33bb73e1bdee5d9a0dc0f5b09a15524f684",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[!].adf
"e663c92a9c88fa38d02bbb299bea8ce70c56b417",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[a2].adf
"65ab988e597b456ac40320f88a502fc016d590aa",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[a].adf
"9496daa66e6b2f4ddde4fa2580bb3983a25e3cd2",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[m2].adf
"cf2f24cf5f5065479476a38ec8f1016b1f746884",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[m3].adf
"0e7f30223af254df0e2b91ea409f35c56d6164a6",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[m4].adf
"08c4afde7a67e6aaee1f07af96e95e9bed897947",
# amiga-os-300-workbench.adf
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[m5].adf
"4f4770caae5950eca4a2720e0424df052ced6a32",
# Workbench v3.0 rev 39.29 (1992)(Commodore)(A1200-A4000)(M10)
# (Disk 2 of 6)(Workbench)[m].adf
"53086c3e44ec2d34e60ab65af71fb11941f4e0af",
]
def update_files():
base_dir = os.path.expanduser("~/Documents/FS-UAE/Floppies/Workbench")
# floppies = {}
floppy_file_sets = {}
files = {}
for floppy in os.listdir(base_dir):
if not floppy.lower().endswith(".adf"):
continue
path = os.path.join(base_dir, floppy)
with open(path, "rb") as f:
floppy_sha1 = hashlib.sha1(f.read()).hexdigest()
sha1sums = set()
try:
adf = ADFFile(path)
except Exception:
print("error parsing", path)
traceback.print_exc()
continue
names = adf.namelist()
for name in names:
if name.endswith("/"):
continue
data = adf.open(name, "r").read()
sha1 = hashlib.sha1(data).hexdigest()
sha1sums.add(sha1)
# floppies[floppy.lower()] = os.path.join(base_dir, floppy)
files.setdefault(sha1, set()).add((floppy_sha1, name))
floppy_file_sets[(floppy, floppy_sha1)] = sha1sums
interesting_files = set()
for file_map in [wb_204_files, wb_300_files]:
for name, sha1 in file_map.items():
if sha1:
interesting_files.add(sha1)
# print("")
# print("workbench_file_map = {")
# for sha1 in sorted(interesting_files):
# print(" \"{0}\": [".format(sha1))
# #print(" \"{0}\",".format(floppy_sha1))
# for floppy_sha1, name in sorted(files[sha1]):
# #print(" \"{0}\",".format(floppy_sha1))
# print(" (\"{0}\", \"{1}\"),".format(floppy_sha1, name))
# print(" ],")
# print("}")
# print("")
for name, file_map in [
("wb_133_floppies", wb_133_files),
("wb_204_floppies", wb_204_files),
("wb_300_floppies", wb_300_files),
]:
print("\n" + name + " = [")
file_set = set([x for x in file_map.values() if x])
for floppy_data, floppy_file_set in floppy_file_sets.items():
floppy_name, floppy_sha1 = floppy_data
if floppy_file_set.issuperset(file_set):
print(" # {0}".format(floppy_name))
print(' "{0}",'.format(floppy_sha1))
print("]")
def main():
if sys.argv[1] == "--update-files":
update_files()
return
base_dir = os.path.expanduser("~/Documents/FS-UAE/Floppies/Workbench")
floppies = {}
for floppy in os.listdir(base_dir):
if not floppy.lower().endswith(".adf"):
continue
floppies[floppy.lower()] = os.path.join(base_dir, floppy)
floppy = floppies[sys.argv[1].lower()]
adf = ADFFile(floppy)
names = adf.namelist()
startup_sequence = ""
for name in names:
if name.lower() == "s/startup-sequence":
startup_sequence = adf.open(name, "r").read()
continue
if name.endswith(".info"):
continue
if name.endswith("/"):
sha1 = ""
else:
data = adf.open(name, "r").read()
sha1 = hashlib.sha1(data).hexdigest()
if sha1:
if len(name) > (80 - 4 - 2 - 1 - 2 - 2 - 40):
print(' "{0}":\n "{1}",'.format(name, sha1))
else:
print(' "{0}": "{1}",'.format(name, sha1))
else:
print(' "{0}": "",'.format(name))
print("")
print(startup_sequence)
if __name__ == "__main__":
main()
|
FrodeSolheim/fs-uae-launcher
|
fsgamesys/amiga/workbenchdata.py
|
Python
|
gpl-2.0
| 37,574
|
[
"ADF"
] |
e4e60247e78d8955855c68fb97adc9a0f5e63be04651957c886a7f18e9e08319
|
from __future__ import with_statement
from setuptools import setup, find_packages
def version():
with open('VERSION') as f:
return f.read().strip()
def readme():
with open('README.md') as f:
return f.read()
reqs = [line.strip() for line in open('requirements.txt') if not line.startswith('#')]
setup(
name = "pyaxiom",
version = version(),
description = "An ocean data toolkit developed and used by Axiom Data Science",
long_description = readme(),
license = 'MIT',
author = "Kyle Wilcox",
author_email = "kyle@axiomdatascience.com",
url = "https://github.com/axiom-data-science/pyaxiom",
packages = find_packages(),
install_requires = reqs,
entry_points = {
'console_scripts' : [
'binner=pyaxiom.netcdf.grids.binner:run'
],
},
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
],
include_package_data = True,
)
|
axiom-data-science/pyaxiom
|
setup.py
|
Python
|
mit
| 1,330
|
[
"NetCDF"
] |
1c9889bb104c86f14fb09155673bae137cf2f078e8e7e82c1134e0e15099d0fc
|
# Natural Language Toolkit: Logic
#
# Author: Dan Garrette <dhgarrette@gmail.com>
#
# Copyright (C) 2001-2016 NLTK Project
# URL: <http://nltk.org>
# For license information, see LICENSE.TXT
"""
A version of first order predicate logic, built on
top of the typed lambda calculus.
"""
from __future__ import print_function, unicode_literals
import re
import operator
from collections import defaultdict
from functools import reduce
from nltk.util import Trie
from nltk.internals import Counter
from nltk.compat import (total_ordering, string_types,
python_2_unicode_compatible)
APP = 'APP'
_counter = Counter()
class Tokens(object):
LAMBDA = '\\'; LAMBDA_LIST = ['\\']
#Quantifiers
EXISTS = 'exists'; EXISTS_LIST = ['some', 'exists', 'exist']
ALL = 'all'; ALL_LIST = ['all', 'forall']
#Punctuation
DOT = '.'
OPEN = '('
CLOSE = ')'
COMMA = ','
#Operations
NOT = '-'; NOT_LIST = ['not', '-', '!']
AND = '&'; AND_LIST = ['and', '&', '^']
OR = '|'; OR_LIST = ['or', '|']
IMP = '->'; IMP_LIST = ['implies', '->', '=>']
IFF = '<->'; IFF_LIST = ['iff', '<->', '<=>']
EQ = '='; EQ_LIST = ['=', '==']
NEQ = '!='; NEQ_LIST = ['!=']
#Collections of tokens
BINOPS = AND_LIST + OR_LIST + IMP_LIST + IFF_LIST
QUANTS = EXISTS_LIST + ALL_LIST
PUNCT = [DOT, OPEN, CLOSE, COMMA]
TOKENS = BINOPS + EQ_LIST + NEQ_LIST + QUANTS + LAMBDA_LIST + PUNCT + NOT_LIST
#Special
SYMBOLS = [x for x in TOKENS if re.match(r'^[-\\.(),!&^|>=<]*$', x)]
def boolean_ops():
"""
Boolean operators
"""
names = ["negation", "conjunction", "disjunction", "implication", "equivalence"]
for pair in zip(names, [Tokens.NOT, Tokens.AND, Tokens.OR, Tokens.IMP, Tokens.IFF]):
print("%-15s\t%s" % pair)
def equality_preds():
"""
Equality predicates
"""
names = ["equality", "inequality"]
for pair in zip(names, [Tokens.EQ, Tokens.NEQ]):
print("%-15s\t%s" % pair)
def binding_ops():
"""
Binding operators
"""
names = ["existential", "universal", "lambda"]
for pair in zip(names, [Tokens.EXISTS, Tokens.ALL, Tokens.LAMBDA]):
print("%-15s\t%s" % pair)
@python_2_unicode_compatible
class LogicParser(object):
"""A lambda calculus expression parser."""
def __init__(self, type_check=False):
"""
:param type_check: bool should type checking be performed?
to their types.
"""
assert isinstance(type_check, bool)
self._currentIndex = 0
self._buffer = []
self.type_check = type_check
"""A list of tuples of quote characters. The 4-tuple is comprised
of the start character, the end character, the escape character, and
a boolean indicating whether the quotes should be included in the
result. Quotes are used to signify that a token should be treated as
atomic, ignoring any special characters within the token. The escape
character allows the quote end character to be used within the quote.
If True, the boolean indicates that the final token should contain the
quote and escape characters.
This method exists to be overridden"""
self.quote_chars = []
self.operator_precedence = dict(
[(x,1) for x in Tokens.LAMBDA_LIST] + \
[(x,2) for x in Tokens.NOT_LIST] + \
[(APP,3)] + \
[(x,4) for x in Tokens.EQ_LIST+Tokens.NEQ_LIST] + \
[(x,5) for x in Tokens.QUANTS] + \
[(x,6) for x in Tokens.AND_LIST] + \
[(x,7) for x in Tokens.OR_LIST] + \
[(x,8) for x in Tokens.IMP_LIST] + \
[(x,9) for x in Tokens.IFF_LIST] + \
[(None,10)])
self.right_associated_operations = [APP]
def parse(self, data, signature=None):
"""
Parse the expression.
:param data: str for the input to be parsed
:param signature: ``dict<str, str>`` that maps variable names to type
strings
:returns: a parsed Expression
"""
data = data.rstrip()
self._currentIndex = 0
self._buffer, mapping = self.process(data)
try:
result = self.process_next_expression(None)
if self.inRange(0):
raise UnexpectedTokenException(self._currentIndex+1, self.token(0))
except LogicalExpressionException as e:
msg = '%s\n%s\n%s^' % (e, data, ' '*mapping[e.index-1])
raise LogicalExpressionException(None, msg)
if self.type_check:
result.typecheck(signature)
return result
def process(self, data):
"""Split the data into tokens"""
out = []
mapping = {}
tokenTrie = Trie(self.get_all_symbols())
token = ''
data_idx = 0
token_start_idx = data_idx
while data_idx < len(data):
cur_data_idx = data_idx
quoted_token, data_idx = self.process_quoted_token(data_idx, data)
if quoted_token:
if not token:
token_start_idx = cur_data_idx
token += quoted_token
continue
st = tokenTrie
c = data[data_idx]
symbol = ''
while c in st:
symbol += c
st = st[c]
if len(data)-data_idx > len(symbol):
c = data[data_idx+len(symbol)]
else:
break
if Trie.LEAF in st:
#token is a complete symbol
if token:
mapping[len(out)] = token_start_idx
out.append(token)
token = ''
mapping[len(out)] = data_idx
out.append(symbol)
data_idx += len(symbol)
else:
if data[data_idx] in ' \t\n': #any whitespace
if token:
mapping[len(out)] = token_start_idx
out.append(token)
token = ''
else:
if not token:
token_start_idx = data_idx
token += data[data_idx]
data_idx += 1
if token:
mapping[len(out)] = token_start_idx
out.append(token)
mapping[len(out)] = len(data)
mapping[len(out)+1] = len(data)+1
return out, mapping
def process_quoted_token(self, data_idx, data):
token = ''
c = data[data_idx]
i = data_idx
for start, end, escape, incl_quotes in self.quote_chars:
if c == start:
if incl_quotes:
token += c
i += 1
while data[i] != end:
if data[i] == escape:
if incl_quotes:
token += data[i]
i += 1
if len(data) == i: #if there are no more chars
raise LogicalExpressionException(None, "End of input reached. "
"Escape character [%s] found at end."
% escape)
token += data[i]
else:
token += data[i]
i += 1
if len(data) == i:
raise LogicalExpressionException(None, "End of input reached. "
"Expected: [%s]" % end)
if incl_quotes:
token += data[i]
i += 1
if not token:
raise LogicalExpressionException(None, 'Empty quoted token found')
break
return token, i
def get_all_symbols(self):
"""This method exists to be overridden"""
return Tokens.SYMBOLS
def inRange(self, location):
"""Return TRUE if the given location is within the buffer"""
return self._currentIndex+location < len(self._buffer)
def token(self, location=None):
"""Get the next waiting token. If a location is given, then
return the token at currentIndex+location without advancing
currentIndex; setting it gives lookahead/lookback capability."""
try:
if location is None:
tok = self._buffer[self._currentIndex]
self._currentIndex += 1
else:
tok = self._buffer[self._currentIndex+location]
return tok
except IndexError:
raise ExpectedMoreTokensException(self._currentIndex+1)
def isvariable(self, tok):
return tok not in Tokens.TOKENS
def process_next_expression(self, context):
"""Parse the next complete expression from the stream and return it."""
try:
tok = self.token()
except ExpectedMoreTokensException:
raise ExpectedMoreTokensException(self._currentIndex+1, message='Expression expected.')
accum = self.handle(tok, context)
if not accum:
raise UnexpectedTokenException(self._currentIndex, tok, message='Expression expected.')
return self.attempt_adjuncts(accum, context)
def handle(self, tok, context):
"""This method is intended to be overridden for logics that
use different operators or expressions"""
if self.isvariable(tok):
return self.handle_variable(tok, context)
elif tok in Tokens.NOT_LIST:
return self.handle_negation(tok, context)
elif tok in Tokens.LAMBDA_LIST:
return self.handle_lambda(tok, context)
elif tok in Tokens.QUANTS:
return self.handle_quant(tok, context)
elif tok == Tokens.OPEN:
return self.handle_open(tok, context)
def attempt_adjuncts(self, expression, context):
cur_idx = None
while cur_idx != self._currentIndex: #while adjuncts are added
cur_idx = self._currentIndex
expression = self.attempt_EqualityExpression(expression, context)
expression = self.attempt_ApplicationExpression(expression, context)
expression = self.attempt_BooleanExpression(expression, context)
return expression
def handle_negation(self, tok, context):
return self.make_NegatedExpression(self.process_next_expression(Tokens.NOT))
def make_NegatedExpression(self, expression):
return NegatedExpression(expression)
def handle_variable(self, tok, context):
#It's either: 1) a predicate expression: sees(x,y)
# 2) an application expression: P(x)
# 3) a solo variable: john OR x
accum = self.make_VariableExpression(tok)
if self.inRange(0) and self.token(0) == Tokens.OPEN:
#The predicate has arguments
if not isinstance(accum, FunctionVariableExpression) and \
not isinstance(accum, ConstantExpression):
raise LogicalExpressionException(self._currentIndex,
"'%s' is an illegal predicate name. "
"Individual variables may not be used as "
"predicates." % tok)
self.token() #swallow the Open Paren
#curry the arguments
accum = self.make_ApplicationExpression(accum, self.process_next_expression(APP))
while self.inRange(0) and self.token(0) == Tokens.COMMA:
self.token() #swallow the comma
accum = self.make_ApplicationExpression(accum, self.process_next_expression(APP))
self.assertNextToken(Tokens.CLOSE)
return accum
def get_next_token_variable(self, description):
try:
tok = self.token()
except ExpectedMoreTokensException as e:
raise ExpectedMoreTokensException(e.index, 'Variable expected.')
if isinstance(self.make_VariableExpression(tok), ConstantExpression):
raise LogicalExpressionException(self._currentIndex,
"'%s' is an illegal variable name. "
"Constants may not be %s." % (tok, description))
return Variable(tok)
def handle_lambda(self, tok, context):
# Expression is a lambda expression
if not self.inRange(0):
raise ExpectedMoreTokensException(self._currentIndex+2,
message="Variable and Expression expected following lambda operator.")
vars = [self.get_next_token_variable('abstracted')]
while True:
if not self.inRange(0) or (self.token(0) == Tokens.DOT and not self.inRange(1)):
raise ExpectedMoreTokensException(self._currentIndex+2, message="Expression expected.")
if not self.isvariable(self.token(0)):
break
# Support expressions like: \x y.M == \x.\y.M
vars.append(self.get_next_token_variable('abstracted'))
if self.inRange(0) and self.token(0) == Tokens.DOT:
self.token() #swallow the dot
accum = self.process_next_expression(tok)
while vars:
accum = self.make_LambdaExpression(vars.pop(), accum)
return accum
def handle_quant(self, tok, context):
# Expression is a quantified expression: some x.M
factory = self.get_QuantifiedExpression_factory(tok)
if not self.inRange(0):
raise ExpectedMoreTokensException(self._currentIndex+2,
message="Variable and Expression expected following quantifier '%s'." % tok)
vars = [self.get_next_token_variable('quantified')]
while True:
if not self.inRange(0) or (self.token(0) == Tokens.DOT and not self.inRange(1)):
raise ExpectedMoreTokensException(self._currentIndex+2, message="Expression expected.")
if not self.isvariable(self.token(0)):
break
# Support expressions like: some x y.M == some x.some y.M
vars.append(self.get_next_token_variable('quantified'))
if self.inRange(0) and self.token(0) == Tokens.DOT:
self.token() #swallow the dot
accum = self.process_next_expression(tok)
while vars:
accum = self.make_QuanifiedExpression(factory, vars.pop(), accum)
return accum
def get_QuantifiedExpression_factory(self, tok):
"""This method serves as a hook for other logic parsers that
have different quantifiers"""
if tok in Tokens.EXISTS_LIST:
return ExistsExpression
elif tok in Tokens.ALL_LIST:
return AllExpression
else:
self.assertToken(tok, Tokens.QUANTS)
def make_QuanifiedExpression(self, factory, variable, term):
return factory(variable, term)
def handle_open(self, tok, context):
#Expression is in parens
accum = self.process_next_expression(None)
self.assertNextToken(Tokens.CLOSE)
return accum
def attempt_EqualityExpression(self, expression, context):
"""Attempt to make an equality expression. If the next token is an
equality operator, then an EqualityExpression will be returned.
Otherwise, the parameter will be returned."""
if self.inRange(0):
tok = self.token(0)
if tok in Tokens.EQ_LIST + Tokens.NEQ_LIST and self.has_priority(tok, context):
self.token() #swallow the "=" or "!="
expression = self.make_EqualityExpression(expression, self.process_next_expression(tok))
if tok in Tokens.NEQ_LIST:
expression = self.make_NegatedExpression(expression)
return expression
def make_EqualityExpression(self, first, second):
"""This method serves as a hook for other logic parsers that
have different equality expression classes"""
return EqualityExpression(first, second)
def attempt_BooleanExpression(self, expression, context):
"""Attempt to make a boolean expression. If the next token is a boolean
operator, then a BooleanExpression will be returned. Otherwise, the
parameter will be returned."""
while self.inRange(0):
tok = self.token(0)
factory = self.get_BooleanExpression_factory(tok)
if factory and self.has_priority(tok, context):
self.token() #swallow the operator
expression = self.make_BooleanExpression(factory, expression,
self.process_next_expression(tok))
else:
break
return expression
def get_BooleanExpression_factory(self, tok):
"""This method serves as a hook for other logic parsers that
have different boolean operators"""
if tok in Tokens.AND_LIST:
return AndExpression
elif tok in Tokens.OR_LIST:
return OrExpression
elif tok in Tokens.IMP_LIST:
return ImpExpression
elif tok in Tokens.IFF_LIST:
return IffExpression
else:
return None
def make_BooleanExpression(self, factory, first, second):
return factory(first, second)
def attempt_ApplicationExpression(self, expression, context):
"""Attempt to make an application expression. The next tokens are
a list of arguments in parens, then the argument expression is a
function being applied to the arguments. Otherwise, return the
argument expression."""
if self.has_priority(APP, context):
if self.inRange(0) and self.token(0) == Tokens.OPEN:
if not isinstance(expression, LambdaExpression) and \
not isinstance(expression, ApplicationExpression) and \
not isinstance(expression, FunctionVariableExpression) and \
not isinstance(expression, ConstantExpression):
raise LogicalExpressionException(self._currentIndex,
("The function '%s" % expression) +
"' is not a Lambda Expression, an "
"Application Expression, or a "
"functional predicate, so it may "
"not take arguments.")
self.token() #swallow then open paren
#curry the arguments
accum = self.make_ApplicationExpression(expression, self.process_next_expression(APP))
while self.inRange(0) and self.token(0) == Tokens.COMMA:
self.token() #swallow the comma
accum = self.make_ApplicationExpression(accum, self.process_next_expression(APP))
self.assertNextToken(Tokens.CLOSE)
return accum
return expression
def make_ApplicationExpression(self, function, argument):
return ApplicationExpression(function, argument)
def make_VariableExpression(self, name):
return VariableExpression(Variable(name))
def make_LambdaExpression(self, variable, term):
return LambdaExpression(variable, term)
def has_priority(self, operation, context):
return self.operator_precedence[operation] < self.operator_precedence[context] or \
(operation in self.right_associated_operations and \
self.operator_precedence[operation] == self.operator_precedence[context])
def assertNextToken(self, expected):
try:
tok = self.token()
except ExpectedMoreTokensException as e:
raise ExpectedMoreTokensException(e.index, message="Expected token '%s'." % expected)
if isinstance(expected, list):
if tok not in expected:
raise UnexpectedTokenException(self._currentIndex, tok, expected)
else:
if tok != expected:
raise UnexpectedTokenException(self._currentIndex, tok, expected)
def assertToken(self, tok, expected):
if isinstance(expected, list):
if tok not in expected:
raise UnexpectedTokenException(self._currentIndex, tok, expected)
else:
if tok != expected:
raise UnexpectedTokenException(self._currentIndex, tok, expected)
def __repr__(self):
if self.inRange(0):
msg = 'Next token: ' + self.token(0)
else:
msg = 'No more tokens'
return '<' + self.__class__.__name__ + ': ' + msg + '>'
def read_logic(s, logic_parser=None, encoding=None):
"""
Convert a file of First Order Formulas into a list of {Expression}s.
:param s: the contents of the file
:type s: str
:param logic_parser: The parser to be used to parse the logical expression
:type logic_parser: LogicParser
:param encoding: the encoding of the input string, if it is binary
:type encoding: str
:return: a list of parsed formulas.
:rtype: list(Expression)
"""
if encoding is not None:
s = s.decode(encoding)
if logic_parser is None:
logic_parser = LogicParser()
statements = []
for linenum, line in enumerate(s.splitlines()):
line = line.strip()
if line.startswith('#') or line=='': continue
try:
statements.append(logic_parser.parse(line))
except LogicalExpressionException:
raise ValueError('Unable to parse line %s: %s' % (linenum, line))
return statements
@total_ordering
@python_2_unicode_compatible
class Variable(object):
def __init__(self, name):
"""
:param name: the name of the variable
"""
assert isinstance(name, string_types), "%s is not a string" % name
self.name = name
def __eq__(self, other):
return isinstance(other, Variable) and self.name == other.name
def __ne__(self, other):
return not self == other
def __lt__(self, other):
if not isinstance(other, Variable):
raise TypeError
return self.name < other.name
def substitute_bindings(self, bindings):
return bindings.get(self, self)
def __hash__(self):
return hash(self.name)
def __str__(self):
return self.name
def __repr__(self):
return "Variable('%s')" % self.name
def unique_variable(pattern=None, ignore=None):
"""
Return a new, unique variable.
:param pattern: ``Variable`` that is being replaced. The new variable must
be the same type.
:param term: a set of ``Variable`` objects that should not be returned from
this function.
:rtype: Variable
"""
if pattern is not None:
if is_indvar(pattern.name):
prefix = 'z'
elif is_funcvar(pattern.name):
prefix = 'F'
elif is_eventvar(pattern.name):
prefix = 'e0'
else:
assert False, "Cannot generate a unique constant"
else:
prefix = 'z'
v = Variable("%s%s" % (prefix, _counter.get()))
while ignore is not None and v in ignore:
v = Variable("%s%s" % (prefix, _counter.get()))
return v
def skolem_function(univ_scope=None):
"""
Return a skolem function over the variables in univ_scope
param univ_scope
"""
skolem = VariableExpression(Variable('F%s' % _counter.get()))
if univ_scope:
for v in list(univ_scope):
skolem = skolem(VariableExpression(v))
return skolem
@python_2_unicode_compatible
class Type(object):
def __repr__(self):
return "%s" % self
def __hash__(self):
return hash("%s" % self)
@classmethod
def fromstring(cls, s):
return read_type(s)
@python_2_unicode_compatible
class ComplexType(Type):
def __init__(self, first, second):
assert(isinstance(first, Type)), "%s is not a Type" % first
assert(isinstance(second, Type)), "%s is not a Type" % second
self.first = first
self.second = second
def __eq__(self, other):
return isinstance(other, ComplexType) and \
self.first == other.first and \
self.second == other.second
def __ne__(self, other):
return not self == other
__hash__ = Type.__hash__
def matches(self, other):
if isinstance(other, ComplexType):
return self.first.matches(other.first) and \
self.second.matches(other.second)
else:
return self == ANY_TYPE
def resolve(self, other):
if other == ANY_TYPE:
return self
elif isinstance(other, ComplexType):
f = self.first.resolve(other.first)
s = self.second.resolve(other.second)
if f and s:
return ComplexType(f,s)
else:
return None
elif self == ANY_TYPE:
return other
else:
return None
def __str__(self):
if self == ANY_TYPE:
return "%s" % ANY_TYPE
else:
return '<%s,%s>' % (self.first, self.second)
def str(self):
if self == ANY_TYPE:
return ANY_TYPE.str()
else:
return '(%s -> %s)' % (self.first.str(), self.second.str())
class BasicType(Type):
def __eq__(self, other):
return isinstance(other, BasicType) and ("%s" % self) == ("%s" % other)
def __ne__(self, other):
return not self == other
__hash__ = Type.__hash__
def matches(self, other):
return other == ANY_TYPE or self == other
def resolve(self, other):
if self.matches(other):
return self
else:
return None
@python_2_unicode_compatible
class EntityType(BasicType):
def __str__(self):
return 'e'
def str(self):
return 'IND'
@python_2_unicode_compatible
class TruthValueType(BasicType):
def __str__(self):
return 't'
def str(self):
return 'BOOL'
@python_2_unicode_compatible
class EventType(BasicType):
def __str__(self):
return 'v'
def str(self):
return 'EVENT'
@python_2_unicode_compatible
class AnyType(BasicType, ComplexType):
def __init__(self):
pass
@property
def first(self): return self
@property
def second(self): return self
def __eq__(self, other):
return isinstance(other, AnyType) or other.__eq__(self)
def __ne__(self, other):
return not self == other
__hash__ = Type.__hash__
def matches(self, other):
return True
def resolve(self, other):
return other
def __str__(self):
return '?'
def str(self):
return 'ANY'
TRUTH_TYPE = TruthValueType()
ENTITY_TYPE = EntityType()
EVENT_TYPE = EventType()
ANY_TYPE = AnyType()
def read_type(type_string):
assert isinstance(type_string, string_types)
type_string = type_string.replace(' ', '') #remove spaces
if type_string[0] == '<':
assert type_string[-1] == '>'
paren_count = 0
for i,char in enumerate(type_string):
if char == '<':
paren_count += 1
elif char == '>':
paren_count -= 1
assert paren_count > 0
elif char == ',':
if paren_count == 1:
break
return ComplexType(read_type(type_string[1 :i ]),
read_type(type_string[i+1:-1]))
elif type_string[0] == "%s" % ENTITY_TYPE:
return ENTITY_TYPE
elif type_string[0] == "%s" % TRUTH_TYPE:
return TRUTH_TYPE
elif type_string[0] == "%s" % ANY_TYPE:
return ANY_TYPE
else:
raise LogicalExpressionException("Unexpected character: '%s'." % type_string[0])
class TypeException(Exception):
def __init__(self, msg):
Exception.__init__(self, msg)
class InconsistentTypeHierarchyException(TypeException):
def __init__(self, variable, expression=None):
if expression:
msg = "The variable '%s' was found in multiple places with different"\
" types in '%s'." % (variable, expression)
else:
msg = "The variable '%s' was found in multiple places with different"\
" types." % (variable)
Exception.__init__(self, msg)
class TypeResolutionException(TypeException):
def __init__(self, expression, other_type):
Exception.__init__(self, "The type of '%s', '%s', cannot be "
"resolved with type '%s'" % \
(expression, expression.type, other_type))
class IllegalTypeException(TypeException):
def __init__(self, expression, other_type, allowed_type):
Exception.__init__(self, "Cannot set type of %s '%s' to '%s'; "
"must match type '%s'." %
(expression.__class__.__name__, expression,
other_type, allowed_type))
def typecheck(expressions, signature=None):
"""
Ensure correct typing across a collection of ``Expression`` objects.
:param expressions: a collection of expressions
:param signature: dict that maps variable names to types (or string
representations of types)
"""
#typecheck and create master signature
for expression in expressions:
signature = expression.typecheck(signature)
#apply master signature to all expressions
for expression in expressions[:-1]:
expression.typecheck(signature)
return signature
class SubstituteBindingsI(object):
"""
An interface for classes that can perform substitutions for
variables.
"""
def substitute_bindings(self, bindings):
"""
:return: The object that is obtained by replacing
each variable bound by ``bindings`` with its values.
Aliases are already resolved. (maybe?)
:rtype: (any)
"""
raise NotImplementedError()
def variables(self):
"""
:return: A list of all variables in this object.
"""
raise NotImplementedError()
@python_2_unicode_compatible
class Expression(SubstituteBindingsI):
"""This is the base abstract object for all logical expressions"""
_logic_parser = LogicParser()
_type_checking_logic_parser = LogicParser(type_check=True)
@classmethod
def fromstring(cls, s, type_check=False, signature=None):
if type_check:
return cls._type_checking_logic_parser.parse(s, signature)
else:
return cls._logic_parser.parse(s, signature)
def __call__(self, other, *additional):
accum = self.applyto(other)
for a in additional:
accum = accum(a)
return accum
def applyto(self, other):
assert isinstance(other, Expression), "%s is not an Expression" % other
return ApplicationExpression(self, other)
def __neg__(self):
return NegatedExpression(self)
def negate(self):
"""If this is a negated expression, remove the negation.
Otherwise add a negation."""
return -self
def __and__(self, other):
if not isinstance(other, Expression):
raise TypeError("%s is not an Expression" % other)
return AndExpression(self, other)
def __or__(self, other):
if not isinstance(other, Expression):
raise TypeError("%s is not an Expression" % other)
return OrExpression(self, other)
def __gt__(self, other):
if not isinstance(other, Expression):
raise TypeError("%s is not an Expression" % other)
return ImpExpression(self, other)
def __lt__(self, other):
if not isinstance(other, Expression):
raise TypeError("%s is not an Expression" % other)
return IffExpression(self, other)
def __eq__(self, other):
raise NotImplementedError()
def __ne__(self, other):
return not self == other
def equiv(self, other, prover=None):
"""
Check for logical equivalence.
Pass the expression (self <-> other) to the theorem prover.
If the prover says it is valid, then the self and other are equal.
:param other: an ``Expression`` to check equality against
:param prover: a ``nltk.inference.api.Prover``
"""
assert isinstance(other, Expression), "%s is not an Expression" % other
if prover is None:
from nltk.inference import Prover9
prover = Prover9()
bicond = IffExpression(self.simplify(), other.simplify())
return prover.prove(bicond)
def __hash__(self):
return hash(repr(self))
def substitute_bindings(self, bindings):
expr = self
for var in expr.variables():
if var in bindings:
val = bindings[var]
if isinstance(val, Variable):
val = self.make_VariableExpression(val)
elif not isinstance(val, Expression):
raise ValueError('Can not substitute a non-expression '
'value into an expression: %r' % (val,))
# Substitute bindings in the target value.
val = val.substitute_bindings(bindings)
# Replace var w/ the target value.
expr = expr.replace(var, val)
return expr.simplify()
def typecheck(self, signature=None):
"""
Infer and check types. Raise exceptions if necessary.
:param signature: dict that maps variable names to types (or string
representations of types)
:return: the signature, plus any additional type mappings
"""
sig = defaultdict(list)
if signature:
for key in signature:
val = signature[key]
varEx = VariableExpression(Variable(key))
if isinstance(val, Type):
varEx.type = val
else:
varEx.type = read_type(val)
sig[key].append(varEx)
self._set_type(signature=sig)
return dict((key, sig[key][0].type) for key in sig)
def findtype(self, variable):
"""
Find the type of the given variable as it is used in this expression.
For example, finding the type of "P" in "P(x) & Q(x,y)" yields "<e,t>"
:param variable: Variable
"""
raise NotImplementedError()
def _set_type(self, other_type=ANY_TYPE, signature=None):
"""
Set the type of this expression to be the given type. Raise type
exceptions where applicable.
:param other_type: Type
:param signature: dict(str -> list(AbstractVariableExpression))
"""
raise NotImplementedError()
def replace(self, variable, expression, replace_bound=False, alpha_convert=True):
"""
Replace every instance of 'variable' with 'expression'
:param variable: ``Variable`` The variable to replace
:param expression: ``Expression`` The expression with which to replace it
:param replace_bound: bool Should bound variables be replaced?
:param alpha_convert: bool Alpha convert automatically to avoid name clashes?
"""
assert isinstance(variable, Variable), "%s is not a Variable" % variable
assert isinstance(expression, Expression), "%s is not an Expression" % expression
return self.visit_structured(lambda e: e.replace(variable, expression,
replace_bound, alpha_convert),
self.__class__)
def normalize(self, newvars=None):
"""Rename auto-generated unique variables"""
def get_indiv_vars(e):
if isinstance(e, IndividualVariableExpression):
return set([e])
elif isinstance(e, AbstractVariableExpression):
return set()
else:
return e.visit(get_indiv_vars,
lambda parts: reduce(operator.or_, parts, set()))
result = self
for i,e in enumerate(sorted(get_indiv_vars(self), key=lambda e: e.variable)):
if isinstance(e,EventVariableExpression):
newVar = e.__class__(Variable('e0%s' % (i+1)))
elif isinstance(e,IndividualVariableExpression):
newVar = e.__class__(Variable('z%s' % (i+1)))
else:
newVar = e
result = result.replace(e.variable, newVar, True)
return result
def visit(self, function, combinator):
"""
Recursively visit subexpressions. Apply 'function' to each
subexpression and pass the result of each function application
to the 'combinator' for aggregation:
return combinator(map(function, self.subexpressions))
Bound variables are neither applied upon by the function nor given to
the combinator.
:param function: ``Function<Expression,T>`` to call on each subexpression
:param combinator: ``Function<list<T>,R>`` to combine the results of the
function calls
:return: result of combination ``R``
"""
raise NotImplementedError()
def visit_structured(self, function, combinator):
"""
Recursively visit subexpressions. Apply 'function' to each
subexpression and pass the result of each function application
to the 'combinator' for aggregation. The combinator must have
the same signature as the constructor. The function is not
applied to bound variables, but they are passed to the
combinator.
:param function: ``Function`` to call on each subexpression
:param combinator: ``Function`` with the same signature as the
constructor, to combine the results of the function calls
:return: result of combination
"""
return self.visit(function, lambda parts: combinator(*parts))
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self)
def __str__(self):
return self.str()
def variables(self):
"""
Return a set of all the variables for binding substitution.
The variables returned include all free (non-bound) individual
variables and any variable starting with '?' or '@'.
:return: set of ``Variable`` objects
"""
return self.free() | set(p for p in self.predicates()|self.constants()
if re.match('^[?@]', p.name))
def free(self):
"""
Return a set of all the free (non-bound) variables. This includes
both individual and predicate variables, but not constants.
:return: set of ``Variable`` objects
"""
return self.visit(lambda e: e.free(),
lambda parts: reduce(operator.or_, parts, set()))
def constants(self):
"""
Return a set of individual constants (non-predicates).
:return: set of ``Variable`` objects
"""
return self.visit(lambda e: e.constants(),
lambda parts: reduce(operator.or_, parts, set()))
def predicates(self):
"""
Return a set of predicates (constants, not variables).
:return: set of ``Variable`` objects
"""
return self.visit(lambda e: e.predicates(),
lambda parts: reduce(operator.or_, parts, set()))
def simplify(self):
"""
:return: beta-converted version of this expression
"""
return self.visit_structured(lambda e: e.simplify(), self.__class__)
def make_VariableExpression(self, variable):
return VariableExpression(variable)
@python_2_unicode_compatible
class ApplicationExpression(Expression):
r"""
This class is used to represent two related types of logical expressions.
The first is a Predicate Expression, such as "P(x,y)". A predicate
expression is comprised of a ``FunctionVariableExpression`` or
``ConstantExpression`` as the predicate and a list of Expressions as the
arguments.
The second is a an application of one expression to another, such as
"(\x.dog(x))(fido)".
The reason Predicate Expressions are treated as Application Expressions is
that the Variable Expression predicate of the expression may be replaced
with another Expression, such as a LambdaExpression, which would mean that
the Predicate should be thought of as being applied to the arguments.
The logical expression reader will always curry arguments in a application expression.
So, "\x y.see(x,y)(john,mary)" will be represented internally as
"((\x y.(see(x))(y))(john))(mary)". This simplifies the internals since
there will always be exactly one argument in an application.
The str() method will usually print the curried forms of application
expressions. The one exception is when the the application expression is
really a predicate expression (ie, underlying function is an
``AbstractVariableExpression``). This means that the example from above
will be returned as "(\x y.see(x,y)(john))(mary)".
"""
def __init__(self, function, argument):
"""
:param function: ``Expression``, for the function expression
:param argument: ``Expression``, for the argument
"""
assert isinstance(function, Expression), "%s is not an Expression" % function
assert isinstance(argument, Expression), "%s is not an Expression" % argument
self.function = function
self.argument = argument
def simplify(self):
function = self.function.simplify()
argument = self.argument.simplify()
if isinstance(function, LambdaExpression):
return function.term.replace(function.variable, argument).simplify()
else:
return self.__class__(function, argument)
@property
def type(self):
if isinstance(self.function.type, ComplexType):
return self.function.type.second
else:
return ANY_TYPE
def _set_type(self, other_type=ANY_TYPE, signature=None):
""":see Expression._set_type()"""
assert isinstance(other_type, Type)
if signature is None:
signature = defaultdict(list)
self.argument._set_type(ANY_TYPE, signature)
try:
self.function._set_type(ComplexType(self.argument.type, other_type), signature)
except TypeResolutionException:
raise TypeException(
"The function '%s' is of type '%s' and cannot be applied "
"to '%s' of type '%s'. Its argument must match type '%s'."
% (self.function, self.function.type, self.argument,
self.argument.type, self.function.type.first))
def findtype(self, variable):
""":see Expression.findtype()"""
assert isinstance(variable, Variable), "%s is not a Variable" % variable
if self.is_atom():
function, args = self.uncurry()
else:
#It's not a predicate expression ("P(x,y)"), so leave args curried
function = self.function
args = [self.argument]
found = [arg.findtype(variable) for arg in [function]+args]
unique = []
for f in found:
if f != ANY_TYPE:
if unique:
for u in unique:
if f.matches(u):
break
else:
unique.append(f)
if len(unique) == 1:
return list(unique)[0]
else:
return ANY_TYPE
def constants(self):
""":see: Expression.constants()"""
if isinstance(self.function, AbstractVariableExpression):
function_constants = set()
else:
function_constants = self.function.constants()
return function_constants | self.argument.constants()
def predicates(self):
""":see: Expression.predicates()"""
if isinstance(self.function, ConstantExpression):
function_preds = set([self.function.variable])
else:
function_preds = self.function.predicates()
return function_preds | self.argument.predicates()
def visit(self, function, combinator):
""":see: Expression.visit()"""
return combinator([function(self.function), function(self.argument)])
def __eq__(self, other):
return isinstance(other, ApplicationExpression) and \
self.function == other.function and \
self.argument == other.argument
def __ne__(self, other):
return not self == other
__hash__ = Expression.__hash__
def __str__(self):
# uncurry the arguments and find the base function
if self.is_atom():
function, args = self.uncurry()
arg_str = ','.join("%s" % arg for arg in args)
else:
#Leave arguments curried
function = self.function
arg_str = "%s" % self.argument
function_str = "%s" % function
parenthesize_function = False
if isinstance(function, LambdaExpression):
if isinstance(function.term, ApplicationExpression):
if not isinstance(function.term.function,
AbstractVariableExpression):
parenthesize_function = True
elif not isinstance(function.term, BooleanExpression):
parenthesize_function = True
elif isinstance(function, ApplicationExpression):
parenthesize_function = True
if parenthesize_function:
function_str = Tokens.OPEN + function_str + Tokens.CLOSE
return function_str + Tokens.OPEN + arg_str + Tokens.CLOSE
def uncurry(self):
"""
Uncurry this application expression
return: A tuple (base-function, arg-list)
"""
function = self.function
args = [self.argument]
while isinstance(function, ApplicationExpression):
#(\x.\y.sees(x,y)(john))(mary)
args.insert(0, function.argument)
function = function.function
return (function, args)
@property
def pred(self):
"""
Return uncurried base-function.
If this is an atom, then the result will be a variable expression.
Otherwise, it will be a lambda expression.
"""
return self.uncurry()[0]
@property
def args(self):
"""
Return uncurried arg-list
"""
return self.uncurry()[1]
def is_atom(self):
"""
Is this expression an atom (as opposed to a lambda expression applied
to a term)?
"""
return isinstance(self.pred, AbstractVariableExpression)
@total_ordering
@python_2_unicode_compatible
class AbstractVariableExpression(Expression):
"""This class represents a variable to be used as a predicate or entity"""
def __init__(self, variable):
"""
:param variable: ``Variable``, for the variable
"""
assert isinstance(variable, Variable), "%s is not a Variable" % variable
self.variable = variable
def simplify(self):
return self
def replace(self, variable, expression, replace_bound=False, alpha_convert=True):
""":see: Expression.replace()"""
assert isinstance(variable, Variable), "%s is not an Variable" % variable
assert isinstance(expression, Expression), "%s is not an Expression" % expression
if self.variable == variable:
return expression
else:
return self
def _set_type(self, other_type=ANY_TYPE, signature=None):
""":see Expression._set_type()"""
assert isinstance(other_type, Type)
if signature is None:
signature = defaultdict(list)
resolution = other_type
for varEx in signature[self.variable.name]:
resolution = varEx.type.resolve(resolution)
if not resolution:
raise InconsistentTypeHierarchyException(self)
signature[self.variable.name].append(self)
for varEx in signature[self.variable.name]:
varEx.type = resolution
def findtype(self, variable):
""":see Expression.findtype()"""
assert isinstance(variable, Variable), "%s is not a Variable" % variable
if self.variable == variable:
return self.type
else:
return ANY_TYPE
def predicates(self):
""":see: Expression.predicates()"""
return set()
def __eq__(self, other):
"""Allow equality between instances of ``AbstractVariableExpression``
subtypes."""
return isinstance(other, AbstractVariableExpression) and \
self.variable == other.variable
def __ne__(self, other):
return not self == other
def __lt__(self, other):
if not isinstance(other, AbstractVariableExpression):
raise TypeError
return self.variable < other.variable
__hash__ = Expression.__hash__
def __str__(self):
return "%s" % self.variable
class IndividualVariableExpression(AbstractVariableExpression):
"""This class represents variables that take the form of a single lowercase
character (other than 'e') followed by zero or more digits."""
def _set_type(self, other_type=ANY_TYPE, signature=None):
""":see Expression._set_type()"""
assert isinstance(other_type, Type)
if signature is None:
signature = defaultdict(list)
if not other_type.matches(ENTITY_TYPE):
raise IllegalTypeException(self, other_type, ENTITY_TYPE)
signature[self.variable.name].append(self)
def _get_type(self): return ENTITY_TYPE
type = property(_get_type, _set_type)
def free(self):
""":see: Expression.free()"""
return set([self.variable])
def constants(self):
""":see: Expression.constants()"""
return set()
class FunctionVariableExpression(AbstractVariableExpression):
"""This class represents variables that take the form of a single uppercase
character followed by zero or more digits."""
type = ANY_TYPE
def free(self):
""":see: Expression.free()"""
return set([self.variable])
def constants(self):
""":see: Expression.constants()"""
return set()
class EventVariableExpression(IndividualVariableExpression):
"""This class represents variables that take the form of a single lowercase
'e' character followed by zero or more digits."""
type = EVENT_TYPE
class ConstantExpression(AbstractVariableExpression):
"""This class represents variables that do not take the form of a single
character followed by zero or more digits."""
type = ENTITY_TYPE
def _set_type(self, other_type=ANY_TYPE, signature=None):
""":see Expression._set_type()"""
assert isinstance(other_type, Type)
if signature is None:
signature = defaultdict(list)
if other_type == ANY_TYPE:
#entity type by default, for individuals
resolution = ENTITY_TYPE
else:
resolution = other_type
if self.type != ENTITY_TYPE:
resolution = resolution.resolve(self.type)
for varEx in signature[self.variable.name]:
resolution = varEx.type.resolve(resolution)
if not resolution:
raise InconsistentTypeHierarchyException(self)
signature[self.variable.name].append(self)
for varEx in signature[self.variable.name]:
varEx.type = resolution
def free(self):
""":see: Expression.free()"""
return set()
def constants(self):
""":see: Expression.constants()"""
return set([self.variable])
def VariableExpression(variable):
"""
This is a factory method that instantiates and returns a subtype of
``AbstractVariableExpression`` appropriate for the given variable.
"""
assert isinstance(variable, Variable), "%s is not a Variable" % variable
if is_indvar(variable.name):
return IndividualVariableExpression(variable)
elif is_funcvar(variable.name):
return FunctionVariableExpression(variable)
elif is_eventvar(variable.name):
return EventVariableExpression(variable)
else:
return ConstantExpression(variable)
class VariableBinderExpression(Expression):
"""This an abstract class for any Expression that binds a variable in an
Expression. This includes LambdaExpressions and Quantified Expressions"""
def __init__(self, variable, term):
"""
:param variable: ``Variable``, for the variable
:param term: ``Expression``, for the term
"""
assert isinstance(variable, Variable), "%s is not a Variable" % variable
assert isinstance(term, Expression), "%s is not an Expression" % term
self.variable = variable
self.term = term
def replace(self, variable, expression, replace_bound=False, alpha_convert=True):
""":see: Expression.replace()"""
assert isinstance(variable, Variable), "%s is not a Variable" % variable
assert isinstance(expression, Expression), "%s is not an Expression" % expression
#if the bound variable is the thing being replaced
if self.variable == variable:
if replace_bound:
assert isinstance(expression, AbstractVariableExpression),\
"%s is not a AbstractVariableExpression" % expression
return self.__class__(expression.variable,
self.term.replace(variable, expression, True, alpha_convert))
else:
return self
else:
# if the bound variable appears in the expression, then it must
# be alpha converted to avoid a conflict
if alpha_convert and self.variable in expression.free():
self = self.alpha_convert(unique_variable(pattern=self.variable))
#replace in the term
return self.__class__(self.variable,
self.term.replace(variable, expression, replace_bound, alpha_convert))
def alpha_convert(self, newvar):
"""Rename all occurrences of the variable introduced by this variable
binder in the expression to ``newvar``.
:param newvar: ``Variable``, for the new variable
"""
assert isinstance(newvar, Variable), "%s is not a Variable" % newvar
return self.__class__(newvar,
self.term.replace(self.variable,
VariableExpression(newvar),
True))
def free(self):
""":see: Expression.free()"""
return self.term.free() - set([self.variable])
def findtype(self, variable):
""":see Expression.findtype()"""
assert isinstance(variable, Variable), "%s is not a Variable" % variable
if variable == self.variable:
return ANY_TYPE
else:
return self.term.findtype(variable)
def visit(self, function, combinator):
""":see: Expression.visit()"""
return combinator([function(self.term)])
def visit_structured(self, function, combinator):
""":see: Expression.visit_structured()"""
return combinator(self.variable, function(self.term))
def __eq__(self, other):
r"""Defines equality modulo alphabetic variance. If we are comparing
\x.M and \y.N, then check equality of M and N[x/y]."""
if isinstance(self, other.__class__) or \
isinstance(other, self.__class__):
if self.variable == other.variable:
return self.term == other.term
else:
# Comparing \x.M and \y.N. Relabel y in N with x and continue.
varex = VariableExpression(self.variable)
return self.term == other.term.replace(other.variable, varex)
else:
return False
def __ne__(self, other):
return not self == other
__hash__ = Expression.__hash__
@python_2_unicode_compatible
class LambdaExpression(VariableBinderExpression):
@property
def type(self):
return ComplexType(self.term.findtype(self.variable),
self.term.type)
def _set_type(self, other_type=ANY_TYPE, signature=None):
""":see Expression._set_type()"""
assert isinstance(other_type, Type)
if signature is None:
signature = defaultdict(list)
self.term._set_type(other_type.second, signature)
if not self.type.resolve(other_type):
raise TypeResolutionException(self, other_type)
def __str__(self):
variables = [self.variable]
term = self.term
while term.__class__ == self.__class__:
variables.append(term.variable)
term = term.term
return Tokens.LAMBDA + ' '.join("%s" % v for v in variables) + \
Tokens.DOT + "%s" % term
@python_2_unicode_compatible
class QuantifiedExpression(VariableBinderExpression):
@property
def type(self): return TRUTH_TYPE
def _set_type(self, other_type=ANY_TYPE, signature=None):
""":see Expression._set_type()"""
assert isinstance(other_type, Type)
if signature is None:
signature = defaultdict(list)
if not other_type.matches(TRUTH_TYPE):
raise IllegalTypeException(self, other_type, TRUTH_TYPE)
self.term._set_type(TRUTH_TYPE, signature)
def __str__(self):
variables = [self.variable]
term = self.term
while term.__class__ == self.__class__:
variables.append(term.variable)
term = term.term
return self.getQuantifier() + ' ' + ' '.join("%s" % v for v in variables) + \
Tokens.DOT + "%s" % term
class ExistsExpression(QuantifiedExpression):
def getQuantifier(self):
return Tokens.EXISTS
class AllExpression(QuantifiedExpression):
def getQuantifier(self):
return Tokens.ALL
@python_2_unicode_compatible
class NegatedExpression(Expression):
def __init__(self, term):
assert isinstance(term, Expression), "%s is not an Expression" % term
self.term = term
@property
def type(self): return TRUTH_TYPE
def _set_type(self, other_type=ANY_TYPE, signature=None):
""":see Expression._set_type()"""
assert isinstance(other_type, Type)
if signature is None:
signature = defaultdict(list)
if not other_type.matches(TRUTH_TYPE):
raise IllegalTypeException(self, other_type, TRUTH_TYPE)
self.term._set_type(TRUTH_TYPE, signature)
def findtype(self, variable):
assert isinstance(variable, Variable), "%s is not a Variable" % variable
return self.term.findtype(variable)
def visit(self, function, combinator):
""":see: Expression.visit()"""
return combinator([function(self.term)])
def negate(self):
""":see: Expression.negate()"""
return self.term
def __eq__(self, other):
return isinstance(other, NegatedExpression) and self.term == other.term
def __ne__(self, other):
return not self == other
__hash__ = Expression.__hash__
def __str__(self):
return Tokens.NOT + "%s" % self.term
@python_2_unicode_compatible
class BinaryExpression(Expression):
def __init__(self, first, second):
assert isinstance(first, Expression), "%s is not an Expression" % first
assert isinstance(second, Expression), "%s is not an Expression" % second
self.first = first
self.second = second
@property
def type(self): return TRUTH_TYPE
def findtype(self, variable):
""":see Expression.findtype()"""
assert isinstance(variable, Variable), "%s is not a Variable" % variable
f = self.first.findtype(variable)
s = self.second.findtype(variable)
if f == s or s == ANY_TYPE:
return f
elif f == ANY_TYPE:
return s
else:
return ANY_TYPE
def visit(self, function, combinator):
""":see: Expression.visit()"""
return combinator([function(self.first), function(self.second)])
def __eq__(self, other):
return (isinstance(self, other.__class__) or \
isinstance(other, self.__class__)) and \
self.first == other.first and self.second == other.second
def __ne__(self, other):
return not self == other
__hash__ = Expression.__hash__
def __str__(self):
first = self._str_subex(self.first)
second = self._str_subex(self.second)
return Tokens.OPEN + first + ' ' + self.getOp() \
+ ' ' + second + Tokens.CLOSE
def _str_subex(self, subex):
return "%s" % subex
class BooleanExpression(BinaryExpression):
def _set_type(self, other_type=ANY_TYPE, signature=None):
""":see Expression._set_type()"""
assert isinstance(other_type, Type)
if signature is None:
signature = defaultdict(list)
if not other_type.matches(TRUTH_TYPE):
raise IllegalTypeException(self, other_type, TRUTH_TYPE)
self.first._set_type(TRUTH_TYPE, signature)
self.second._set_type(TRUTH_TYPE, signature)
class AndExpression(BooleanExpression):
"""This class represents conjunctions"""
def getOp(self):
return Tokens.AND
def _str_subex(self, subex):
s = "%s" % subex
if isinstance(subex, AndExpression):
return s[1:-1]
return s
class OrExpression(BooleanExpression):
"""This class represents disjunctions"""
def getOp(self):
return Tokens.OR
def _str_subex(self, subex):
s = "%s" % subex
if isinstance(subex, OrExpression):
return s[1:-1]
return s
class ImpExpression(BooleanExpression):
"""This class represents implications"""
def getOp(self):
return Tokens.IMP
class IffExpression(BooleanExpression):
"""This class represents biconditionals"""
def getOp(self):
return Tokens.IFF
class EqualityExpression(BinaryExpression):
"""This class represents equality expressions like "(x = y)"."""
def _set_type(self, other_type=ANY_TYPE, signature=None):
""":see Expression._set_type()"""
assert isinstance(other_type, Type)
if signature is None:
signature = defaultdict(list)
if not other_type.matches(TRUTH_TYPE):
raise IllegalTypeException(self, other_type, TRUTH_TYPE)
self.first._set_type(ENTITY_TYPE, signature)
self.second._set_type(ENTITY_TYPE, signature)
def getOp(self):
return Tokens.EQ
### Utilities
class LogicalExpressionException(Exception):
def __init__(self, index, message):
self.index = index
Exception.__init__(self, message)
class UnexpectedTokenException(LogicalExpressionException):
def __init__(self, index, unexpected=None, expected=None, message=None):
if unexpected and expected:
msg = "Unexpected token: '%s'. " \
"Expected token '%s'." % (unexpected, expected)
elif unexpected:
msg = "Unexpected token: '%s'." % unexpected
if message:
msg += ' '+message
else:
msg = "Expected token '%s'." % expected
LogicalExpressionException.__init__(self, index, msg)
class ExpectedMoreTokensException(LogicalExpressionException):
def __init__(self, index, message=None):
if not message:
message = 'More tokens expected.'
LogicalExpressionException.__init__(self, index, 'End of input found. ' + message)
def is_indvar(expr):
"""
An individual variable must be a single lowercase character other than 'e',
followed by zero or more digits.
:param expr: str
:return: bool True if expr is of the correct form
"""
assert isinstance(expr, string_types), "%s is not a string" % expr
return re.match(r'^[a-df-z]\d*$', expr) is not None
def is_funcvar(expr):
"""
A function variable must be a single uppercase character followed by
zero or more digits.
:param expr: str
:return: bool True if expr is of the correct form
"""
assert isinstance(expr, string_types), "%s is not a string" % expr
return re.match(r'^[A-Z]\d*$', expr) is not None
def is_eventvar(expr):
"""
An event variable must be a single lowercase 'e' character followed by
zero or more digits.
:param expr: str
:return: bool True if expr is of the correct form
"""
assert isinstance(expr, string_types), "%s is not a string" % expr
return re.match(r'^e\d*$', expr) is not None
def demo():
lexpr = Expression.fromstring
print('='*20 + 'Test reader' + '='*20)
print(lexpr(r'john'))
print(lexpr(r'man(x)'))
print(lexpr(r'-man(x)'))
print(lexpr(r'(man(x) & tall(x) & walks(x))'))
print(lexpr(r'exists x.(man(x) & tall(x) & walks(x))'))
print(lexpr(r'\x.man(x)'))
print(lexpr(r'\x.man(x)(john)'))
print(lexpr(r'\x y.sees(x,y)'))
print(lexpr(r'\x y.sees(x,y)(a,b)'))
print(lexpr(r'(\x.exists y.walks(x,y))(x)'))
print(lexpr(r'exists x.x = y'))
print(lexpr(r'exists x.(x = y)'))
print(lexpr('P(x) & x=y & P(y)'))
print(lexpr(r'\P Q.exists x.(P(x) & Q(x))'))
print(lexpr(r'man(x) <-> tall(x)'))
print('='*20 + 'Test simplify' + '='*20)
print(lexpr(r'\x.\y.sees(x,y)(john)(mary)').simplify())
print(lexpr(r'\x.\y.sees(x,y)(john, mary)').simplify())
print(lexpr(r'all x.(man(x) & (\x.exists y.walks(x,y))(x))').simplify())
print(lexpr(r'(\P.\Q.exists x.(P(x) & Q(x)))(\x.dog(x))(\x.bark(x))').simplify())
print('='*20 + 'Test alpha conversion and binder expression equality' + '='*20)
e1 = lexpr('exists x.P(x)')
print(e1)
e2 = e1.alpha_convert(Variable('z'))
print(e2)
print(e1 == e2)
def demo_errors():
print('='*20 + 'Test reader errors' + '='*20)
demoException('(P(x) & Q(x)')
demoException('((P(x) &) & Q(x))')
demoException('P(x) -> ')
demoException('P(x')
demoException('P(x,')
demoException('P(x,)')
demoException('exists')
demoException('exists x.')
demoException('\\')
demoException('\\ x y.')
demoException('P(x)Q(x)')
demoException('(P(x)Q(x)')
demoException('exists x -> y')
def demoException(s):
try:
Expression.fromstring(s)
except LogicalExpressionException as e:
print("%s: %s" % (e.__class__.__name__, e))
def printtype(ex):
print("%s : %s" % (ex.str(), ex.type))
if __name__ == '__main__':
demo()
# demo_errors()
|
adazey/Muzez
|
libs/nltk/sem/logic.py
|
Python
|
gpl-3.0
| 69,910
|
[
"VisIt"
] |
a22b807a1096666b2eec325df46d5a7568f1f0e586b21fd7eddfd4a5908a9e6b
|
""" :mod: GFAL2_SRM2Storage
=================
.. module: python
:synopsis: SRM2 module based on the GFAL2_StorageBase class.
"""
# pylint: disable=invalid-name
import six
import errno
import json
import gfal2 # pylint: disable=import-error
# from DIRAC
from DIRAC import gLogger, gConfig, S_OK, S_ERROR
from DIRAC.Resources.Storage.GFAL2_StorageBase import GFAL2_StorageBase
from DIRAC.Resources.Storage.Utilities import checkArgumentFormat
class GFAL2_SRM2Storage(GFAL2_StorageBase):
"""SRM2 SE class that inherits from GFAL2StorageBase"""
_INPUT_PROTOCOLS = ["file", "root", "srm", "gsiftp"]
_OUTPUT_PROTOCOLS = ["file", "root", "dcap", "gsidcap", "rfio", "srm", "gsiftp"]
def __init__(self, storageName, parameters):
""" """
super(GFAL2_SRM2Storage, self).__init__(storageName, parameters)
self.log = gLogger.getSubLogger("GFAL2_SRM2Storage")
self.log.debug("GFAL2_SRM2Storage.__init__: Initializing object")
self.pluginName = "GFAL2_SRM2"
# This attribute is used to know the file status (OFFLINE,NEARLINE,ONLINE)
self._defaultExtendedAttributes = ["user.status"]
# ##
# Setting the default SRM parameters here. For methods where this
# is not the default there is a method defined in this class, setting
# the proper values and then calling the base class method.
# ##
self.gfal2requestLifetime = gConfig.getValue("/Resources/StorageElements/RequestLifeTime", 100)
self.__setSRMOptionsToDefault()
# This lists contains the list of protocols to ask to SRM to get a URL
# It can be either defined in the plugin of the SE, or as a global option
if "ProtocolsList" in parameters:
self.protocolsList = parameters["ProtocolsList"].split(",")
else:
self.log.debug("GFAL2_SRM2Storage: No protocols provided, using the default protocols.")
self.protocolsList = self.defaultLocalProtocols
self.log.debug("GFAL2_SRM2Storage: protocolsList = %s" % self.protocolsList)
def __setSRMOptionsToDefault(self):
"""Resetting the SRM options back to default"""
self.ctx.set_opt_integer("SRM PLUGIN", "OPERATION_TIMEOUT", self.gfal2Timeout)
if self.spaceToken:
self.ctx.set_opt_string("SRM PLUGIN", "SPACETOKENDESC", self.spaceToken)
self.ctx.set_opt_integer("SRM PLUGIN", "REQUEST_LIFETIME", self.gfal2requestLifetime)
# Setting the TURL protocol to gsiftp because with other protocols we have authorisation problems
# self.ctx.set_opt_string_list( "SRM PLUGIN", "TURL_PROTOCOLS", self.defaultLocalProtocols )
self.ctx.set_opt_string_list("SRM PLUGIN", "TURL_PROTOCOLS", ["gsiftp"])
def _updateMetadataDict(self, metadataDict, attributeDict):
"""Updating the metadata dictionary with srm specific attributes
:param self: self reference
:param dict: metadataDict we want add the SRM specific attributes to
:param dict: attributeDict contains 'user.status' which we then fill in the metadataDict
"""
# 'user.status' is the extended attribute we are interested in
user_status = attributeDict.get("user.status", "")
metadataDict["Cached"] = int("ONLINE" in user_status)
metadataDict["Migrated"] = int("NEARLINE" in user_status)
metadataDict["Lost"] = int(user_status == "LOST")
metadataDict["Unavailable"] = int(user_status == "UNAVAILABLE")
metadataDict["Accessible"] = (
not metadataDict["Lost"] and metadataDict["Cached"] and not metadataDict["Unavailable"]
)
def getTransportURL(self, path, protocols=False):
"""obtain the tURLs for the supplied path and protocols
:param self: self reference
:param str path: path on storage
:param mixed protocols: protocols to use
:returns: Failed dict {path : error message}
Successful dict {path : transport url}
S_ERROR in case of argument problems
"""
res = checkArgumentFormat(path)
if not res["OK"]:
return res
urls = res["Value"]
self.log.debug("GFAL2_SRM2Storage.getTransportURL: Attempting to retrieve tURL for %s paths" % len(urls))
failed = {}
successful = {}
if not protocols:
listProtocols = self.protocolsList
if not listProtocols:
return S_ERROR("GFAL2_SRM2Storage.getTransportURL: No local protocols defined and no defaults found.")
elif isinstance(protocols, six.string_types):
listProtocols = [protocols]
elif isinstance(protocols, list):
listProtocols = protocols
else:
return S_ERROR("getTransportURL: Must supply desired protocols to this plug-in.")
# Compatibility because of castor returning a castor: url if you ask
# for a root URL, and a root: url if you ask for a xroot url...
if "root" in listProtocols and "xroot" not in listProtocols:
listProtocols.insert(listProtocols.index("root"), "xroot")
elif "xroot" in listProtocols and "root" not in listProtocols:
listProtocols.insert(listProtocols.index("xroot") + 1, "root")
if self.protocolParameters["Protocol"] in listProtocols:
successful = {}
failed = {}
for url in urls:
if self.isURL(url)["Value"]:
successful[url] = url
else:
failed[url] = "getTransportURL: Failed to obtain turls."
return S_OK({"Successful": successful, "Failed": failed})
for url in urls:
res = self.__getSingleTransportURL(url, listProtocols)
self.log.debug("res = %s" % res)
if not res["OK"]:
failed[url] = res["Message"]
else:
successful[url] = res["Value"]
return S_OK({"Failed": failed, "Successful": successful})
def __getSingleTransportURL(self, path, protocols=False):
"""Get the tURL from path with getxattr from gfal2
:param self: self reference
:param str path: path on the storage
:returns: S_OK( Transport_URL ) in case of success
S_ERROR( errStr ) in case of a failure
"""
self.log.debug("GFAL2_SRM2Storage.__getSingleTransportURL: trying to retrieve tURL for %s" % path)
if protocols:
self.ctx.set_opt_string_list("SRM PLUGIN", "TURL_PROTOCOLS", protocols)
res = self._getExtendedAttributes(path, attributes=["user.replicas"])
self.__setSRMOptionsToDefault()
if res["OK"]:
return S_OK(res["Value"]["user.replicas"])
errStr = "GFAL2_SRM2Storage.__getSingleTransportURL: Extended attribute tURL is not set."
self.log.debug(errStr, res["Message"])
return res
def getOccupancy(self, *parms, **kws):
"""Gets the GFAL2_SRM2Storage occupancy info.
TODO: needs gfal2.15 because of bugs:
https://its.cern.ch/jira/browse/DMC-979
https://its.cern.ch/jira/browse/DMC-977
It queries the srm interface for a given space token.
Out of the results, we keep totalsize, guaranteedsize, and unusedsize all in B.
"""
if not self.spaceToken:
self.log.info("getOccupancy: SpaceToken not defined for this SE. Falling back to the default getOccupancy.")
return super(GFAL2_SRM2Storage, self).getOccupancy(*parms, **kws)
# Gfal2 extended parameter name to query the space token occupancy
spaceTokenAttr = "spacetoken.description?%s" % self.protocolParameters["SpaceToken"]
# gfal2 can take any srm url as a base.
spaceTokenEndpoint = self.getURLBase(withWSUrl=True)["Value"]
try:
occupancyStr = self.ctx.getxattr(spaceTokenEndpoint, spaceTokenAttr)
try:
occupancyDict = json.loads(occupancyStr)[0]
except ValueError:
# https://its.cern.ch/jira/browse/DMC-977
# a closing bracket is missing, so we retry after adding it
occupancyStr = occupancyStr[:-1] + "}]"
occupancyDict = json.loads(occupancyStr)[0]
# https://its.cern.ch/jira/browse/DMC-979
# We set totalsize to guaranteed size
# (it is anyway true for all the SEs I could test)
occupancyDict["totalsize"] = occupancyDict.get("guaranteedsize", 0)
except (gfal2.GError, ValueError) as e:
errStr = "Something went wrong while checking for spacetoken occupancy."
self.log.verbose(errStr, e.message)
return S_ERROR(getattr(e, "code", errno.EINVAL), "%s %s" % (errStr, repr(e)))
sTokenDict = {}
sTokenDict["Total"] = float(occupancyDict.get("totalsize", "0"))
sTokenDict["Free"] = float(occupancyDict.get("unusedsize", "0"))
sTokenDict["SpaceReservation"] = self.protocolParameters["SpaceToken"]
return S_OK(sTokenDict)
|
DIRACGrid/DIRAC
|
src/DIRAC/Resources/Storage/GFAL2_SRM2Storage.py
|
Python
|
gpl-3.0
| 9,181
|
[
"DIRAC"
] |
be2c10f70a4c1c3516918e6034991540160a232800fe6eaa38e223783cdb5a19
|
import itertools
import numpy as np
import tensor
class Scalar:
def __init__ (self, frequencies, derivatives, closed_time_interval, dtype=float, tau=2.0*np.pi, cos=np.cos, sin=np.sin, double_nonzero_frequency_basis_functions=True):
# NOTE: This is designed to be able to work with any type, including e.g. sympy symbols.
assert len(frequencies.shape) == 1
assert len(derivatives.shape) == 1
assert len(closed_time_interval.shape) == 1
assert frequencies.shape[0] > 0
assert derivatives.shape[0] > 0
assert closed_time_interval.shape[0] >= 2
assert len(frozenset(frequencies)) == len(frequencies), 'frequencies must contain unique values'
assert len(frozenset(derivatives)) == len(derivatives), 'derivatives must contain unique values'
# Period of orbit
self.period = period = closed_time_interval[-1] - closed_time_interval[0]
# Number of frequencies specified
self.F = F = len(frequencies)
# The frequencies of the basis (cos,sin) functions.
self.frequencies = frequencies
# The map giving an index for a valid frequency
self.frequency_index_d = {frequency:i for i,frequency in enumerate(frequencies)}
# Number of derivatives specified
self.D = D = len(derivatives)
# Derivatives requested
self.derivatives = derivatives
# The map giving an index for a valid derivative
self.derivative_index_d = {derivative:i for i,derivative in enumerate(derivatives)}
# Times that the Fourier sum will be sampled at.
self.closed_time_interval = closed_time_interval
# Half-open interval without the right endpoint (the right endpoint defines the period).
# This serves as the discretization of time at which the Fourier sum will be sampled.
# This is a discrete sampling of a fundamental domain of the periodicity.
self.half_open_time_interval = half_open_time_interval = closed_time_interval[:-1]
# Number of time-samples in the fundamental domain
self.T = T = len(half_open_time_interval)
# Compute the deltas between time interval points, which can be used e.g. in integrating
# over the half-open time interval. Note that this is not invariant under a reversal
# of the time interval; TODO: compute a symmetric version of this.
self.half_open_time_interval_deltas = half_open_time_interval_deltas = np.diff(closed_time_interval)
# The shape of the coefficients tensor it expects for Scalar.sample.
self.fourier_coefficients_shape = (F,2)
# This is the linear transform taking Fourier coefficients and producing a time-sampled curve.
# I.e. the linear map from frequency domain to time domain.
# 2 indicates that there are two coefficients for each (cos,sin) pair
# This tensor is indexed as fourier_tensor[t,d,f,c]
self.fourier_tensor = fourier_tensor = np.ndarray((T,D,F,2), dtype=dtype)
for t,time in enumerate(half_open_time_interval):
self.fourier_tensor[t,:,:,:] = Scalar._compute_partial_fourier_tensor(derivatives, frequencies, period, time, dtype, tau, cos, sin)
# This is the linear transform projecting a time-sampled curve into the space of Fourier sums spanned
# by the given frequencies. This tensor is indexed as inverse_fourier_tensor[f,c,t].
self.inverse_fourier_tensor = Scalar._compute_inverse_fourier_tensor(frequencies, period, half_open_time_interval, half_open_time_interval_deltas, dtype, tau, cos, sin, double_nonzero_frequency_basis_functions)
def sample (self, coefficient_tensor, at_t=None, dtype=float):
assert coefficient_tensor.shape == self.fourier_coefficients_shape, 'expected {0} but got {1}'.format(coefficient_tensor.shape)
if at_t == None:
return tensor.contract('tdfc,fc', self.fourier_tensor, coefficient_tensor, output='td', dtype=dtype)
else:
return tensor.contract('dfc,fc', self.fourier_tensor[t,:,:,:], coefficient_tensor, output='td', dtype=dtype)
def index_of_frequency (self, frequency):
return self.frequency_index_d[frequency]
def index_of_derivative (self, derivative):
return self.derivative_index_d[derivative]
@staticmethod
def _compute_partial_fourier_tensor (derivatives, frequencies, period, time, dtype, tau, cos, sin):
"""
Computes the linear transformation taking Fourier coefficients and returning the X-jet of the corresponding time-series signal.
In this case, the X-jet can be any set of derivatives (e.g. the 0th, or the 0th and 1st, or the 1st and 3rd, or any combination).
"""
D = len(derivatives)
F = len(frequencies)
# 2 indicates that there are two coefficients; one for each element of a (cos,sin) pair
partial_fourier_tensor = np.ndarray((D,F,2), dtype=dtype)
omega = tau/period
# The expression `omega_freq = omega*frequencies` sometimes produced a floating point constant multiple
# for some reason, but the following expression seems to work more reliably.
omega_freq = np.array([omega*frequency for frequency in frequencies])
# print 'omega:', omega, 'type(omega):', type(omega), 'frequencies:', frequencies, 'frequencies.dtype:', frequencies.dtype, 'omega_freq:', omega_freq
cos_sin_omega_freq = np.array([[cos(of*time), sin(of*time)] for of in omega_freq])
for d,derivative in enumerate(derivatives):
omega_freq__deriv = omega_freq**derivative
partial_fourier_tensor[d,:,0] = (-1)**((derivative+1)//2) * omega_freq__deriv * cos_sin_omega_freq[:,derivative%2]
partial_fourier_tensor[d,:,1] = (-1)**(derivative//2) * omega_freq__deriv * cos_sin_omega_freq[:,(derivative+1)%2]
# print 'partial_fourier_tensor[0,0,:]:'
# print partial_fourier_tensor[0,0,:]
return partial_fourier_tensor
@staticmethod
def _compute_inverse_fourier_tensor (frequencies, period, half_open_time_interval, half_open_time_interval_deltas, dtype, tau, cos, sin, double_nonzero_frequency_basis_functions):
"""
Computes the linear transformation taking a time-series signal and returning its Fourier coefficients for the specified frequencies.
"""
assert len(half_open_time_interval) == len(half_open_time_interval_deltas)
T = len(half_open_time_interval)
F = len(frequencies)
# print 'period:', period, 'half_open_time_interval:', half_open_time_interval, 'half_open_time_interval_deltas:', half_open_time_interval_deltas
inverse_fourier_tensor = np.ndarray((F,2,T), dtype=dtype)
omega = tau/period
for f,frequency in enumerate(frequencies):
for t,(time,delta) in enumerate(itertools.izip(half_open_time_interval,half_open_time_interval_deltas)):
inverse_fourier_tensor[f,0,t] = cos(omega*frequency*time)*delta/period
inverse_fourier_tensor[f,1,t] = sin(omega*frequency*time)*delta/period
if double_nonzero_frequency_basis_functions:
# Multiply the nonzero frequencies' components by the normalizing factor 2.
inverse_fourier_tensor[frequencies!=0,:,:] *= 2
# print 'inverse_fourier_tensor:'
# print inverse_fourier_tensor
return inverse_fourier_tensor
@staticmethod
def test1 ():
import symbolic as sy
import sympy as sp
import sys
sys.stdout.write('fourier_parameterization.Scalar.test1()\n')
def lerp (start, end, count):
for i in xrange(count):
yield (start*(count-1-i) + end*i)/(count-1)
D = 5
frequencies = np.array([0,1,2,3,4,5])
derivatives = np.array(range(D))
period = sp.symbols('period')
tau = 2*sp.pi
T = 32
closed_time_interval = np.array(list(lerp(0, period, T+1)))
fourier_parameterization = Scalar(frequencies, derivatives, closed_time_interval, dtype=object, tau=tau, cos=sp.cos, sin=sp.sin)
t = sp.symbols('t')
coefficients = sy.tensor('c', (len(frequencies),2))
basis_functions = np.array([[sp.cos(tau/period*f*t), sp.sin(tau/period*f*t)] for f in frequencies])
f = np.dot(coefficients.flat, basis_functions.flat)
s_sampled = fourier_parameterization.sample(coefficients, dtype=object)
assert s_sampled.shape == (T,D)
expand_vec = np.vectorize(sp.expand)
for d,derivative in enumerate(derivatives):
sys.stdout.write('testing {0}th derivative...'.format(d))
dth_derivative_of_f_sampled = np.array([f.diff(t,d).subs({t:sampled_t}) for sampled_t in fourier_parameterization.half_open_time_interval])
assert all(expand_vec(dth_derivative_of_f_sampled - s_sampled[:,d]) == 0)
sys.stdout.write('passed.\n')
@staticmethod
def test2 ():
import matplotlib.pyplot as plt
import scipy.linalg
import symbolic as sy
import sympy as sp
import sys
import warnings
warnings.filterwarnings('ignore', module='matplotlib')
sys.stdout.write('fourier_parameterization.Scalar.test2()\n')
def lerp (start, end, count):
for i in xrange(count):
yield (start*(count-1-i) + end*i)/(count-1)
def test_spectrum_endomorphism (frequencies):
F = len(frequencies)
assert F > 0
sys.stdout.write('test_spectrum_endomorphism(frequencies={0}) ... '.format(frequencies))
D = 1
derivatives = np.array(range(D))
period = sp.symbols('period')
tau = 2*sp.pi
# By the Nyquist theorem, the number of time samples must be greater than twice the highest frequency.
# But also we need there to be at least as many dimensions in the signal vector space as there
# are in the spectrum space (or the spectrum_endomorphism can't hope to be the identity).
T = max(2*F-np.sum(frequencies==0), 2*np.max(frequencies)+2) # TODO: Figure out why `np.max(frequencies)*2+2` works and `np.max(frequencies)*2+1` doesn't.
closed_time_interval = np.array(list(lerp(0, period, T+1)))
fourier_parameterization = Scalar(frequencies, derivatives, closed_time_interval, dtype=object, tau=tau, cos=sp.cos, sin=sp.sin)
spectrum_endomorphism = tensor.contract('tdfc,FCt', fourier_parameterization.fourier_tensor, fourier_parameterization.inverse_fourier_tensor, output='FCdfc', dtype=object)
assert spectrum_endomorphism.shape == (F,2,D,F,2)
spectrum_endomorphism = spectrum_endomorphism[:,:,0,:,:]
spectrum_endomorphism = np.vectorize(sp.simplify)(spectrum_endomorphism)
cos_coefficient_endomorphism = spectrum_endomorphism[:,0,:,0]
cos_to_sin_coefficient_morphism = spectrum_endomorphism[:,0,:,1]
sin_to_cos_coefficient_morphism = spectrum_endomorphism[:,1,:,0]
sin_coefficient_endomorphism = spectrum_endomorphism[:,1,:,1]
# print 'frequencies:'
# print frequencies
# print 'T:', T
# print 'cos_coefficient_endomorphism:'
# print cos_coefficient_endomorphism
# print 'cos_to_sin_coefficient_morphism:'
# print cos_to_sin_coefficient_morphism
# print 'sin_to_cos_coefficient_morphism:'
# print sin_to_cos_coefficient_morphism
# print 'sin_coefficient_endomorphism:'
# print sin_coefficient_endomorphism
assert np.all(cos_coefficient_endomorphism == np.eye(*cos_coefficient_endomorphism.shape, dtype=int))
assert np.all(cos_to_sin_coefficient_morphism == 0)
assert np.all(sin_to_cos_coefficient_morphism == 0)
expected_diagonal = np.array(map(lambda f:1 if f!=0 else 0, frequencies))
assert np.all(sin_coefficient_endomorphism == np.diag(expected_diagonal))
sys.stdout.write('passed.\n')
def test_signal_endomorphism (T):
assert T >= 1
sys.stdout.write('test_signal_endomorphism(T={0}) ... '.format(T))
D = 1
derivatives = np.array(range(D)) # Only use 0th derivative (i.e. position)
# Frequencies must be less than T//2, otherwise they'll count double because of aliasing. The
# frequency T//2 in particular will just show up as 0, because it has nodes at every sample.
highest_frequency = (T-1)//2
frequencies = np.array(range(highest_frequency+1))
# period = sp.symbols('period')
# tau = 2*sp.pi
period = 10.0 # arbitrary
tau = 2*np.pi
# closed_time_interval = np.array(list(lerp(0, period, T+1)))
closed_time_interval = np.linspace(0.0, period, T+1)
fourier_parameterization = Scalar(frequencies, derivatives, closed_time_interval, dtype=float, tau=tau, cos=np.cos, sin=np.sin)
# print ''
# # print 'fourier_parameterization.fourier_tensor:'
# for t in xrange(T):
# print 't:', t, 'time:', closed_time_interval[t]
# print 'fourier_parameterization.fourier_tensor[{0},0,f,c]:'.format(closed_time_interval[t])
# print fourier_parameterization.fourier_tensor[t,0,:,:]
# print 'fourier_parameterization.inverse_fourier_tensor[f,c,{0}]:'.format(closed_time_interval[t])
# print fourier_parameterization.inverse_fourier_tensor[:,:,t]
# print ''
# print ''
# signal_endomorphism = tensor.contract('tdfc,fcT', fourier_parameterization.fourier_tensor, fourier_parameterization.inverse_fourier_tensor, output='tdT', dtype=object)
signal_endomorphism = np.einsum('tdfc,fcT->tdT', fourier_parameterization.fourier_tensor, fourier_parameterization.inverse_fourier_tensor)
assert signal_endomorphism.shape == (T,D,T)
signal_endomorphism = signal_endomorphism[:,0,:]
# signal_endomorphism = np.vectorize(sp.simplify)(signal_endomorphism)
# The eigenvectors are the columns.
eigenvalues,eigenvectors = scipy.linalg.eigh(signal_endomorphism)
# print 'signal_endomorphism:'
# print signal_endomorphism
# print 'eigenvalues of signal_endomorphism:'
# print eigenvalues
expected_zero_eigenvalues = 1 if T%2==0 else 0
actual_zero_eigenvalues = np.sum(np.abs(eigenvalues) < 1.0e-12)
expected_one_eigenvalues = T - expected_zero_eigenvalues
actual_one_eigenvalues = np.sum(np.abs(eigenvalues-1) < 1.0e-12)
assert actual_zero_eigenvalues == expected_zero_eigenvalues, 'expected {0} eigenvalues with value [near] 0, but got {1}'.format(expected_zero_eigenvalues, actual_zero_eigenvalues)
assert actual_one_eigenvalues == expected_one_eigenvalues, 'expected {0} eigenvalues with value [near] 1, but got {1}'.format(expected_one_eigenvalues, actual_one_eigenvalues)
sys.stdout.write('passed.\n')
if actual_zero_eigenvalues == 1:
zero_eigenvalue_filter = np.abs(eigenvalues) < 1.0e-12
assert sum(zero_eigenvalue_filter) == 1
zero_eigenvalue_index = list(zero_eigenvalue_filter).index(True)
assert np.abs(eigenvalues[zero_eigenvalue_index]) < 1.0e-12
return {
'T':T,
'period':period,
'highest_frequency':highest_frequency,
'signal_domain':fourier_parameterization.half_open_time_interval,
'eigenvector':eigenvectors[:,zero_eigenvalue_index],
}
else:
return None
if True:
for F in xrange(1,6):
test_spectrum_endomorphism(np.array(range(F+1)))
test_spectrum_endomorphism(np.array([0,2]))
test_spectrum_endomorphism(np.array([0,3]))
test_spectrum_endomorphism(np.array([1]))
test_spectrum_endomorphism(np.array([2]))
test_spectrum_endomorphism(np.array([1,3,5]))
test_spectrum_endomorphism(np.array([0,3,4]))
if True:
zero_eigenvector_dv = []
for T in xrange(4,16):
d = test_signal_endomorphism(T)
if d is not None:
zero_eigenvector_dv.append(d)
row_count = len(zero_eigenvector_dv)
col_count = 1
fig,axes = plt.subplots(row_count, col_count, squeeze=False, figsize=(5*col_count, 3*row_count))
for zero_eigenvector_index,zero_eigenvector_d in enumerate(zero_eigenvector_dv):
axis = axes[zero_eigenvector_index][0]
axis.set_title('zero eigenvector for T: {0}\nhighest frequency: {1}'.format(zero_eigenvector_d['T'], zero_eigenvector_d['highest_frequency']))
signal_domain = zero_eigenvector_d['signal_domain']
eigenvector = zero_eigenvector_d['eigenvector']
axis.plot(signal_domain, eigenvector)
axis.set_xlim(0.0, zero_eigenvector_d['period'])
fig.tight_layout()
filename = 'fourier_parameterization.scalar.test2.png'
plt.savefig(filename, bbox_inches='tight')
print 'wrote "{0}"'.format(filename)
plt.close(fig)
@staticmethod
def test3 ():
"""
Compute the Fourier coefficients of a given function and plot the resampled function.
"""
import matplotlib.pyplot as plt
import scipy.signal
import sys
def process_function (axis_row, closed_time_interval, frequencies, samples):
assert len(samples.shape) == 1
assert len(closed_time_interval) == samples.shape[0]+1
derivatives = np.array([0])
p = Scalar(frequencies, derivatives, closed_time_interval)
fc = np.einsum('fct,t->fc', p.inverse_fourier_tensor, samples)
assert fc.shape == (p.F,2)
print 'mode coefficient for frequency 1:', fc[p.index_of_frequency(1)]
reconstructed_samples = np.einsum('tdfc,fc->dt', p.fourier_tensor, fc)
# print('reconstructed_samples.shape:', reconstructed_samples.shape)
assert reconstructed_samples.shape == (1,p.T)
reconstructed_samples = reconstructed_samples[0,:]
max_reconstruction_error = np.max(np.abs(reconstructed_samples - samples))
assert len(axis_row) >= 3
axis = axis_row[0]
axis.set_title('original function')
axis.plot(p.half_open_time_interval, samples)
axis = axis_row[1]
axis.set_title('log abs of Fourier coefficients')
axis.semilogy(p.frequencies, np.linalg.norm(fc, axis=1))
axis = axis_row[2]
axis.set_title('reconstructed function\nmax reconstruction error: {0}'.format(max_reconstruction_error))
axis.plot(p.half_open_time_interval, reconstructed_samples)
period = 10.0
closed_time_interval = np.linspace(0.0, period, 1000)
frequencies = np.linspace(0, 10, 11, dtype=np.int)
row_count = 2
col_count = 3
fig,axis_row_v = plt.subplots(row_count, col_count, squeeze=False, figsize=(10*col_count,10*row_count))
process_function(
axis_row_v[0],
closed_time_interval,
frequencies,
np.array([0.3+np.cos(2*np.pi/period*t) for t in closed_time_interval[:-1]])
)
process_function(
axis_row_v[1],
closed_time_interval,
frequencies,
scipy.signal.gaussian(len(closed_time_interval)-1, len(closed_time_interval)//10)
)
filename = 'fourier_parameterization.scalar.test3.png'
plt.savefig(filename, bbox_inches='tight')
print 'wrote "{0}"'.format(filename)
plt.close(fig)
@staticmethod
def run_all_unit_tests ():
Scalar.test1()
Scalar.test2()
Scalar.test3()
if __name__ == '__main__':
Scalar.run_all_unit_tests()
|
vdods/heisenberg
|
attic/library/fourier_parameterization/scalar.py
|
Python
|
mit
| 20,439
|
[
"Gaussian"
] |
17f113d809507a74bb1027f92fd9336c06359618e59b8797e4c4d399469e48d9
|
import subprocess as sp
import os
import numpy as np
if __name__=="__main__":
stretchfmt = """
log cylinder-stretch-r_{0}-f_{2}-t_{3}.log
units metal
atom_style atomic
read_restart cylinder_{0}.restart
change_box all boundary p p s
region TOPREG block -99999 99999 -99999 99999 {1} 99999
region BOTREG block -99999 99999 -99999 99999 -99999 -{1}
group TOPAT region TOPREG
group BOTAT region BOTREG
variable TOPSTRESS equal {2}
variable BOTSTRESS equal -{2}
pair_style eam
pair_coeff 1 1 Cu_u3.eam
neighbor 0.3 bin
neigh_modify every 20 delay 0 check yes
timestep 0.0005
compute ep all pe/atom
compute st all stress/atom
dump mydump all custom 1000 cylinder-stretch-r_{0}-f_{2}-t_{3}.dump type x y z c_ep c_st[1] c_st[2] c_st[3] c_st[4] c_st[5] c_st[6]
dump_modify mydump append yes
thermo 100
thermo_style custom step temp pe etotal press vol
thermo_modify line one flush yes format 1 "ec %8lu" format float "%20.10g"
fix MYFIX all nve
fix MYTFIX all temp/berendsen 300.0 300.0 0.1
fix MYCMASS all recenter INIT INIT INIT
fix MYTOPFFIX TOPAT addforce 0.0 0.0 v_TOPSTRESS
fix MYBOTFFIX BOTAT addforce 0.0 0.0 v_BOTSTRESS
run {3}
"""
filenamefmt = "cylinder-stretch-r_{0}-f_{1}-t_{2}.{3}"
forces = [0.001,0.005,0.009,0.013,0.017]
forcedist = 100.0
time = 100000
lammps_program = 'lammps-daily'
#delta = (lenmult - 1.0)/nsteps
#stretch = stretchfmt.format(1.0+delta, 45)
for r in np.arange(5,31,5):
for force in forces:
print 'Running %d timesteps of stretch for cylinder with r=%d nm with f=%f.' % (time,r,force)
filename = filenamefmt.format(r,force,time,'in')
dumpfile = filenamefmt.format(r,force,time,'dump')
if os.path.exists(dumpfile):
print 'Dumpfile exists, will not run.'
else:
config = stretchfmt.format(r, forcedist, force, time)
with open(filename, 'w') as f:
f.write(config)
#for i in range(0,nsteps):
# f.write(stretch)
stdout = filenamefmt.format(r,force,time,'stdout')
with open(filename, 'r') as f:
with open(stdout, 'w') as g:
cmd2 = sp.call(lammps_program, stdin=f, stdout=g)
|
simo-tuomisto/portfolio
|
Computational Nanoscience 2013 - Final project/Code/run_stretch.py
|
Python
|
mit
| 2,129
|
[
"LAMMPS"
] |
ad53b85a7018b3762b5171050cf44fdeeccced49371a37baa3c92c0d3368972e
|
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import unittest
import warnings
from pymatgen.core.bonds import (
CovalentBond,
get_bond_length,
get_bond_order,
obtain_all_bond_lengths,
)
from pymatgen.core.periodic_table import Element
from pymatgen.core.sites import Site
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "Jul 26, 2012"
class CovalentBondTest(unittest.TestCase):
def setUp(self):
warnings.simplefilter("ignore")
def tearDown(self):
warnings.simplefilter("default")
def test_length(self):
site1 = Site("C", [0, 0, 0])
site2 = Site("H", [0, 0.7, 0.6])
self.assertAlmostEqual(CovalentBond(site1, site2).length, 0.92195444572928864)
def test_get_bond_order(self):
site1 = Site("C", [0, 0, 0])
site2 = Site("H", [0, 0, 1.08])
self.assertAlmostEqual(CovalentBond(site1, site2).get_bond_order(), 1)
bond = CovalentBond(Site("C", [0, 0, 0]), Site("Br", [0, 0, 2]))
self.assertAlmostEqual(bond.get_bond_order(0.5, 1.9), 0.894736842105263)
def test_is_bonded(self):
site1 = Site("C", [0, 0, 0])
site2 = Site("H", [0, 0, 1])
self.assertTrue(CovalentBond.is_bonded(site1, site2))
site2 = Site("H", [0, 0, 1.5])
self.assertFalse(CovalentBond.is_bonded(site1, site2))
site1 = Site("U", [0, 0, 0])
self.assertRaises(ValueError, CovalentBond.is_bonded, site1, site2)
self.assertTrue(CovalentBond.is_bonded(site1, site2, default_bl=2))
def test_str(self):
site1 = Site("C", [0, 0, 0])
site2 = Site("H", [0, 0.7, 0.6])
self.assertIsNotNone(CovalentBond(site1, site2))
class FuncTest(unittest.TestCase):
def test_get_bond_length(self):
self.assertAlmostEqual(get_bond_length("C", "C", 1), 1.54)
self.assertAlmostEqual(get_bond_length("C", "C", 2), 1.34)
self.assertAlmostEqual(get_bond_length("C", "H", 1), 1.08)
self.assertEqual(get_bond_length("C", "H", 2), 0.95)
self.assertAlmostEqual(get_bond_length("C", "Br", 1), 1.85)
def test_obtain_all_bond_lengths(self):
self.assertDictEqual(obtain_all_bond_lengths("C", "C"), {1.0: 1.54, 2.0: 1.34, 3.0: 1.2})
self.assertRaises(ValueError, obtain_all_bond_lengths, "Br", Element("C"))
self.assertDictEqual(obtain_all_bond_lengths("C", Element("Br"), 1.76), {1: 1.76})
bond_lengths_dict = obtain_all_bond_lengths("C", "N")
bond_lengths_dict[4] = 999
self.assertDictEqual(obtain_all_bond_lengths("C", "N"), {1.0: 1.47, 2.0: 1.3, 3.0: 1.16})
def test_get_bond_order(self):
self.assertAlmostEqual(get_bond_order("C", "C", 1), 3)
self.assertAlmostEqual(get_bond_order("C", "C", 1.2), 3)
self.assertAlmostEqual(get_bond_order("C", "C", 1.25), 2.642857142857143)
self.assertAlmostEqual(get_bond_order("C", "C", 1.34), 2)
self.assertAlmostEqual(get_bond_order("C", "C", 1.4), 1.7) # bond length in benzene
self.assertAlmostEqual(get_bond_order("C", "C", 1.54), 1)
self.assertAlmostEqual(get_bond_order("C", "C", 2.5), 0)
self.assertAlmostEqual(get_bond_order("C", "C", 9999), 0)
self.assertAlmostEqual(get_bond_order("C", "Br", 1.9, default_bl=1.9), 1)
self.assertAlmostEqual(get_bond_order("C", "Br", 2, default_bl=1.9), 0.7368421052631575)
self.assertAlmostEqual(get_bond_order("C", "Br", 1.9, tol=0.5, default_bl=1.9), 1)
self.assertAlmostEqual(get_bond_order("C", "Br", 2, tol=0.5, default_bl=1.9), 0.894736842105263)
self.assertRaises(ValueError, get_bond_order, "C", "Br", 1.9)
self.assertAlmostEqual(get_bond_order("N", "N", 1.25), 2)
if __name__ == "__main__":
unittest.main()
|
vorwerkc/pymatgen
|
pymatgen/core/tests/test_bonds.py
|
Python
|
mit
| 3,942
|
[
"pymatgen"
] |
53d35220b61cc9ade813c5699bbd3cebd14189d59f7da7262805b27a49a02230
|
from . import qndispatch as dispatch
try:
basestring
except NameError:
basestring = str
class CodeGenException(Exception):
pass
class CodeGenIndentException(CodeGenException):
pass
class NotImplementedException(Exception):
pass
class Module(object):
"""Outermost Code block representing a Python Module.
May include a main block
"""
def __init__(self, main=False):
self.has_main = main
self.main_body = []
self.content = []
class ForLoop(object):
def __init__(self, pointer, iterable, content=None):
self.pointer = pointer
self.iterable = iterable
if content is not None:
self.content = content
else:
self.content = []
class IfStatement(object):
def __init__(self, clause, true_content=None, false_content=None):
self.clause = clause
if true_content is not None:
self.true_content = true_content
else:
self.true_content = []
if false_content is not None:
self.false_content = false_content
else:
self.false_content = []
class Function(object):
def __init__(self, name, args=None, content=None):
self.name = name
if args is not None:
self.args = args
else:
self.args = []
if content is not None:
self.content = content
else:
self.content = []
class CallStatement(object):
def __init__(self, func, args):
self.func = func
self.args = args
class Assignment(object):
def __init__(self, target, operator, expression):
self.target = target
self.operator = operator
self.expression = expression
class Statement(object):
"""Generic statement.
To be overridden.
"""
def get(self):
raise NotImplementedException
def fix(self):
raise NotImplementedException
class Class(object):
def __init__(self, name, super=None, content=None):
self.name = name
if super:
self.super = super
else:
self.super = ['object']
if content:
self.content = content
else:
self.content = []
class Method(object):
def __init__(self, name, args=None, content=None):
self.name = name
self.args = []
if args is not None:
self.args = args
if content is not None:
self.content = content
else:
self.content = []
class FixGenerator(object):
def __init__(self):
pass
def visit_block(self, block):
fixed = []
for stmt in block:
if isinstance(stmt, str):
fixed.append(stmt)
continue
if isinstance(stmt, list):
fixed.append(self.visit_args(list))
continue
if callable(stmt):
fixed.append(stmt())
continue
fixed.append(self.visit(stmt))
return fixed
def visit_args(self, args):
return [self.visit_expr(arg) for arg in args]
def visit_expr(self, expr):
if isinstance(expr, str):
return expr
if isinstance(expr, list):
return self.visit_args(expr)
if callable(expr):
return expr()
return self.visit(expr)
def generate(self, node):
return self.visit(node)
@dispatch.on('node')
def visit(self, node):
pass
@visit.when(Module)
def visit(self, node):
m = Module(node.has_main)
m.content = self.visit_block(node.content)
m.main_body = self.visit_block(node.main_body)
return m
@visit.when(Statement)
def visit(self, node):
return node.fix()
@visit.when(CallStatement)
def visit(self, node):
stmt = CallStatement(node.func,
self.visit_args(node.args))
return stmt
@visit.when(Function)
def visit(self, node):
func = Function(node.name)
func.args = self.visit_args(node.args)
func.content = self.visit_block(node.content)
return func
@visit.when(Class)
def visit(self, node):
c = Class(node.name)
c.super = self.visit_args(node.super)
c.content = self.visit_block(node.content)
return c
@visit.when(Method)
def visit(self, node):
m = Method(node.name)
m.args = self.visit_args(node.args)
m.content = self.visit_block(node.content)
return m
@visit.when(IfStatement)
def visit(self, node):
stmt = IfStatement(node.clause)
stmt.true_content = self.visit_block(node.true_content)
stmt.false_content = self.visit_block(node.false_content)
return stmt
@visit.when(ForLoop)
def visit(self, node):
stmt = ForLoop(node.pointer, node.iterable,
self.visit_block(node.content))
return stmt
@visit.when(Assignment)
def visit(self, node):
stmt = Assignment(
node.target,
node.operator,
self.visit_block(
node.expression))
return stmt
class CodeGenerator(object):
def __init__(self):
pass
def generate(self, node):
code = self.visit(0, node)
return "\n".join(code)
def code(self, depth, line):
code = []
for i in range(depth):
code.append(' ')
if isinstance(line, list):
line = "".join(line)
code.append(line)
return "".join(code)
def visit_block(self, depth, block):
if len(block) == 0:
return [self.code(depth+1, 'pass')]
content = []
for node in block:
if isinstance(node, str):
content.append(self.code(depth+1, node))
continue
if callable(node):
content.append(self.code(depth+1, node()))
continue
content += self.visit(depth+1, node)
return content
def visit_args(self, args):
content = []
for arg in args:
if isinstance(arg, str):
content.append(self.code(0, arg))
continue
if isinstance(arg, list):
content.append("".join(self.visit_args(arg)))
continue
if callable(arg):
content.append(self.code(0, arg()))
continue
content += self.visit(0, arg)
return content
@dispatch.on('node')
def visit(self, depth, node):
"""Generic visit function."""
return []
@visit.when(Statement)
def visit(self, depth, node):
return [self.code(depth, node.get())]
@visit.when(Module)
def visit(self, depth, node):
if depth != 0:
raise CodeGenIndentException()
content = []
for n in node.content:
if isinstance(n, str):
content.append(self.code(depth, n))
continue
content += self.visit(depth, n)
if node.has_main:
content.append(self.code(depth, 'if __name__ == "__main__":'))
content += self.visit_block(depth, node.main_body)
return content
@visit.when(ForLoop)
def visit(self, depth, node):
iterable = " ".join(self.visit_args(node.iterable))
line = "".join(["for ", node.pointer, " in ", iterable, ":"])
content = [self.code(depth, line)]
content += self.visit_block(depth, node.content)
return content
@visit.when(IfStatement)
def visit(self, depth, node):
content = []
content.append(self.code(depth, ["if ", node.clause, ":"]))
content += self.visit_block(depth, node.true_content)
content.append(self.code(depth, "else:"))
content += self.visit_block(depth, node.false_content)
return content
@visit.when(Function)
def visit(self, depth, node):
if node.args:
args = ", ".join(node.args)
else:
args = ""
fun = "".join(['def ', node.name, '(', args, '):'])
content = [self.code(depth, fun)]
content += self.visit_block(depth, node.content)
return content
@visit.when(Class)
def visit(self, depth, node):
superclasses = ", ".join(node.super)
c = "".join(['class ', node.name, '(', superclasses, '):'])
content = [self.code(depth, c)]
content += self.visit_block(depth, node.content)
return content
@visit.when(Method)
def visit(self, depth, node):
if node.args:
args = ", ".join(["self"] + node.args)
else:
args = "self"
fun = ''.join(['def ', node.name, '(', args, '):'])
content = [self.code(depth, fun)]
content += self.visit_block(depth, node.content)
return content
@visit.when(CallStatement)
def visit(self, depth, node):
args = ", ".join(self.visit_args(node.args))
if isinstance(node.func, basestring):
fun = "".join([node.func, '(', args, ')'])
else:
fun = "".join([node.func.name, '(', args, ')'])
return [self.code(depth, fun)]
@visit.when(Assignment)
def visit(self, depth, node):
code = [node.target, node.operator]
if(len(node.expression) > 0):
code += map(
lambda x: x.strip(),
self.visit_block(0,
node.expression))
return [self.code(depth, " ".join(code))]
|
myint/pyfuzz
|
pygen/cgen.py
|
Python
|
bsd-3-clause
| 9,736
|
[
"VisIt"
] |
21b0ee7f0810e71257c47464ae7d5f28dfee6485b4681cba0f7c3f2e168e7ef7
|
from stringhelpers import *
import unittest
class Test(unittest.TestCase):
def setUp(self):
self.random_string = random_string()
self.random_string_password_safe =\
random_string(password_safe=True, length=12)
def test_upcase(self):
self.assertEqual(upcase("down here"), "DOWN HERE")
def test_upcase(self):
self.assertEqual(downcase("UP HERE"), "up here")
def test_upcase_first_letter(self):
self.assertEqual(upcase_first_letter("lorem iPsum"), "Lorem iPsum")
def test_reverse(self):
self.assertEqual(reverse(u'esrever'), "reverse")
def test_reverse_order(self):
self.assertEqual(reverse_order("one two three"), "three two one")
def test_count_items(self):
self.assertEqual(count_items('Now or never'), 3)
def test_camelize(self):
self.assertEqual(camelize("a lizard that slithers"),
"A Lizard That Slithers")
def test_list_to_string(self):
self.assertEqual(list_to_string(['Apple', 'Microsoft', 'Sony']),
"Apple, Microsoft, Sony")
def test_truncate(self):
self.assertEqual(truncate("A Mystery Easy to Take for Granted",
length=9), "A Mystery...")
self.assertEqual(truncate("A Lizard That Slithers"),
"A Lizard That S...")
def test_random_string(self):
self.assertTrue(len(self.random_string) == 6 and
len(self.random_string_password_safe) == 12)
r = "^[aA1bB2cC3dD4eE5fF6gG7hH8iI9jJkKlLmMnNpPqQrRsStTuUvVwWxXyYzZ]*$"
match = re.match(r, self.random_string_password_safe)
self.assertTrue(match, "%s is not password safe" %
self.random_string_password_safe)
def test_dasherize(self):
self.assertEqual(dasherize("singing_in_the rain"),
"singing-in-the-rain")
def test_humanize(self):
self.assertEqual(humanize("summer_08-pictures.tar.gz"),
"summer 08 pictures")
def test_flatten(self):
def checkEqual(L1, L2):
return len(L1) == len(L2) and sorted(L1) == sorted(L2)
self.assertTrue(checkEqual(
flatten(["one", ["one", ["two", "three"]], "three"]),
["one", "one", "two", "three", "three"]))
self.assertTrue(checkEqual(
flatten(["one", ["one", ["two", "three"]], "three"],
remove_duplicates=True), ['one', 'two', 'three']))
def test_in_list(self):
self.assertEqual(in_list("one", ["one", "two"]), "one")
def test_ireplace(self):
self.assertEqual(ireplace('w3scHoolS', 'Apple', "Visit W3Schools"),
"Visit Apple")
def test_count(self):
self.assertEqual(count("but", "But what about the BUT ?"), 2)
self.assertEqual(count("But", "But what about the BUT ?",
case_sensitive=True), 1)
def test_odd(self):
self.assertEqual(odd(11), True)
self.assertEqual(odd(11), True)
self.assertEqual(odd("11"), True)
self.assertEqual(odd(10), False)
self.assertEqual(odd("10"), False)
self.assertEqual(odd("x"), False)
self.assertEqual(odd(None), False)
def test_even(self):
self.assertEqual(even(11), False)
self.assertEqual(even("11"), False)
self.assertEqual(even(10), True)
self.assertEqual(even("10"), True)
self.assertEqual(even("x"), False)
self.assertEqual(even(None), False)
def test_strip_slashes(self):
self.assertEqual(strip_slashes('/foo/and/bar//'), "foo/and/bar")
def test_sort(self):
self.assertEqual(sort({"To": b"Two", "En": "One", "Tre": "Three"}),
[("En", "One"), ("To", b"Two"), ("Tre", "Three")])
self.assertEqual(sort({"To": "Two", "En": "One", "Tre": "Three"},
order="descending"), [("Tre", "Three"),
("To", "Two"),
("En", "One")])
self.assertEqual(sort({"b": "Two", "a": "One", "c": "Three"}),
[("a", "One"), ("b", "Two"), ("c", "Three")])
self.assertEqual(sort(("foo", "foobar", "bar")),
["bar", "foo", "foobar"])
self.assertEqual(sort("to sort or not to sort"),
"not or sort sort to to")
self.assertEqual(sort(["Banana", "Orange", "Apple", "Mango"],
order="ascending"),
['Apple', 'Banana', 'Mango', 'Orange'])
self.assertEqual(sort(["Banana", "Orange", "Apple", "Mango"],
order="descending"),
['Orange', 'Mango', 'Banana', 'Apple'])
self.assertEqual(sort("abc,bca"), ",aabbcc")
self.assertEqual(sort("4213"), "1234")
sequences = [
{"sequence1": "foo !!!!! bar",
"sequence2": "bar !!!!! foo",
"longest_result": "!!!!!", "shortest_result": "foo"},
{"sequence1": ("sit", "Lorem", 1234),
"sequence2": "Lorem ipsum dolor sit amet",
"longest_result": "Lorem", "shortest_result": "sit"},
{"sequence1": ["Sed", "ut", "perspiciatis", "unde"],
"sequence2": ("perspiciatis", "lorem ipsum", ""),
"longest_result": "perspiciatis", "shortest_result":
"perspiciatis"},
{"sequence1": [True, False],
"sequence2": [True, "fff"],
"longest_result": True, "shortest_result": True},
{"sequence1": [False, "fafafa", True],
"sequence2": [True, "ffffff"],
"longest_result": True, "shortest_result": True},
{"sequence1": ["Lorem", ["foobar"]],
"sequence2": ["lipsum", ["foobar"], "Lorem"],
"longest_result": ['foobar'], "shortest_result": "Lorem"},
{"sequence1": ["123", 1],
"sequence2": [123, "1"],
"longest_result": None, "shortest_result": None},
{"sequence1": {"Lorem": "Ipsum", "type": "dummy"},
"sequence2": ["Lorem", "is dummy"],
"longest_result": "Lorem", "shortest_result": "Lorem"},
{"sequence1": "Python is a programming language.",
"sequence2": "Python is an interpreted, " +
"object-oriented, high-level programming language",
"longest_result": "programming", "shortest_result": "is"},
{"sequence1": "Python is named after Monty Python",
"sequence2": "What is Python Used For ?",
"longest_result": "Python", "shortest_result": "is"},
{"sequence1": "What is Python?",
"sequence2": "A programming language.",
"longest_result": None, "shortest_result": None},
{"sequence1": ["Python", "lambda"],
"sequence2": ["Pythons", "lambdas"],
"longest_result": None, "shortest_result": None},
{"sequence1": ["Python", "Ruby", "PHP"],
"sequence2": ["PHP", "Python"],
"longest_result": "Python", "shortest_result": "PHP"},
{"sequence1": ("Python", "Interwebs", "Lorem", "Ipsum"),
"sequence2": ["Ipsum", "Python", "Ruby", "Interwebs"],
"longest_result": "Interwebs", "shortest_result": "Ipsum"},
{"sequence1": {"name": "Zara", "age": 7},
"sequence2": ["Zara", "name", "age"],
"longest_result": "name", "shortest_result": "age"},
{"sequence1": {"hello": "greeting", "goodbye": "see ya"},
"sequence2": {"ordering": "undefined", "hello":
"Vyrde helsing", "goodbye": "later"},
"longest_result": "goodbye", "shortest_result": "hello"},
{"sequence1": {"hello": "Vyrde helsing", "goodbye": "see ya",
"foo": "bar"},
"sequence2": ["hello", "goodbye", "foo"],
"longest_result": "goodbye", "shortest_result": "foo"},
]
def test_common_sub(self):
lipsum1 = "Lorem Ipsum is simply dummy text of the printing and "\
"typesetting industry."
lipsum2 = "Lorem Ipsum has been the industry's standard dummy "\
"text ever since the 1500s."
self.assertEqual(common_sub(lipsum1, lipsum2),
["Lorem", "Ipsum", "dummy", "text", "the"])
self.assertEqual(common_sub(lipsum1, "dummy text it is"),
["is", "dummy", "text"])
self.assertEqual(common_sub(("Lorem", "Ipsum", "dummy",
"is", "dummy"), lipsum1.split()),
["Lorem", "Ipsum", "dummy", "is", "dummy"])
self.assertEqual(common_sub("asdf", "fdsa"), None)
self.assertEqual(common_sub({"Lorem": "dummy",
"Ipsum": "Dummy text"}, {"Lorem": "dummy",
"Ipsum": "Dummy"}),
{'Lorem': 'dummy'})
# `longest` and `shortest`
for sequence in self.sequences:
longest_sub = common_sub(sequence["sequence1"],
sequence["sequence2"], "longest")
shortest_sub = common_sub(sequence["sequence1"],
sequence["sequence2"], "shortest")
if not getattr(unittest.TestCase, "assertIsInstance", None):
# Py >= 2.6
def assertIsInstance(a, b):
self.assertTrue(isinstance(a, b))
assertIsInstance(longest_sub, type(sequence["longest_result"]))
assertIsInstance(shortest_sub,
type(sequence["shortest_result"]))
else:
# Py <= 2.7 / 3
self.assertIsInstance(longest_sub,
type(sequence["longest_result"]))
self.assertIsInstance(shortest_sub,
type(sequence["shortest_result"]))
self.assertEqual(longest_sub, sequence["longest_result"])
self.assertEqual(shortest_sub,
sequence["shortest_result"])
def test_is_iterable(self):
class Test:
def __iter__(self): return ["foo", "bar"]
def __init__(self): return self
def test(): return [1, 2, 3]
for i in ["stringhelpers", ["a", "b", "c"], ("foo", "bar")]:
self.assertTrue(is_iterable(i))
for i in [1234, Test, test]:
self.assertFalse(is_iterable(i))
def test_substr(self):
self.assertEqual(substr(["One", "To", "Three"], 0, 3),
["One", "To", "Three"])
self.assertEqual(substr(("One", "To", "Three"), 0, 3),
("One", "To", "Three"))
self.assertEqual(substr(["One", "To", "Three"], 0), "One")
self.assertEqual(substr(["One", "To", "Three"], 1), ["One"])
self.assertEqual(substr("asdf", 0), "a")
self.assertEqual(substr("asdf", 1), "a")
self.assertEqual(substr("asdf", 2), "as")
self.assertEqual(substr("asdf", 1, 2), "sdf")
self.assertEqual(substr("asdf", 0, 2), "asdf")
self.assertEqual(substr("asdf", 1.1), None)
self.assertEqual(substr("asdf", 1, 2.1), None)
if __name__ == "__main__":
unittest.main()
|
thomskaf/stringhelpers
|
test_stringhelpers.py
|
Python
|
mit
| 11,602
|
[
"VisIt"
] |
44206ed71ff5dbe55497cca9a641a3ae3a5721ecfc68e5c9cb6cf2c6c7eb65fc
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein, Ant1, Marius van Voorden
#
# This code is subject to the (new) BSD license:
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <organization> nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" Module images2gif
Provides functionality for reading and writing animated GIF images.
Use writeGif to write a series of numpy arrays or PIL images as an
animated GIF. Use readGif to read an animated gif as a series of numpy
arrays.
Note that since July 2004, all patents on the LZW compression patent have
expired. Therefore the GIF format may now be used freely.
Acknowledgements
----------------
Many thanks to Ant1 for:
* noting the use of "palette=PIL.Image.ADAPTIVE", which significantly
improves the results.
* the modifications to save each image with its own palette, or optionally
the global palette (if its the same).
Many thanks to Marius van Voorden for porting the NeuQuant quantization
algorithm of Anthony Dekker to Python (See the NeuQuant class for its
license).
Many thanks to Alex Robinson for implementing the concept of subrectangles,
which (depening on image content) can give a very significant reduction in
file size.
This code is based on gifmaker (in the scripts folder of the source
distribution of PIL)
Usefull links
-------------
* http://tronche.com/computer-graphics/gif/
* http://en.wikipedia.org/wiki/Graphics_Interchange_Format
* http://www.w3.org/Graphics/GIF/spec-gif89a.txt
"""
# todo: This module should be part of imageio (or at least based on)
import os, time
try:
import PIL
from PIL import Image
from PIL.GifImagePlugin import getheader, getdata
except ImportError:
PIL = None
try:
import numpy as np
except ImportError:
np = None
def get_cKDTree():
try:
from scipy.spatial import cKDTree
except ImportError:
cKDTree = None
return cKDTree
# getheader gives a 87a header and a color palette (two elements in a list).
# getdata()[0] gives the Image Descriptor up to (including) "LZW min code size".
# getdatas()[1:] is the image data itself in chuncks of 256 bytes (well
# technically the first byte says how many bytes follow, after which that
# amount (max 255) follows).
def checkImages(images):
""" checkImages(images)
Check numpy images and correct intensity range etc.
The same for all movie formats.
"""
# Init results
images2 = []
for im in images:
if PIL and isinstance(im, PIL.Image.Image):
# We assume PIL images are allright
images2.append(im)
elif np and isinstance(im, np.ndarray):
# Check and convert dtype
if im.dtype == np.uint8:
images2.append(im) # Ok
elif im.dtype in [np.float32, np.float64]:
im = im.copy()
im[im<0] = 0
im[im>1] = 1
im *= 255
images2.append( im.astype(np.uint8) )
else:
im = im.astype(np.uint8)
images2.append(im)
# Check size
if im.ndim == 2:
pass # ok
elif im.ndim == 3:
if im.shape[2] not in [3,4]:
raise ValueError('This array can not represent an image.')
else:
raise ValueError('This array can not represent an image.')
else:
raise ValueError('Invalid image type: ' + str(type(im)))
# Done
return images2
def intToBin(i):
""" Integer to two bytes """
# devide in two parts (bytes)
i1 = i % 256
i2 = int( i/256)
# make string (little endian)
return chr(i1) + chr(i2)
class GifWriter:
""" GifWriter()
Class that contains methods for helping write the animated GIF file.
"""
def getheaderAnim(self, im):
""" getheaderAnim(im)
Get animation header. To replace PILs getheader()[0]
"""
bb = "GIF89a"
bb += intToBin(im.size[0])
bb += intToBin(im.size[1])
bb += "\x87\x00\x00"
return bb
def getImageDescriptor(self, im, xy=None):
""" getImageDescriptor(im, xy=None)
Used for the local color table properties per image.
Otherwise global color table applies to all frames irrespective of
whether additional colors comes in play that require a redefined
palette. Still a maximum of 256 color per frame, obviously.
Written by Ant1 on 2010-08-22
Modified by Alex Robinson in Janurari 2011 to implement subrectangles.
"""
# Defaule use full image and place at upper left
if xy is None:
xy = (0,0)
# Image separator,
bb = '\x2C'
# Image position and size
bb += intToBin( xy[0] ) # Left position
bb += intToBin( xy[1] ) # Top position
bb += intToBin( im.size[0] ) # image width
bb += intToBin( im.size[1] ) # image height
# packed field: local color table flag1, interlace0, sorted table0,
# reserved00, lct size111=7=2^(7+1)=256.
bb += '\x87'
# LZW minimum size code now comes later, begining of [image data] blocks
return bb
def getAppExt(self, loops=float('inf')):
""" getAppExt(loops=float('inf'))
Application extention. This part specifies the amount of loops.
If loops is 0 or inf, it goes on infinitely.
"""
if loops==0 or loops==float('inf'):
loops = 2**16-1
#bb = "" # application extension should not be used
# (the extension interprets zero loops
# to mean an infinite number of loops)
# Mmm, does not seem to work
if True:
bb = "\x21\xFF\x0B" # application extension
bb += "NETSCAPE2.0"
bb += "\x03\x01"
bb += intToBin(loops)
bb += '\x00' # end
return bb
def getGraphicsControlExt(self, duration=0.1, dispose=2):
""" getGraphicsControlExt(duration=0.1, dispose=2)
Graphics Control Extension. A sort of header at the start of
each image. Specifies duration and transparancy.
Dispose
-------
* 0 - No disposal specified.
* 1 - Do not dispose. The graphic is to be left in place.
* 2 - Restore to background color. The area used by the graphic
must be restored to the background color.
* 3 - Restore to previous. The decoder is required to restore the
area overwritten by the graphic with what was there prior to
rendering the graphic.
* 4-7 -To be defined.
"""
bb = '\x21\xF9\x04'
bb += chr((dispose & 3) << 2) # low bit 1 == transparency,
# 2nd bit 1 == user input , next 3 bits, the low two of which are used,
# are dispose.
bb += intToBin( int(duration*100) ) # in 100th of seconds
bb += '\x00' # no transparant color
bb += '\x00' # end
return bb
def handleSubRectangles(self, images, subRectangles):
""" handleSubRectangles(images)
Handle the sub-rectangle stuff. If the rectangles are given by the
user, the values are checked. Otherwise the subrectangles are
calculated automatically.
"""
if isinstance(subRectangles, (tuple,list)):
# xy given directly
# Check xy
xy = subRectangles
if xy is None:
xy = (0,0)
if hasattr(xy, '__len__'):
if len(xy) == len(images):
xy = [xxyy for xxyy in xy]
else:
raise ValueError("len(xy) doesn't match amount of images.")
else:
xy = [xy for im in images]
xy[0] = (0,0)
else:
# Calculate xy using some basic image processing
# Check Numpy
if np is None:
raise RuntimeError("Need Numpy to use auto-subRectangles.")
# First make numpy arrays if required
for i in range(len(images)):
im = images[i]
if isinstance(im, Image.Image):
tmp = im.convert() # Make without palette
a = np.asarray(tmp)
if len(a.shape)==0:
raise MemoryError("Too little memory to convert PIL image to array")
images[i] = a
# Determine the sub rectangles
images, xy = self.getSubRectangles(images)
# Done
return images, xy
def getSubRectangles(self, ims):
""" getSubRectangles(ims)
Calculate the minimal rectangles that need updating each frame.
Returns a two-element tuple containing the cropped images and a
list of x-y positions.
Calculating the subrectangles takes extra time, obviously. However,
if the image sizes were reduced, the actual writing of the GIF
goes faster. In some cases applying this method produces a GIF faster.
"""
# Check image count
if len(ims) < 2:
return ims, [(0,0) for i in ims]
# We need numpy
if np is None:
raise RuntimeError("Need Numpy to calculate sub-rectangles. ")
# Prepare
ims2 = [ims[0]]
xy = [(0,0)]
t0 = time.time()
# Iterate over images
prev = ims[0]
for im in ims[1:]:
# Get difference, sum over colors
diff = np.abs(im-prev)
if diff.ndim==3:
diff = diff.sum(2)
# Get begin and end for both dimensions
X = np.argwhere(diff.sum(0))
Y = np.argwhere(diff.sum(1))
# Get rect coordinates
if X.size and Y.size:
x0, x1 = X[0], X[-1]+1
y0, y1 = Y[0], Y[-1]+1
else: # No change ... make it minimal
x0, x1 = 0, 2
y0, y1 = 0, 2
# Cut out and store
im2 = im[y0:y1,x0:x1]
prev = im
ims2.append(im2)
xy.append((x0,y0))
# Done
#print('%1.2f seconds to determine subrectangles of %i images' %
# (time.time()-t0, len(ims2)) )
return ims2, xy
def convertImagesToPIL(self, images, dither, nq=0):
""" convertImagesToPIL(images, nq=0)
Convert images to Paletted PIL images, which can then be
written to a single animaged GIF.
"""
# Convert to PIL images
images2 = []
for im in images:
if isinstance(im, Image.Image):
images2.append(im)
elif np and isinstance(im, np.ndarray):
if im.ndim==3 and im.shape[2]==3:
im = Image.fromarray(im,'RGB')
elif im.ndim==3 and im.shape[2]==4:
im = Image.fromarray(im[:,:,:3],'RGB')
elif im.ndim==2:
im = Image.fromarray(im,'L')
images2.append(im)
# Convert to paletted PIL images
images, images2 = images2, []
if nq >= 1:
# NeuQuant algorithm
for im in images:
im = im.convert("RGBA") # NQ assumes RGBA
nqInstance = NeuQuant(im, int(nq)) # Learn colors from image
if dither:
im = im.convert("RGB").quantize(palette=nqInstance.paletteImage())
else:
im = nqInstance.quantize(im) # Use to quantize the image itself
images2.append(im)
else:
# Adaptive PIL algorithm
AD = Image.ADAPTIVE
for im in images:
im = im.convert('P', palette=AD, dither=dither)
images2.append(im)
# Done
return images2
def writeGifToFile(self, fp, images, durations, loops, xys, disposes):
""" writeGifToFile(fp, images, durations, loops, xys, disposes)
Given a set of images writes the bytes to the specified stream.
"""
# Obtain palette for all images and count each occurance
palettes, occur = [], []
for im in images:
palette = getheader(im)[1]
if not palette:
palette = PIL.ImagePalette.ImageColor
palettes.append(palette)
for palette in palettes:
occur.append( palettes.count( palette ) )
# Select most-used palette as the global one (or first in case no max)
globalPalette = palettes[ occur.index(max(occur)) ]
# Init
frames = 0
firstFrame = True
for im, palette in zip(images, palettes):
if firstFrame:
# Write header
# Gather info
header = self.getheaderAnim(im)
appext = self.getAppExt(loops)
# Write
fp.write(header.encode('utf-8'))
fp.write(globalPalette)
fp.write(appext.encode('utf-8'))
# Next frame is not the first
firstFrame = False
if True:
# Write palette and image data
# Gather info
data = getdata(im)
imdes, data = data[0], data[1:]
graphext = self.getGraphicsControlExt(durations[frames],
disposes[frames])
# Make image descriptor suitable for using 256 local color palette
lid = self.getImageDescriptor(im, xys[frames])
# Write local header
if (palette != globalPalette) or (disposes[frames] != 2):
# Use local color palette
fp.write(graphext.encode('utf-8'))
fp.write(lid.encode('utf-8')) # write suitable image descriptor
fp.write(palette) # write local color table
fp.write('\x08'.encode('utf-8')) # LZW minimum size code
else:
# Use global color palette
fp.write(graphext.encode('utf-8'))
fp.write(imdes) # write suitable image descriptor
# Write image data
for d in data:
fp.write(d)
# Prepare for next round
frames = frames + 1
fp.write(";".encode('utf-8')) # end gif
return frames
## Exposed functions
def writeGif(filename, images, duration=0.1, repeat=True, dither=False,
nq=0, subRectangles=True, dispose=None):
""" writeGif(filename, images, duration=0.1, repeat=True, dither=False,
nq=0, subRectangles=True, dispose=None)
Write an animated gif from the specified images.
Parameters
----------
filename : string
The name of the file to write the image to.
images : list
Should be a list consisting of PIL images or numpy arrays.
The latter should be between 0 and 255 for integer types, and
between 0 and 1 for float types.
duration : scalar or list of scalars
The duration for all frames, or (if a list) for each frame.
repeat : bool or integer
The amount of loops. If True, loops infinitetely.
dither : bool
Whether to apply dithering
nq : integer
If nonzero, applies the NeuQuant quantization algorithm to create
the color palette. This algorithm is superior, but slower than
the standard PIL algorithm. The value of nq is the quality
parameter. 1 represents the best quality. 10 is in general a
good tradeoff between quality and speed. When using this option,
better results are usually obtained when subRectangles is False.
subRectangles : False, True, or a list of 2-element tuples
Whether to use sub-rectangles. If True, the minimal rectangle that
is required to update each frame is automatically detected. This
can give significant reductions in file size, particularly if only
a part of the image changes. One can also give a list of x-y
coordinates if you want to do the cropping yourself. The default
is True.
dispose : int
How to dispose each frame. 1 means that each frame is to be left
in place. 2 means the background color should be restored after
each frame. 3 means the decoder should restore the previous frame.
If subRectangles==False, the default is 2, otherwise it is 1.
"""
# Check PIL
if PIL is None:
print 'PIL is none'
raise RuntimeError("Need PIL to write animated gif files.")
# Check images
print 'check images'
images = checkImages(images)
# Instantiate writer object
gifWriter = GifWriter()
# Check loops
if repeat is False:
loops = 1
elif repeat is True:
loops = 0 # zero means infinite
else:
loops = int(repeat)
# Check duration
if hasattr(duration, '__len__'):
if len(duration) == len(images):
duration = [d for d in duration]
else:
raise ValueError("len(duration) doesn't match amount of images.")
else:
duration = [duration for im in images]
# Check subrectangles
if subRectangles:
images, xy = gifWriter.handleSubRectangles(images, subRectangles)
defaultDispose = 1 # Leave image in place
else:
# Normal mode
xy = [(0,0) for im in images]
defaultDispose = 2 # Restore to background color.
# Check dispose
if dispose is None:
dispose = defaultDispose
if hasattr(dispose, '__len__'):
if len(dispose) != len(images):
raise ValueError("len(xy) doesn't match amount of images.")
else:
dispose = [dispose for im in images]
# Make images in a format that we can write easy
images = gifWriter.convertImagesToPIL(images, dither, nq)
# Write
fp = open(filename, 'wb')
try:
print 'writing to gif file'
gifWriter.writeGifToFile(fp, images, duration, loops, xy, dispose)
finally:
fp.close()
def readGif(filename, asNumpy=True):
""" readGif(filename, asNumpy=True)
Read images from an animated GIF file. Returns a list of numpy
arrays, or, if asNumpy is false, a list if PIL images.
"""
# Check PIL
if PIL is None:
raise RuntimeError("Need PIL to read animated gif files.")
# Check Numpy
if np is None:
raise RuntimeError("Need Numpy to read animated gif files.")
# Check whether it exists
if not os.path.isfile(filename):
raise IOError('File not found: '+str(filename))
# Load file using PIL
pilIm = PIL.Image.open(filename)
pilIm.seek(0)
# Read all images inside
images = []
try:
while True:
# Get image as numpy array
tmp = pilIm.convert() # Make without palette
a = np.asarray(tmp)
if len(a.shape)==0:
raise MemoryError("Too little memory to convert PIL image to array")
# Store, and next
images.append(a)
pilIm.seek(pilIm.tell()+1)
except EOFError:
pass
# Convert to normal PIL images if needed
if not asNumpy:
images2 = images
images = []
for im in images2:
images.append( PIL.Image.fromarray(im) )
# Done
return images
class NeuQuant:
""" NeuQuant(image, samplefac=10, colors=256)
samplefac should be an integer number of 1 or higher, 1
being the highest quality, but the slowest performance.
With avalue of 10, one tenth of all pixels are used during
training. This value seems a nice tradeof between speed
and quality.
colors is the amount of colors to reduce the image to. This
should best be a power of two.
See also:
http://members.ozemail.com.au/~dekker/NEUQUANT.HTML
License of the NeuQuant Neural-Net Quantization Algorithm
---------------------------------------------------------
Copyright (c) 1994 Anthony Dekker
Ported to python by Marius van Voorden in 2010
NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994.
See "Kohonen neural networks for optimal colour quantization"
in "network: Computation in Neural Systems" Vol. 5 (1994) pp 351-367.
for a discussion of the algorithm.
See also http://members.ozemail.com.au/~dekker/NEUQUANT.HTML
Any party obtaining a copy of these files from the author, directly or
indirectly, is granted, free of charge, a full and unrestricted irrevocable,
world-wide, paid up, royalty-free, nonexclusive right and license to deal
in this software and documentation files (the "Software"), including without
limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons who receive
copies from any such party to do so, with the only requirement being
that this copyright notice remain intact.
"""
NCYCLES = None # Number of learning cycles
NETSIZE = None # Number of colours used
SPECIALS = None # Number of reserved colours used
BGCOLOR = None # Reserved background colour
CUTNETSIZE = None
MAXNETPOS = None
INITRAD = None # For 256 colours, radius starts at 32
RADIUSBIASSHIFT = None
RADIUSBIAS = None
INITBIASRADIUS = None
RADIUSDEC = None # Factor of 1/30 each cycle
ALPHABIASSHIFT = None
INITALPHA = None # biased by 10 bits
GAMMA = None
BETA = None
BETAGAMMA = None
network = None # The network itself
colormap = None # The network itself
netindex = None # For network lookup - really 256
bias = None # Bias and freq arrays for learning
freq = None
pimage = None
# Four primes near 500 - assume no image has a length so large
# that it is divisible by all four primes
PRIME1 = 499
PRIME2 = 491
PRIME3 = 487
PRIME4 = 503
MAXPRIME = PRIME4
pixels = None
samplefac = None
a_s = None
def setconstants(self, samplefac, colors):
self.NCYCLES = 100 # Number of learning cycles
self.NETSIZE = colors # Number of colours used
self.SPECIALS = 3 # Number of reserved colours used
self.BGCOLOR = self.SPECIALS-1 # Reserved background colour
self.CUTNETSIZE = self.NETSIZE - self.SPECIALS
self.MAXNETPOS = self.NETSIZE - 1
self.INITRAD = self.NETSIZE/8 # For 256 colours, radius starts at 32
self.RADIUSBIASSHIFT = 6
self.RADIUSBIAS = 1 << self.RADIUSBIASSHIFT
self.INITBIASRADIUS = self.INITRAD * self.RADIUSBIAS
self.RADIUSDEC = 30 # Factor of 1/30 each cycle
self.ALPHABIASSHIFT = 10 # Alpha starts at 1
self.INITALPHA = 1 << self.ALPHABIASSHIFT # biased by 10 bits
self.GAMMA = 1024.0
self.BETA = 1.0/1024.0
self.BETAGAMMA = self.BETA * self.GAMMA
self.network = np.empty((self.NETSIZE, 3), dtype='float64') # The network itself
self.colormap = np.empty((self.NETSIZE, 4), dtype='int32') # The network itself
self.netindex = np.empty(256, dtype='int32') # For network lookup - really 256
self.bias = np.empty(self.NETSIZE, dtype='float64') # Bias and freq arrays for learning
self.freq = np.empty(self.NETSIZE, dtype='float64')
self.pixels = None
self.samplefac = samplefac
self.a_s = {}
def __init__(self, image, samplefac=10, colors=256):
# Check Numpy
if np is None:
raise RuntimeError("Need Numpy for the NeuQuant algorithm.")
# Check image
if image.size[0] * image.size[1] < NeuQuant.MAXPRIME:
raise IOError("Image is too small")
if image.mode != "RGBA":
raise IOError("Image mode should be RGBA.")
# Initialize
self.setconstants(samplefac, colors)
self.pixels = np.fromstring(image.tostring(), np.uint32)
self.setUpArrays()
self.learn()
self.fix()
self.inxbuild()
def writeColourMap(self, rgb, outstream):
for i in range(self.NETSIZE):
bb = self.colormap[i,0];
gg = self.colormap[i,1];
rr = self.colormap[i,2];
outstream.write(rr if rgb else bb)
outstream.write(gg)
outstream.write(bb if rgb else rr)
return self.NETSIZE
def setUpArrays(self):
self.network[0,0] = 0.0 # Black
self.network[0,1] = 0.0
self.network[0,2] = 0.0
self.network[1,0] = 255.0 # White
self.network[1,1] = 255.0
self.network[1,2] = 255.0
# RESERVED self.BGCOLOR # Background
for i in range(self.SPECIALS):
self.freq[i] = 1.0 / self.NETSIZE
self.bias[i] = 0.0
for i in range(self.SPECIALS, self.NETSIZE):
p = self.network[i]
p[:] = (255.0 * (i-self.SPECIALS)) / self.CUTNETSIZE
self.freq[i] = 1.0 / self.NETSIZE
self.bias[i] = 0.0
# Omitted: setPixels
def altersingle(self, alpha, i, b, g, r):
"""Move neuron i towards biased (b,g,r) by factor alpha"""
n = self.network[i] # Alter hit neuron
n[0] -= (alpha*(n[0] - b))
n[1] -= (alpha*(n[1] - g))
n[2] -= (alpha*(n[2] - r))
def geta(self, alpha, rad):
try:
return self.a_s[(alpha, rad)]
except KeyError:
length = rad*2-1
mid = int(length//2)
q = np.array(list(range(mid-1,-1,-1))+list(range(-1,mid)))
a = alpha*(rad*rad - q*q)/(rad*rad)
a[mid] = 0
self.a_s[(alpha, rad)] = a
return a
def alterneigh(self, alpha, rad, i, b, g, r):
if i-rad >= self.SPECIALS-1:
lo = i-rad
start = 0
else:
lo = self.SPECIALS-1
start = (self.SPECIALS-1 - (i-rad))
if i+rad <= self.NETSIZE:
hi = i+rad
end = rad*2-1
else:
hi = self.NETSIZE
end = (self.NETSIZE - (i+rad))
a = self.geta(alpha, rad)[start:end]
p = self.network[lo+1:hi]
p -= np.transpose(np.transpose(p - np.array([b, g, r])) * a)
#def contest(self, b, g, r):
# """ Search for biased BGR values
# Finds closest neuron (min dist) and updates self.freq
# finds best neuron (min dist-self.bias) and returns position
# for frequently chosen neurons, self.freq[i] is high and self.bias[i] is negative
# self.bias[i] = self.GAMMA*((1/self.NETSIZE)-self.freq[i])"""
#
# i, j = self.SPECIALS, self.NETSIZE
# dists = abs(self.network[i:j] - np.array([b,g,r])).sum(1)
# bestpos = i + np.argmin(dists)
# biasdists = dists - self.bias[i:j]
# bestbiaspos = i + np.argmin(biasdists)
# self.freq[i:j] -= self.BETA * self.freq[i:j]
# self.bias[i:j] += self.BETAGAMMA * self.freq[i:j]
# self.freq[bestpos] += self.BETA
# self.bias[bestpos] -= self.BETAGAMMA
# return bestbiaspos
def contest(self, b, g, r):
""" Search for biased BGR values
Finds closest neuron (min dist) and updates self.freq
finds best neuron (min dist-self.bias) and returns position
for frequently chosen neurons, self.freq[i] is high and self.bias[i] is negative
self.bias[i] = self.GAMMA*((1/self.NETSIZE)-self.freq[i])"""
i, j = self.SPECIALS, self.NETSIZE
dists = abs(self.network[i:j] - np.array([b,g,r])).sum(1)
bestpos = i + np.argmin(dists)
biasdists = dists - self.bias[i:j]
bestbiaspos = i + np.argmin(biasdists)
self.freq[i:j] *= (1-self.BETA)
self.bias[i:j] += self.BETAGAMMA * self.freq[i:j]
self.freq[bestpos] += self.BETA
self.bias[bestpos] -= self.BETAGAMMA
return bestbiaspos
def specialFind(self, b, g, r):
for i in range(self.SPECIALS):
n = self.network[i]
if n[0] == b and n[1] == g and n[2] == r:
return i
return -1
def learn(self):
biasRadius = self.INITBIASRADIUS
alphadec = 30 + ((self.samplefac-1)/3)
lengthcount = self.pixels.size
samplepixels = lengthcount / self.samplefac
delta = samplepixels / self.NCYCLES
alpha = self.INITALPHA
i = 0;
rad = biasRadius * 2**self.RADIUSBIASSHIFT
if rad <= 1:
rad = 0
print("Beginning 1D learning: samplepixels = %1.2f rad = %i" %
(samplepixels, rad) )
step = 0
pos = 0
if lengthcount%NeuQuant.PRIME1 != 0:
step = NeuQuant.PRIME1
elif lengthcount%NeuQuant.PRIME2 != 0:
step = NeuQuant.PRIME2
elif lengthcount%NeuQuant.PRIME3 != 0:
step = NeuQuant.PRIME3
else:
step = NeuQuant.PRIME4
i = 0
printed_string = ''
while i < samplepixels:
if i%100 == 99:
tmp = '\b'*len(printed_string)
printed_string = str((i+1)*100/samplepixels)+"%\n"
print(tmp + printed_string)
p = self.pixels[pos]
r = (p >> 16) & 0xff
g = (p >> 8) & 0xff
b = (p ) & 0xff
if i == 0: # Remember background colour
self.network[self.BGCOLOR] = [b, g, r]
j = self.specialFind(b, g, r)
if j < 0:
j = self.contest(b, g, r)
if j >= self.SPECIALS: # Don't learn for specials
a = (1.0 * alpha) / self.INITALPHA
self.altersingle(a, j, b, g, r)
if rad > 0:
self.alterneigh(a, rad, j, b, g, r)
pos = (pos+step)%lengthcount
i += 1
if i%delta == 0:
alpha -= alpha / alphadec
biasRadius -= biasRadius / self.RADIUSDEC
rad = biasRadius * 2**self.RADIUSBIASSHIFT
if rad <= 1:
rad = 0
finalAlpha = (1.0*alpha)/self.INITALPHA
print("Finished 1D learning: final alpha = %1.2f!" % finalAlpha)
def fix(self):
for i in range(self.NETSIZE):
for j in range(3):
x = int(0.5 + self.network[i,j])
x = max(0, x)
x = min(255, x)
self.colormap[i,j] = x
self.colormap[i,3] = i
def inxbuild(self):
previouscol = 0
startpos = 0
for i in range(self.NETSIZE):
p = self.colormap[i]
q = None
smallpos = i
smallval = p[1] # Index on g
# Find smallest in i..self.NETSIZE-1
for j in range(i+1, self.NETSIZE):
q = self.colormap[j]
if q[1] < smallval: # Index on g
smallpos = j
smallval = q[1] # Index on g
q = self.colormap[smallpos]
# Swap p (i) and q (smallpos) entries
if i != smallpos:
p[:],q[:] = q, p.copy()
# smallval entry is now in position i
if smallval != previouscol:
self.netindex[previouscol] = (startpos+i) >> 1
for j in range(previouscol+1, smallval):
self.netindex[j] = i
previouscol = smallval
startpos = i
self.netindex[previouscol] = (startpos+self.MAXNETPOS) >> 1
for j in range(previouscol+1, 256): # Really 256
self.netindex[j] = self.MAXNETPOS
def paletteImage(self):
""" PIL weird interface for making a paletted image: create an image which
already has the palette, and use that in Image.quantize. This function
returns this palette image. """
if self.pimage is None:
palette = []
for i in range(self.NETSIZE):
palette.extend(self.colormap[i][:3])
palette.extend([0]*(256-self.NETSIZE)*3)
# a palette image to use for quant
self.pimage = Image.new("P", (1, 1), 0)
self.pimage.putpalette(palette)
return self.pimage
def quantize(self, image):
""" Use a kdtree to quickly find the closest palette colors for the pixels """
if get_cKDTree():
return self.quantize_with_scipy(image)
else:
print('Scipy not available, falling back to slower version.')
return self.quantize_without_scipy(image)
def quantize_with_scipy(self, image):
w,h = image.size
px = np.asarray(image).copy()
px2 = px[:,:,:3].reshape((w*h,3))
cKDTree = get_cKDTree()
kdtree = cKDTree(self.colormap[:,:3],leafsize=10)
result = kdtree.query(px2)
colorindex = result[1]
print("Distance: %1.2f" % (result[0].sum()/(w*h)) )
px2[:] = self.colormap[colorindex,:3]
return Image.fromarray(px).convert("RGB").quantize(palette=self.paletteImage())
def quantize_without_scipy(self, image):
"""" This function can be used if no scipy is availabe.
It's 7 times slower though.
"""
w,h = image.size
px = np.asarray(image).copy()
memo = {}
for j in range(w):
for i in range(h):
key = (px[i,j,0],px[i,j,1],px[i,j,2])
try:
val = memo[key]
except KeyError:
val = self.convert(*key)
memo[key] = val
px[i,j,0],px[i,j,1],px[i,j,2] = val
return Image.fromarray(px).convert("RGB").quantize(palette=self.paletteImage())
def convert(self, *color):
i = self.inxsearch(*color)
return self.colormap[i,:3]
def inxsearch(self, r, g, b):
"""Search for BGR values 0..255 and return colour index"""
dists = (self.colormap[:,:3] - np.array([r,g,b]))
a= np.argmin((dists*dists).sum(1))
return a
if __name__ == '__main__':
im = np.zeros((200,200), dtype=np.uint8)
im[10:30,:] = 100
im[:,80:120] = 255
im[-50:-40,:] = 50
images = [im*1.0, im*0.8, im*0.6, im*0.4, im*0]
writeGif('lala3.gif',images, duration=0.5, dither=0)
|
adobe-research/video-lecture-summaries
|
Scripts/images2gif.py
|
Python
|
bsd-2-clause
| 37,282
|
[
"NEURON"
] |
18e9aacc117950e2457f0651cd3861bef9abb4a928bd19dde975f6841e197441
|
# -*- coding: utf-8 -*-
"""
pysteps.io.interface
====================
Interface for the io module.
.. currentmodule:: pysteps.io.interface
.. autosummary::
:toctree: ../generated/
get_method
"""
import importlib
from pkg_resources import iter_entry_points
from pysteps import io
from pysteps.decorators import postprocess_import
from pysteps.io import importers, exporters
from pprint import pprint
_importer_methods = dict(
bom_rf3=importers.import_bom_rf3,
fmi_geotiff=importers.import_fmi_geotiff,
fmi_pgm=importers.import_fmi_pgm,
mch_gif=importers.import_mch_gif,
mch_hdf5=importers.import_mch_hdf5,
mch_metranet=importers.import_mch_metranet,
mrms_grib=importers.import_mrms_grib,
odim_hdf5=importers.import_odim_hdf5,
opera_hdf5=importers.import_opera_hdf5,
knmi_hdf5=importers.import_knmi_hdf5,
saf_crri=importers.import_saf_crri,
)
_exporter_methods = dict(
geotiff=exporters.initialize_forecast_exporter_geotiff,
kineros=exporters.initialize_forecast_exporter_kineros,
netcdf=exporters.initialize_forecast_exporter_netcdf,
)
def discover_importers():
"""
Search for installed importers plugins in the entrypoint 'pysteps.plugins.importers'
The importers found are added to the `pysteps.io.interface_importer_methods`
dictionary containing the available importers.
"""
# The pkg resources needs to be reload to detect new packages installed during
# the execution of the python application. For example, when the plugins are
# installed during the tests
import pkg_resources
importlib.reload(pkg_resources)
for entry_point in pkg_resources.iter_entry_points(
group="pysteps.plugins.importers", name=None
):
_importer = entry_point.load()
importer_function_name = _importer.__name__
importer_short_name = importer_function_name.replace("import_", "")
_postprocess_kws = getattr(_importer, "postprocess_kws", dict())
_importer = postprocess_import(**_postprocess_kws)(_importer)
if importer_short_name not in _importer_methods:
_importer_methods[importer_short_name] = _importer
else:
RuntimeWarning(
f"The importer identifier '{importer_short_name}' is already available in"
"'pysteps.io.interface._importer_methods'.\n"
f"Skipping {entry_point.module_name}:{'.'.join(entry_point.attrs)}"
)
if hasattr(importers, importer_function_name):
RuntimeWarning(
f"The importer function '{importer_function_name}' is already an attribute"
"of 'pysteps.io.importers`.\n"
f"Skipping {entry_point.module_name}:{'.'.join(entry_point.attrs)}"
)
else:
setattr(importers, importer_function_name, _importer)
def importers_info():
"""Print all the available importers."""
# Importers available in the `io.importers` module
available_importers = [
attr for attr in dir(io.importers) if attr.startswith("import_")
]
print("\nImporters available in the pysteps.io.importers module")
pprint(available_importers)
# Importers declared in the pysteps.io.get_method interface
importers_in_the_interface = [
f.__name__ for f in io.interface._importer_methods.values()
]
print("\nImporters available in the pysteps.io.get_method interface")
pprint(
[
(short_name, f.__name__)
for short_name, f in io.interface._importer_methods.items()
]
)
# Let's use sets to find out if there are importers present in the importer module
# but not declared in the interface, and viceversa.
available_importers = set(available_importers)
importers_in_the_interface = set(importers_in_the_interface)
difference = available_importers ^ importers_in_the_interface
if len(difference) > 0:
print("\nIMPORTANT:")
_diff = available_importers - importers_in_the_interface
if len(_diff) > 0:
print(
"\nIMPORTANT:\nThe following importers are available in pysteps.io.importers module "
"but not in the pysteps.io.get_method interface"
)
pprint(_diff)
_diff = importers_in_the_interface - available_importers
if len(_diff) > 0:
print(
"\nWARNING:\n"
"The following importers are available in the pysteps.io.get_method "
"interface but not in the pysteps.io.importers module"
)
pprint(_diff)
return available_importers, importers_in_the_interface
def get_method(name, method_type):
"""
Return a callable function for the method corresponding to the given
name.
Parameters
----------
name: str
Name of the method. The available options are:\n
Importers:
.. tabularcolumns:: |p{2cm}|L|
+--------------+------------------------------------------------------+
| Name | Description |
+==============+======================================================+
| bom_rf3 | NefCDF files used in the Boreau of Meterorology |
| | archive containing precipitation intensity |
| | composites. |
+--------------+------------------------------------------------------+
| fmi_geotiff | GeoTIFF files used in the Finnish Meteorological |
| | Institute (FMI) archive, containing reflectivity |
| | composites (dBZ). |
+--------------+------------------------------------------------------+
| fmi_pgm | PGM files used in the Finnish Meteorological |
| | Institute (FMI) archive, containing reflectivity |
| | composites (dBZ). |
+--------------+------------------------------------------------------+
| knmi_hdf5 | HDF5 file format used by KNMI. |
+--------------+------------------------------------------------------+
| mch_gif | GIF files in the MeteoSwiss (MCH) archive containing |
| | precipitation composites. |
+--------------+------------------------------------------------------+
| mch_hdf5 | HDF5 file format used by MeteoSiss (MCH). |
+--------------+------------------------------------------------------+
| mch_metranet | metranet files in the MeteoSwiss (MCH) archive |
| | containing precipitation composites. |
+--------------+------------------------------------------------------+
| mrms_grib | Grib2 files used by the NSSL's MRMS product |
+--------------+------------------------------------------------------+
| odim_hdf5 | HDF5 file conforming to the ODIM specification. |
+--------------+------------------------------------------------------+
| opera_hdf5 | Wrapper to "odim_hdf5" to maintain backward |
| | compatibility with previous pysteps versions. |
+--------------+------------------------------------------------------+
| saf_crri | NetCDF SAF CRRI files containing convective rain |
| | rate intensity and other |
+--------------+------------------------------------------------------+
Exporters:
.. tabularcolumns:: |p{2cm}|L|
+-------------+-------------------------------------------------------+
| Name | Description |
+=============+=======================================================+
| geotiff | Export as GeoTIFF files. |
+-------------+-------------------------------------------------------+
| kineros | KINEROS2 Rainfall file as specified in |
| | https://www.tucson.ars.ag.gov/kineros/. |
| | Grid points are treated as individual rain gauges. |
| | A separate file is produced for each ensemble member. |
+-------------+-------------------------------------------------------+
| netcdf | NetCDF files conforming to the CF 1.7 specification. |
+-------------+-------------------------------------------------------+
method_type: {'importer', 'exporter'}
Type of the method (see tables above).
"""
if isinstance(method_type, str):
method_type = method_type.lower()
else:
raise TypeError(
"Only strings supported for for the method_type"
+ " argument\n"
+ "The available types are: 'importer' and 'exporter'"
) from None
if isinstance(name, str):
name = name.lower()
else:
raise TypeError(
"Only strings supported for the method's names.\n"
+ "Available importers names:"
+ str(list(_importer_methods.keys()))
+ "\nAvailable exporters names:"
+ str(list(_exporter_methods.keys()))
) from None
if method_type == "importer":
methods_dict = _importer_methods
elif method_type == "exporter":
methods_dict = _exporter_methods
else:
raise ValueError(
"Unknown method type {}\n".format(name)
+ "The available types are: 'importer' and 'exporter'"
) from None
try:
return methods_dict[name]
except KeyError:
raise ValueError(
"Unknown {} method {}\n".format(method_type, name)
+ "The available methods are:"
+ str(list(methods_dict.keys()))
) from None
|
pySTEPS/pysteps
|
pysteps/io/interface.py
|
Python
|
bsd-3-clause
| 10,166
|
[
"NetCDF"
] |
ebf6c0cd6273c0e5f6089379b040f026d633f6f386d5f119fe5312eee89360d9
|
"""Universal feed parser
Handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds
Visit https://code.google.com/p/feedparser/ for the latest version
Visit http://packages.python.org/feedparser/ for the latest documentation
Required: Python 2.4 or later
Recommended: iconv_codec <http://cjkpython.i18n.org/>
"""
__version__ = "5.1.2"
__license__ = """
Copyright (c) 2010-2012 Kurt McKee <contactme@kurtmckee.org>
Copyright (c) 2002-2008 Mark Pilgrim
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE."""
__author__ = "Mark Pilgrim <http://diveintomark.org/>"
__contributors__ = ["Jason Diamond <http://injektilo.org/>",
"John Beimler <http://john.beimler.org/>",
"Fazal Majid <http://www.majid.info/mylos/weblog/>",
"Aaron Swartz <http://aaronsw.com/>",
"Kevin Marks <http://epeus.blogspot.com/>",
"Sam Ruby <http://intertwingly.net/>",
"Ade Oshineye <http://blog.oshineye.com/>",
"Martin Pool <http://sourcefrog.net/>",
"Kurt McKee <http://kurtmckee.org/>"]
# HTTP "User-Agent" header to send to servers when downloading feeds.
# If you are embedding feedparser in a larger application, you should
# change this to your application name and URL.
USER_AGENT = "UniversalFeedParser/%s +https://code.google.com/p/feedparser/" % __version__
# HTTP "Accept" header to send to servers when downloading feeds. If you don't
# want to send an Accept header, set this to None.
ACCEPT_HEADER = "application/atom+xml,application/rdf+xml,application/rss+xml,application/x-netcdf,application/xml;q=0.9,text/xml;q=0.2,*/*;q=0.1"
# List of preferred XML parsers, by SAX driver name. These will be tried first,
# but if they're not installed, Python will keep searching through its own list
# of pre-installed parsers until it finds one that supports everything we need.
PREFERRED_XML_PARSERS = ["drv_libxml2"]
# If you want feedparser to automatically run HTML markup through HTML Tidy, set
# this to 1. Requires mxTidy <http://www.egenix.com/files/python/mxTidy.html>
# or utidylib <http://utidylib.berlios.de/>.
TIDY_MARKUP = 0
# List of Python interfaces for HTML Tidy, in order of preference. Only useful
# if TIDY_MARKUP = 1
PREFERRED_TIDY_INTERFACES = ["uTidy", "mxTidy"]
# If you want feedparser to automatically resolve all relative URIs, set this
# to 1.
RESOLVE_RELATIVE_URIS = 1
# If you want feedparser to automatically sanitize all potentially unsafe
# HTML content, set this to 1.
SANITIZE_HTML = 1
# If you want feedparser to automatically parse microformat content embedded
# in entry contents, set this to 1
PARSE_MICROFORMATS = 1
# ---------- Python 3 modules (make it work if possible) ----------
try:
import rfc822
except ImportError:
from email import _parseaddr as rfc822
try:
# Python 3.1 introduces bytes.maketrans and simultaneously
# deprecates string.maketrans; use bytes.maketrans if possible
_maketrans = bytes.maketrans
except (NameError, AttributeError):
import string
_maketrans = string.maketrans
# base64 support for Atom feeds that contain embedded binary data
try:
import base64, binascii
except ImportError:
base64 = binascii = None
else:
# Python 3.1 deprecates decodestring in favor of decodebytes
_base64decode = getattr(base64, 'decodebytes', base64.decodestring)
# _s2bytes: convert a UTF-8 str to bytes if the interpreter is Python 3
# _l2bytes: convert a list of ints to bytes if the interpreter is Python 3
try:
if bytes is str:
# In Python 2.5 and below, bytes doesn't exist (NameError)
# In Python 2.6 and above, bytes and str are the same type
raise NameError
except NameError:
# Python 2
def _s2bytes(s):
return s
def _l2bytes(l):
return ''.join(map(chr, l))
else:
# Python 3
def _s2bytes(s):
return bytes(s, 'utf8')
def _l2bytes(l):
return bytes(l)
# If you want feedparser to allow all URL schemes, set this to ()
# List culled from Python's urlparse documentation at:
# http://docs.python.org/library/urlparse.html
# as well as from "URI scheme" at Wikipedia:
# https://secure.wikimedia.org/wikipedia/en/wiki/URI_scheme
# Many more will likely need to be added!
ACCEPTABLE_URI_SCHEMES = (
'file', 'ftp', 'gopher', 'h323', 'hdl', 'http', 'https', 'imap', 'magnet',
'mailto', 'mms', 'news', 'nntp', 'prospero', 'rsync', 'rtsp', 'rtspu',
'sftp', 'shttp', 'sip', 'sips', 'snews', 'svn', 'svn+ssh', 'telnet',
'wais',
# Additional common-but-unofficial schemes
'aim', 'callto', 'cvs', 'facetime', 'feed', 'git', 'gtalk', 'irc', 'ircs',
'irc6', 'itms', 'mms', 'msnim', 'skype', 'ssh', 'smb', 'svn', 'ymsg',
)
#ACCEPTABLE_URI_SCHEMES = ()
# ---------- required modules (should come with any Python distribution) ----------
import cgi
import codecs
import copy
import datetime
import re
import struct
import time
import types
import urllib
import urllib2
import urlparse
import warnings
from htmlentitydefs import name2codepoint, codepoint2name, entitydefs
try:
from io import BytesIO as _StringIO
except ImportError:
try:
from cStringIO import StringIO as _StringIO
except ImportError:
from StringIO import StringIO as _StringIO
# ---------- optional modules (feedparser will work without these, but with reduced functionality) ----------
# gzip is included with most Python distributions, but may not be available if you compiled your own
try:
import gzip
except ImportError:
gzip = None
try:
import zlib
except ImportError:
zlib = None
# If a real XML parser is available, feedparser will attempt to use it. feedparser has
# been tested with the built-in SAX parser and libxml2. On platforms where the
# Python distribution does not come with an XML parser (such as Mac OS X 10.2 and some
# versions of FreeBSD), feedparser will quietly fall back on regex-based parsing.
try:
import xml.sax
from xml.sax.saxutils import escape as _xmlescape
except ImportError:
_XML_AVAILABLE = 0
def _xmlescape(data,entities={}):
data = data.replace('&', '&')
data = data.replace('>', '>')
data = data.replace('<', '<')
for char, entity in entities:
data = data.replace(char, entity)
return data
else:
try:
xml.sax.make_parser(PREFERRED_XML_PARSERS) # test for valid parsers
except xml.sax.SAXReaderNotAvailable:
_XML_AVAILABLE = 0
else:
_XML_AVAILABLE = 1
# sgmllib is not available by default in Python 3; if the end user doesn't have
# it available then we'll lose illformed XML parsing, content santizing, and
# microformat support (at least while feedparser depends on BeautifulSoup).
try:
import sgmllib
except ImportError:
# This is probably Python 3, which doesn't include sgmllib anymore
_SGML_AVAILABLE = 0
# Mock sgmllib enough to allow subclassing later on
class sgmllib(object):
class SGMLParser(object):
def goahead(self, i):
pass
def parse_starttag(self, i):
pass
else:
_SGML_AVAILABLE = 1
# sgmllib defines a number of module-level regular expressions that are
# insufficient for the XML parsing feedparser needs. Rather than modify
# the variables directly in sgmllib, they're defined here using the same
# names, and the compiled code objects of several sgmllib.SGMLParser
# methods are copied into _BaseHTMLProcessor so that they execute in
# feedparser's scope instead of sgmllib's scope.
charref = re.compile('&#(\d+|[xX][0-9a-fA-F]+);')
tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
attrfind = re.compile(
r'\s*([a-zA-Z_][-:.a-zA-Z_0-9]*)[$]?(\s*=\s*'
r'(\'[^\']*\'|"[^"]*"|[][\-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~\'"@]*))?'
)
# Unfortunately, these must be copied over to prevent NameError exceptions
entityref = sgmllib.entityref
incomplete = sgmllib.incomplete
interesting = sgmllib.interesting
shorttag = sgmllib.shorttag
shorttagopen = sgmllib.shorttagopen
starttagopen = sgmllib.starttagopen
class _EndBracketRegEx:
def __init__(self):
# Overriding the built-in sgmllib.endbracket regex allows the
# parser to find angle brackets embedded in element attributes.
self.endbracket = re.compile('''([^'"<>]|"[^"]*"(?=>|/|\s|\w+=)|'[^']*'(?=>|/|\s|\w+=))*(?=[<>])|.*?(?=[<>])''')
def search(self, target, index=0):
match = self.endbracket.match(target, index)
if match is not None:
# Returning a new object in the calling thread's context
# resolves a thread-safety.
return EndBracketMatch(match)
return None
class EndBracketMatch:
def __init__(self, match):
self.match = match
def start(self, n):
return self.match.end(n)
endbracket = _EndBracketRegEx()
# iconv_codec provides support for more character encodings.
# It's available from http://cjkpython.i18n.org/
try:
import iconv_codec
except ImportError:
pass
# chardet library auto-detects character encodings
# Download from http://chardet.feedparser.org/
try:
import chardet
except ImportError:
chardet = None
# BeautifulSoup is used to extract microformat content from HTML
# feedparser is tested using BeautifulSoup 3.2.0
# http://www.crummy.com/software/BeautifulSoup/
try:
import BeautifulSoup
except ImportError:
BeautifulSoup = None
PARSE_MICROFORMATS = False
try:
# the utf_32 codec was introduced in Python 2.6; it's necessary to
# check this as long as feedparser supports Python 2.4 and 2.5
codecs.lookup('utf_32')
except LookupError:
_UTF32_AVAILABLE = False
else:
_UTF32_AVAILABLE = True
# ---------- don't touch these ----------
class ThingsNobodyCaresAboutButMe(Exception): pass
class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): pass
class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): pass
class NonXMLContentType(ThingsNobodyCaresAboutButMe): pass
class UndeclaredNamespace(Exception): pass
SUPPORTED_VERSIONS = {'': u'unknown',
'rss090': u'RSS 0.90',
'rss091n': u'RSS 0.91 (Netscape)',
'rss091u': u'RSS 0.91 (Userland)',
'rss092': u'RSS 0.92',
'rss093': u'RSS 0.93',
'rss094': u'RSS 0.94',
'rss20': u'RSS 2.0',
'rss10': u'RSS 1.0',
'rss': u'RSS (unknown version)',
'atom01': u'Atom 0.1',
'atom02': u'Atom 0.2',
'atom03': u'Atom 0.3',
'atom10': u'Atom 1.0',
'atom': u'Atom (unknown version)',
'cdf': u'CDF',
}
class FeedParserDict(dict):
keymap = {'channel': 'feed',
'items': 'entries',
'guid': 'id',
'date': 'updated',
'date_parsed': 'updated_parsed',
'description': ['summary', 'subtitle'],
'description_detail': ['summary_detail', 'subtitle_detail'],
'url': ['href'],
'modified': 'updated',
'modified_parsed': 'updated_parsed',
'issued': 'published',
'issued_parsed': 'published_parsed',
'copyright': 'rights',
'copyright_detail': 'rights_detail',
'tagline': 'subtitle',
'tagline_detail': 'subtitle_detail'}
def __getitem__(self, key):
if key == 'category':
try:
return dict.__getitem__(self, 'tags')[0]['term']
except IndexError:
raise KeyError, "object doesn't have key 'category'"
elif key == 'enclosures':
norel = lambda link: FeedParserDict([(name,value) for (name,value) in link.items() if name!='rel'])
return [norel(link) for link in dict.__getitem__(self, 'links') if link['rel']==u'enclosure']
elif key == 'license':
for link in dict.__getitem__(self, 'links'):
if link['rel']==u'license' and 'href' in link:
return link['href']
elif key == 'updated':
# Temporarily help developers out by keeping the old
# broken behavior that was reported in issue 310.
# This fix was proposed in issue 328.
if not dict.__contains__(self, 'updated') and \
dict.__contains__(self, 'published'):
warnings.warn("To avoid breaking existing software while "
"fixing issue 310, a temporary mapping has been created "
"from `updated` to `published` if `updated` doesn't "
"exist. This fallback will be removed in a future version "
"of feedparser.", DeprecationWarning)
return dict.__getitem__(self, 'published')
return dict.__getitem__(self, 'updated')
elif key == 'updated_parsed':
if not dict.__contains__(self, 'updated_parsed') and \
dict.__contains__(self, 'published_parsed'):
warnings.warn("To avoid breaking existing software while "
"fixing issue 310, a temporary mapping has been created "
"from `updated_parsed` to `published_parsed` if "
"`updated_parsed` doesn't exist. This fallback will be "
"removed in a future version of feedparser.",
DeprecationWarning)
return dict.__getitem__(self, 'published_parsed')
return dict.__getitem__(self, 'updated_parsed')
else:
realkey = self.keymap.get(key, key)
if isinstance(realkey, list):
for k in realkey:
if dict.__contains__(self, k):
return dict.__getitem__(self, k)
elif dict.__contains__(self, realkey):
return dict.__getitem__(self, realkey)
return dict.__getitem__(self, key)
def __contains__(self, key):
if key in ('updated', 'updated_parsed'):
# Temporarily help developers out by keeping the old
# broken behavior that was reported in issue 310.
# This fix was proposed in issue 328.
return dict.__contains__(self, key)
try:
self.__getitem__(key)
except KeyError:
return False
else:
return True
has_key = __contains__
def get(self, key, default=None):
try:
return self.__getitem__(key)
except KeyError:
return default
def __setitem__(self, key, value):
key = self.keymap.get(key, key)
if isinstance(key, list):
key = key[0]
return dict.__setitem__(self, key, value)
def setdefault(self, key, value):
if key not in self:
self[key] = value
return value
return self[key]
def __getattr__(self, key):
# __getattribute__() is called first; this will be called
# only if an attribute was not already found
try:
return self.__getitem__(key)
except KeyError:
raise AttributeError, "object has no attribute '%s'" % key
def __hash__(self):
return id(self)
_cp1252 = {
128: unichr(8364), # euro sign
130: unichr(8218), # single low-9 quotation mark
131: unichr( 402), # latin small letter f with hook
132: unichr(8222), # double low-9 quotation mark
133: unichr(8230), # horizontal ellipsis
134: unichr(8224), # dagger
135: unichr(8225), # double dagger
136: unichr( 710), # modifier letter circumflex accent
137: unichr(8240), # per mille sign
138: unichr( 352), # latin capital letter s with caron
139: unichr(8249), # single left-pointing angle quotation mark
140: unichr( 338), # latin capital ligature oe
142: unichr( 381), # latin capital letter z with caron
145: unichr(8216), # left single quotation mark
146: unichr(8217), # right single quotation mark
147: unichr(8220), # left double quotation mark
148: unichr(8221), # right double quotation mark
149: unichr(8226), # bullet
150: unichr(8211), # en dash
151: unichr(8212), # em dash
152: unichr( 732), # small tilde
153: unichr(8482), # trade mark sign
154: unichr( 353), # latin small letter s with caron
155: unichr(8250), # single right-pointing angle quotation mark
156: unichr( 339), # latin small ligature oe
158: unichr( 382), # latin small letter z with caron
159: unichr( 376), # latin capital letter y with diaeresis
}
_urifixer = re.compile('^([A-Za-z][A-Za-z0-9+-.]*://)(/*)(.*?)')
def _urljoin(base, uri):
uri = _urifixer.sub(r'\1\3', uri)
#try:
if not isinstance(uri, unicode):
uri = uri.decode('utf-8', 'ignore')
uri = urlparse.urljoin(base, uri)
if not isinstance(uri, unicode):
return uri.decode('utf-8', 'ignore')
return uri
#except:
# uri = urlparse.urlunparse([urllib.quote(part) for part in urlparse.urlparse(uri)])
# return urlparse.urljoin(base, uri)
class _FeedParserMixin:
namespaces = {
'': '',
'http://backend.userland.com/rss': '',
'http://blogs.law.harvard.edu/tech/rss': '',
'http://purl.org/rss/1.0/': '',
'http://my.netscape.com/rdf/simple/0.9/': '',
'http://example.com/newformat#': '',
'http://example.com/necho': '',
'http://purl.org/echo/': '',
'uri/of/echo/namespace#': '',
'http://purl.org/pie/': '',
'http://purl.org/atom/ns#': '',
'http://www.w3.org/2005/Atom': '',
'http://purl.org/rss/1.0/modules/rss091#': '',
'http://webns.net/mvcb/': 'admin',
'http://purl.org/rss/1.0/modules/aggregation/': 'ag',
'http://purl.org/rss/1.0/modules/annotate/': 'annotate',
'http://media.tangent.org/rss/1.0/': 'audio',
'http://backend.userland.com/blogChannelModule': 'blogChannel',
'http://web.resource.org/cc/': 'cc',
'http://backend.userland.com/creativeCommonsRssModule': 'creativeCommons',
'http://purl.org/rss/1.0/modules/company': 'co',
'http://purl.org/rss/1.0/modules/content/': 'content',
'http://my.theinfo.org/changed/1.0/rss/': 'cp',
'http://purl.org/dc/elements/1.1/': 'dc',
'http://purl.org/dc/terms/': 'dcterms',
'http://purl.org/rss/1.0/modules/email/': 'email',
'http://purl.org/rss/1.0/modules/event/': 'ev',
'http://rssnamespace.org/feedburner/ext/1.0': 'feedburner',
'http://freshmeat.net/rss/fm/': 'fm',
'http://xmlns.com/foaf/0.1/': 'foaf',
'http://www.w3.org/2003/01/geo/wgs84_pos#': 'geo',
'http://postneo.com/icbm/': 'icbm',
'http://purl.org/rss/1.0/modules/image/': 'image',
'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes',
'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes',
'http://purl.org/rss/1.0/modules/link/': 'l',
'http://search.yahoo.com/mrss': 'media',
# Version 1.1.2 of the Media RSS spec added the trailing slash on the namespace
'http://search.yahoo.com/mrss/': 'media',
'http://madskills.com/public/xml/rss/module/pingback/': 'pingback',
'http://prismstandard.org/namespaces/1.2/basic/': 'prism',
'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf',
'http://www.w3.org/2000/01/rdf-schema#': 'rdfs',
'http://purl.org/rss/1.0/modules/reference/': 'ref',
'http://purl.org/rss/1.0/modules/richequiv/': 'reqv',
'http://purl.org/rss/1.0/modules/search/': 'search',
'http://purl.org/rss/1.0/modules/slash/': 'slash',
'http://schemas.xmlsoap.org/soap/envelope/': 'soap',
'http://purl.org/rss/1.0/modules/servicestatus/': 'ss',
'http://hacks.benhammersley.com/rss/streaming/': 'str',
'http://purl.org/rss/1.0/modules/subscription/': 'sub',
'http://purl.org/rss/1.0/modules/syndication/': 'sy',
'http://schemas.pocketsoap.com/rss/myDescModule/': 'szf',
'http://purl.org/rss/1.0/modules/taxonomy/': 'taxo',
'http://purl.org/rss/1.0/modules/threading/': 'thr',
'http://purl.org/rss/1.0/modules/textinput/': 'ti',
'http://madskills.com/public/xml/rss/module/trackback/': 'trackback',
'http://wellformedweb.org/commentAPI/': 'wfw',
'http://purl.org/rss/1.0/modules/wiki/': 'wiki',
'http://www.w3.org/1999/xhtml': 'xhtml',
'http://www.w3.org/1999/xlink': 'xlink',
'http://www.w3.org/XML/1998/namespace': 'xml',
}
_matchnamespaces = {}
can_be_relative_uri = set(['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'icon', 'logo'])
can_contain_relative_uris = set(['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description'])
can_contain_dangerous_markup = set(['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description'])
html_types = [u'text/html', u'application/xhtml+xml']
def __init__(self, baseuri=None, baselang=None, encoding=u'utf-8'):
if not self._matchnamespaces:
for k, v in self.namespaces.items():
self._matchnamespaces[k.lower()] = v
self.feeddata = FeedParserDict() # feed-level data
self.encoding = encoding # character encoding
self.entries = [] # list of entry-level data
self.version = u'' # feed type/version, see SUPPORTED_VERSIONS
self.namespacesInUse = {} # dictionary of namespaces defined by the feed
# the following are used internally to track state;
# this is really out of control and should be refactored
self.infeed = 0
self.inentry = 0
self.incontent = 0
self.intextinput = 0
self.inimage = 0
self.inauthor = 0
self.incontributor = 0
self.inpublisher = 0
self.insource = 0
self.sourcedata = FeedParserDict()
self.contentparams = FeedParserDict()
self._summaryKey = None
self.namespacemap = {}
self.elementstack = []
self.basestack = []
self.langstack = []
self.baseuri = baseuri or u''
self.lang = baselang or None
self.svgOK = 0
self.title_depth = -1
self.depth = 0
if baselang:
self.feeddata['language'] = baselang.replace('_','-')
# A map of the following form:
# {
# object_that_value_is_set_on: {
# property_name: depth_of_node_property_was_extracted_from,
# other_property: depth_of_node_property_was_extracted_from,
# },
# }
self.property_depth_map = {}
def _normalize_attributes(self, kv):
k = kv[0].lower()
v = k in ('rel', 'type') and kv[1].lower() or kv[1]
# the sgml parser doesn't handle entities in attributes, nor
# does it pass the attribute values through as unicode, while
# strict xml parsers do -- account for this difference
if isinstance(self, _LooseFeedParser):
v = v.replace('&', '&')
if not isinstance(v, unicode):
v = v.decode('utf-8')
return (k, v)
def unknown_starttag(self, tag, attrs):
# increment depth counter
self.depth += 1
# normalize attrs
attrs = map(self._normalize_attributes, attrs)
# track xml:base and xml:lang
attrsD = dict(attrs)
baseuri = attrsD.get('xml:base', attrsD.get('base')) or self.baseuri
if not isinstance(baseuri, unicode):
baseuri = baseuri.decode(self.encoding, 'ignore')
# ensure that self.baseuri is always an absolute URI that
# uses a whitelisted URI scheme (e.g. not `javscript:`)
if self.baseuri:
self.baseuri = _makeSafeAbsoluteURI(self.baseuri, baseuri) or self.baseuri
else:
self.baseuri = _urljoin(self.baseuri, baseuri)
lang = attrsD.get('xml:lang', attrsD.get('lang'))
if lang == '':
# xml:lang could be explicitly set to '', we need to capture that
lang = None
elif lang is None:
# if no xml:lang is specified, use parent lang
lang = self.lang
if lang:
if tag in ('feed', 'rss', 'rdf:RDF'):
self.feeddata['language'] = lang.replace('_','-')
self.lang = lang
self.basestack.append(self.baseuri)
self.langstack.append(lang)
# track namespaces
for prefix, uri in attrs:
if prefix.startswith('xmlns:'):
self.trackNamespace(prefix[6:], uri)
elif prefix == 'xmlns':
self.trackNamespace(None, uri)
# track inline content
if self.incontent and not self.contentparams.get('type', u'xml').endswith(u'xml'):
if tag in ('xhtml:div', 'div'):
return # typepad does this 10/2007
# element declared itself as escaped markup, but it isn't really
self.contentparams['type'] = u'application/xhtml+xml'
if self.incontent and self.contentparams.get('type') == u'application/xhtml+xml':
if tag.find(':') <> -1:
prefix, tag = tag.split(':', 1)
namespace = self.namespacesInUse.get(prefix, '')
if tag=='math' and namespace=='http://www.w3.org/1998/Math/MathML':
attrs.append(('xmlns',namespace))
if tag=='svg' and namespace=='http://www.w3.org/2000/svg':
attrs.append(('xmlns',namespace))
if tag == 'svg':
self.svgOK += 1
return self.handle_data('<%s%s>' % (tag, self.strattrs(attrs)), escape=0)
# match namespaces
if tag.find(':') <> -1:
prefix, suffix = tag.split(':', 1)
else:
prefix, suffix = '', tag
prefix = self.namespacemap.get(prefix, prefix)
if prefix:
prefix = prefix + '_'
# special hack for better tracking of empty textinput/image elements in illformed feeds
if (not prefix) and tag not in ('title', 'link', 'description', 'name'):
self.intextinput = 0
if (not prefix) and tag not in ('title', 'link', 'description', 'url', 'href', 'width', 'height'):
self.inimage = 0
# call special handler (if defined) or default handler
methodname = '_start_' + prefix + suffix
try:
method = getattr(self, methodname)
return method(attrsD)
except AttributeError:
# Since there's no handler or something has gone wrong we explicitly add the element and its attributes
unknown_tag = prefix + suffix
if len(attrsD) == 0:
# No attributes so merge it into the encosing dictionary
return self.push(unknown_tag, 1)
else:
# Has attributes so create it in its own dictionary
context = self._getContext()
context[unknown_tag] = attrsD
def unknown_endtag(self, tag):
# match namespaces
if tag.find(':') <> -1:
prefix, suffix = tag.split(':', 1)
else:
prefix, suffix = '', tag
prefix = self.namespacemap.get(prefix, prefix)
if prefix:
prefix = prefix + '_'
if suffix == 'svg' and self.svgOK:
self.svgOK -= 1
# call special handler (if defined) or default handler
methodname = '_end_' + prefix + suffix
try:
if self.svgOK:
raise AttributeError()
method = getattr(self, methodname)
method()
except AttributeError:
self.pop(prefix + suffix)
# track inline content
if self.incontent and not self.contentparams.get('type', u'xml').endswith(u'xml'):
# element declared itself as escaped markup, but it isn't really
if tag in ('xhtml:div', 'div'):
return # typepad does this 10/2007
self.contentparams['type'] = u'application/xhtml+xml'
if self.incontent and self.contentparams.get('type') == u'application/xhtml+xml':
tag = tag.split(':')[-1]
self.handle_data('</%s>' % tag, escape=0)
# track xml:base and xml:lang going out of scope
if self.basestack:
self.basestack.pop()
if self.basestack and self.basestack[-1]:
self.baseuri = self.basestack[-1]
if self.langstack:
self.langstack.pop()
if self.langstack: # and (self.langstack[-1] is not None):
self.lang = self.langstack[-1]
self.depth -= 1
def handle_charref(self, ref):
# called for each character reference, e.g. for ' ', ref will be '160'
if not self.elementstack:
return
ref = ref.lower()
if ref in ('34', '38', '39', '60', '62', 'x22', 'x26', 'x27', 'x3c', 'x3e'):
text = '&#%s;' % ref
else:
if ref[0] == 'x':
c = int(ref[1:], 16)
else:
c = int(ref)
text = unichr(c).encode('utf-8')
self.elementstack[-1][2].append(text)
def handle_entityref(self, ref):
# called for each entity reference, e.g. for '©', ref will be 'copy'
if not self.elementstack:
return
if ref in ('lt', 'gt', 'quot', 'amp', 'apos'):
text = '&%s;' % ref
elif ref in self.entities:
text = self.entities[ref]
if text.startswith('&#') and text.endswith(';'):
return self.handle_entityref(text)
else:
try:
name2codepoint[ref]
except KeyError:
text = '&%s;' % ref
else:
text = unichr(name2codepoint[ref]).encode('utf-8')
self.elementstack[-1][2].append(text)
def handle_data(self, text, escape=1):
# called for each block of plain text, i.e. outside of any tag and
# not containing any character or entity references
if not self.elementstack:
return
if escape and self.contentparams.get('type') == u'application/xhtml+xml':
text = _xmlescape(text)
self.elementstack[-1][2].append(text)
def handle_comment(self, text):
# called for each comment, e.g. <!-- insert message here -->
pass
def handle_pi(self, text):
# called for each processing instruction, e.g. <?instruction>
pass
def handle_decl(self, text):
pass
def parse_declaration(self, i):
# override internal declaration handler to handle CDATA blocks
if self.rawdata[i:i+9] == '<![CDATA[':
k = self.rawdata.find(']]>', i)
if k == -1:
# CDATA block began but didn't finish
k = len(self.rawdata)
return k
self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0)
return k+3
else:
k = self.rawdata.find('>', i)
if k >= 0:
return k+1
else:
# We have an incomplete CDATA block.
return k
def mapContentType(self, contentType):
contentType = contentType.lower()
if contentType == 'text' or contentType == 'plain':
contentType = u'text/plain'
elif contentType == 'html':
contentType = u'text/html'
elif contentType == 'xhtml':
contentType = u'application/xhtml+xml'
return contentType
def trackNamespace(self, prefix, uri):
loweruri = uri.lower()
if not self.version:
if (prefix, loweruri) == (None, 'http://my.netscape.com/rdf/simple/0.9/'):
self.version = u'rss090'
elif loweruri == 'http://purl.org/rss/1.0/':
self.version = u'rss10'
elif loweruri == 'http://www.w3.org/2005/atom':
self.version = u'atom10'
if loweruri.find(u'backend.userland.com/rss') <> -1:
# match any backend.userland.com namespace
uri = u'http://backend.userland.com/rss'
loweruri = uri
if loweruri in self._matchnamespaces:
self.namespacemap[prefix] = self._matchnamespaces[loweruri]
self.namespacesInUse[self._matchnamespaces[loweruri]] = uri
else:
self.namespacesInUse[prefix or ''] = uri
def resolveURI(self, uri):
return _urljoin(self.baseuri or u'', uri)
def decodeEntities(self, element, data):
return data
def strattrs(self, attrs):
return ''.join([' %s="%s"' % (t[0],_xmlescape(t[1],{'"':'"'})) for t in attrs])
def push(self, element, expectingText):
self.elementstack.append([element, expectingText, []])
def pop(self, element, stripWhitespace=1):
if not self.elementstack:
return
if self.elementstack[-1][0] != element:
return
element, expectingText, pieces = self.elementstack.pop()
if self.version == u'atom10' and self.contentparams.get('type', u'text') == u'application/xhtml+xml':
# remove enclosing child element, but only if it is a <div> and
# only if all the remaining content is nested underneath it.
# This means that the divs would be retained in the following:
# <div>foo</div><div>bar</div>
while pieces and len(pieces)>1 and not pieces[-1].strip():
del pieces[-1]
while pieces and len(pieces)>1 and not pieces[0].strip():
del pieces[0]
if pieces and (pieces[0] == '<div>' or pieces[0].startswith('<div ')) and pieces[-1]=='</div>':
depth = 0
for piece in pieces[:-1]:
if piece.startswith('</'):
depth -= 1
if depth == 0:
break
elif piece.startswith('<') and not piece.endswith('/>'):
depth += 1
else:
pieces = pieces[1:-1]
# Ensure each piece is a str for Python 3
for (i, v) in enumerate(pieces):
if not isinstance(v, unicode):
pieces[i] = v.decode('utf-8')
output = u''.join(pieces)
if stripWhitespace:
output = output.strip()
if not expectingText:
return output
# decode base64 content
if base64 and self.contentparams.get('base64', 0):
try:
output = _base64decode(output)
except binascii.Error:
pass
except binascii.Incomplete:
pass
except TypeError:
# In Python 3, base64 takes and outputs bytes, not str
# This may not be the most correct way to accomplish this
output = _base64decode(output.encode('utf-8')).decode('utf-8')
# resolve relative URIs
if (element in self.can_be_relative_uri) and output:
output = self.resolveURI(output)
# decode entities within embedded markup
if not self.contentparams.get('base64', 0):
output = self.decodeEntities(element, output)
# some feed formats require consumers to guess
# whether the content is html or plain text
if not self.version.startswith(u'atom') and self.contentparams.get('type') == u'text/plain':
if self.lookslikehtml(output):
self.contentparams['type'] = u'text/html'
# remove temporary cruft from contentparams
try:
del self.contentparams['mode']
except KeyError:
pass
try:
del self.contentparams['base64']
except KeyError:
pass
is_htmlish = self.mapContentType(self.contentparams.get('type', u'text/html')) in self.html_types
# resolve relative URIs within embedded markup
if is_htmlish and RESOLVE_RELATIVE_URIS:
if element in self.can_contain_relative_uris:
output = _resolveRelativeURIs(output, self.baseuri, self.encoding, self.contentparams.get('type', u'text/html'))
# parse microformats
# (must do this before sanitizing because some microformats
# rely on elements that we sanitize)
if PARSE_MICROFORMATS and is_htmlish and element in ['content', 'description', 'summary']:
mfresults = _parseMicroformats(output, self.baseuri, self.encoding)
if mfresults:
for tag in mfresults.get('tags', []):
self._addTag(tag['term'], tag['scheme'], tag['label'])
for enclosure in mfresults.get('enclosures', []):
self._start_enclosure(enclosure)
for xfn in mfresults.get('xfn', []):
self._addXFN(xfn['relationships'], xfn['href'], xfn['name'])
vcard = mfresults.get('vcard')
if vcard:
self._getContext()['vcard'] = vcard
# sanitize embedded markup
if is_htmlish and SANITIZE_HTML:
if element in self.can_contain_dangerous_markup:
output = _sanitizeHTML(output, self.encoding, self.contentparams.get('type', u'text/html'))
if self.encoding and not isinstance(output, unicode):
output = output.decode(self.encoding, 'ignore')
# address common error where people take data that is already
# utf-8, presume that it is iso-8859-1, and re-encode it.
if self.encoding in (u'utf-8', u'utf-8_INVALID_PYTHON_3') and isinstance(output, unicode):
try:
output = output.encode('iso-8859-1').decode('utf-8')
except (UnicodeEncodeError, UnicodeDecodeError):
pass
# map win-1252 extensions to the proper code points
if isinstance(output, unicode):
output = output.translate(_cp1252)
# categories/tags/keywords/whatever are handled in _end_category
if element == 'category':
return output
if element == 'title' and -1 < self.title_depth <= self.depth:
return output
# store output in appropriate place(s)
if self.inentry and not self.insource:
if element == 'content':
self.entries[-1].setdefault(element, [])
contentparams = copy.deepcopy(self.contentparams)
contentparams['value'] = output
self.entries[-1][element].append(contentparams)
elif element == 'link':
if not self.inimage:
# query variables in urls in link elements are improperly
# converted from `?a=1&b=2` to `?a=1&b;=2` as if they're
# unhandled character references. fix this special case.
output = re.sub("&([A-Za-z0-9_]+);", "&\g<1>", output)
self.entries[-1][element] = output
if output:
self.entries[-1]['links'][-1]['href'] = output
else:
if element == 'description':
element = 'summary'
old_value_depth = self.property_depth_map.setdefault(self.entries[-1], {}).get(element)
if old_value_depth is None or self.depth <= old_value_depth:
self.property_depth_map[self.entries[-1]][element] = self.depth
self.entries[-1][element] = output
if self.incontent:
contentparams = copy.deepcopy(self.contentparams)
contentparams['value'] = output
self.entries[-1][element + '_detail'] = contentparams
elif (self.infeed or self.insource):# and (not self.intextinput) and (not self.inimage):
context = self._getContext()
if element == 'description':
element = 'subtitle'
context[element] = output
if element == 'link':
# fix query variables; see above for the explanation
output = re.sub("&([A-Za-z0-9_]+);", "&\g<1>", output)
context[element] = output
context['links'][-1]['href'] = output
elif self.incontent:
contentparams = copy.deepcopy(self.contentparams)
contentparams['value'] = output
context[element + '_detail'] = contentparams
return output
def pushContent(self, tag, attrsD, defaultContentType, expectingText):
self.incontent += 1
if self.lang:
self.lang=self.lang.replace('_','-')
self.contentparams = FeedParserDict({
'type': self.mapContentType(attrsD.get('type', defaultContentType)),
'language': self.lang,
'base': self.baseuri})
self.contentparams['base64'] = self._isBase64(attrsD, self.contentparams)
self.push(tag, expectingText)
def popContent(self, tag):
value = self.pop(tag)
self.incontent -= 1
self.contentparams.clear()
return value
# a number of elements in a number of RSS variants are nominally plain
# text, but this is routinely ignored. This is an attempt to detect
# the most common cases. As false positives often result in silent
# data loss, this function errs on the conservative side.
@staticmethod
def lookslikehtml(s):
# must have a close tag or an entity reference to qualify
if not (re.search(r'</(\w+)>',s) or re.search("&#?\w+;",s)):
return
# all tags must be in a restricted subset of valid HTML tags
if filter(lambda t: t.lower() not in _HTMLSanitizer.acceptable_elements,
re.findall(r'</?(\w+)',s)):
return
# all entities must have been defined as valid HTML entities
if filter(lambda e: e not in entitydefs.keys(), re.findall(r'&(\w+);', s)):
return
return 1
def _mapToStandardPrefix(self, name):
colonpos = name.find(':')
if colonpos <> -1:
prefix = name[:colonpos]
suffix = name[colonpos+1:]
prefix = self.namespacemap.get(prefix, prefix)
name = prefix + ':' + suffix
return name
def _getAttribute(self, attrsD, name):
return attrsD.get(self._mapToStandardPrefix(name))
def _isBase64(self, attrsD, contentparams):
if attrsD.get('mode', '') == 'base64':
return 1
if self.contentparams['type'].startswith(u'text/'):
return 0
if self.contentparams['type'].endswith(u'+xml'):
return 0
if self.contentparams['type'].endswith(u'/xml'):
return 0
return 1
def _itsAnHrefDamnIt(self, attrsD):
href = attrsD.get('url', attrsD.get('uri', attrsD.get('href', None)))
if href:
try:
del attrsD['url']
except KeyError:
pass
try:
del attrsD['uri']
except KeyError:
pass
attrsD['href'] = href
return attrsD
def _save(self, key, value, overwrite=False):
context = self._getContext()
if overwrite:
context[key] = value
else:
context.setdefault(key, value)
def _start_rss(self, attrsD):
versionmap = {'0.91': u'rss091u',
'0.92': u'rss092',
'0.93': u'rss093',
'0.94': u'rss094'}
#If we're here then this is an RSS feed.
#If we don't have a version or have a version that starts with something
#other than RSS then there's been a mistake. Correct it.
if not self.version or not self.version.startswith(u'rss'):
attr_version = attrsD.get('version', '')
version = versionmap.get(attr_version)
if version:
self.version = version
elif attr_version.startswith('2.'):
self.version = u'rss20'
else:
self.version = u'rss'
def _start_channel(self, attrsD):
self.infeed = 1
self._cdf_common(attrsD)
def _cdf_common(self, attrsD):
if 'lastmod' in attrsD:
self._start_modified({})
self.elementstack[-1][-1] = attrsD['lastmod']
self._end_modified()
if 'href' in attrsD:
self._start_link({})
self.elementstack[-1][-1] = attrsD['href']
self._end_link()
def _start_feed(self, attrsD):
self.infeed = 1
versionmap = {'0.1': u'atom01',
'0.2': u'atom02',
'0.3': u'atom03'}
if not self.version:
attr_version = attrsD.get('version')
version = versionmap.get(attr_version)
if version:
self.version = version
else:
self.version = u'atom'
def _end_channel(self):
self.infeed = 0
_end_feed = _end_channel
def _start_image(self, attrsD):
context = self._getContext()
if not self.inentry:
context.setdefault('image', FeedParserDict())
self.inimage = 1
self.title_depth = -1
self.push('image', 0)
def _end_image(self):
self.pop('image')
self.inimage = 0
def _start_textinput(self, attrsD):
context = self._getContext()
context.setdefault('textinput', FeedParserDict())
self.intextinput = 1
self.title_depth = -1
self.push('textinput', 0)
_start_textInput = _start_textinput
def _end_textinput(self):
self.pop('textinput')
self.intextinput = 0
_end_textInput = _end_textinput
def _start_author(self, attrsD):
self.inauthor = 1
self.push('author', 1)
# Append a new FeedParserDict when expecting an author
context = self._getContext()
context.setdefault('authors', [])
context['authors'].append(FeedParserDict())
_start_managingeditor = _start_author
_start_dc_author = _start_author
_start_dc_creator = _start_author
_start_itunes_author = _start_author
def _end_author(self):
self.pop('author')
self.inauthor = 0
self._sync_author_detail()
_end_managingeditor = _end_author
_end_dc_author = _end_author
_end_dc_creator = _end_author
_end_itunes_author = _end_author
def _start_itunes_owner(self, attrsD):
self.inpublisher = 1
self.push('publisher', 0)
def _end_itunes_owner(self):
self.pop('publisher')
self.inpublisher = 0
self._sync_author_detail('publisher')
def _start_contributor(self, attrsD):
self.incontributor = 1
context = self._getContext()
context.setdefault('contributors', [])
context['contributors'].append(FeedParserDict())
self.push('contributor', 0)
def _end_contributor(self):
self.pop('contributor')
self.incontributor = 0
def _start_dc_contributor(self, attrsD):
self.incontributor = 1
context = self._getContext()
context.setdefault('contributors', [])
context['contributors'].append(FeedParserDict())
self.push('name', 0)
def _end_dc_contributor(self):
self._end_name()
self.incontributor = 0
def _start_name(self, attrsD):
self.push('name', 0)
_start_itunes_name = _start_name
def _end_name(self):
value = self.pop('name')
if self.inpublisher:
self._save_author('name', value, 'publisher')
elif self.inauthor:
self._save_author('name', value)
elif self.incontributor:
self._save_contributor('name', value)
elif self.intextinput:
context = self._getContext()
context['name'] = value
_end_itunes_name = _end_name
def _start_width(self, attrsD):
self.push('width', 0)
def _end_width(self):
value = self.pop('width')
try:
value = int(value)
except ValueError:
value = 0
if self.inimage:
context = self._getContext()
context['width'] = value
def _start_height(self, attrsD):
self.push('height', 0)
def _end_height(self):
value = self.pop('height')
try:
value = int(value)
except ValueError:
value = 0
if self.inimage:
context = self._getContext()
context['height'] = value
def _start_url(self, attrsD):
self.push('href', 1)
_start_homepage = _start_url
_start_uri = _start_url
def _end_url(self):
value = self.pop('href')
if self.inauthor:
self._save_author('href', value)
elif self.incontributor:
self._save_contributor('href', value)
_end_homepage = _end_url
_end_uri = _end_url
def _start_email(self, attrsD):
self.push('email', 0)
_start_itunes_email = _start_email
def _end_email(self):
value = self.pop('email')
if self.inpublisher:
self._save_author('email', value, 'publisher')
elif self.inauthor:
self._save_author('email', value)
elif self.incontributor:
self._save_contributor('email', value)
_end_itunes_email = _end_email
def _getContext(self):
if self.insource:
context = self.sourcedata
elif self.inimage and 'image' in self.feeddata:
context = self.feeddata['image']
elif self.intextinput:
context = self.feeddata['textinput']
elif self.inentry:
context = self.entries[-1]
else:
context = self.feeddata
return context
def _save_author(self, key, value, prefix='author'):
context = self._getContext()
context.setdefault(prefix + '_detail', FeedParserDict())
context[prefix + '_detail'][key] = value
self._sync_author_detail()
context.setdefault('authors', [FeedParserDict()])
context['authors'][-1][key] = value
def _save_contributor(self, key, value):
context = self._getContext()
context.setdefault('contributors', [FeedParserDict()])
context['contributors'][-1][key] = value
def _sync_author_detail(self, key='author'):
context = self._getContext()
detail = context.get('%s_detail' % key)
if detail:
name = detail.get('name')
email = detail.get('email')
if name and email:
context[key] = u'%s (%s)' % (name, email)
elif name:
context[key] = name
elif email:
context[key] = email
else:
author, email = context.get(key), None
if not author:
return
emailmatch = re.search(ur'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))(\?subject=\S+)?''', author)
if emailmatch:
email = emailmatch.group(0)
# probably a better way to do the following, but it passes all the tests
author = author.replace(email, u'')
author = author.replace(u'()', u'')
author = author.replace(u'<>', u'')
author = author.replace(u'<>', u'')
author = author.strip()
if author and (author[0] == u'('):
author = author[1:]
if author and (author[-1] == u')'):
author = author[:-1]
author = author.strip()
if author or email:
context.setdefault('%s_detail' % key, FeedParserDict())
if author:
context['%s_detail' % key]['name'] = author
if email:
context['%s_detail' % key]['email'] = email
def _start_subtitle(self, attrsD):
self.pushContent('subtitle', attrsD, u'text/plain', 1)
_start_tagline = _start_subtitle
_start_itunes_subtitle = _start_subtitle
def _end_subtitle(self):
self.popContent('subtitle')
_end_tagline = _end_subtitle
_end_itunes_subtitle = _end_subtitle
def _start_rights(self, attrsD):
self.pushContent('rights', attrsD, u'text/plain', 1)
_start_dc_rights = _start_rights
_start_copyright = _start_rights
def _end_rights(self):
self.popContent('rights')
_end_dc_rights = _end_rights
_end_copyright = _end_rights
def _start_item(self, attrsD):
self.entries.append(FeedParserDict())
self.push('item', 0)
self.inentry = 1
self.guidislink = 0
self.title_depth = -1
id = self._getAttribute(attrsD, 'rdf:about')
if id:
context = self._getContext()
context['id'] = id
self._cdf_common(attrsD)
_start_entry = _start_item
def _end_item(self):
self.pop('item')
self.inentry = 0
_end_entry = _end_item
def _start_dc_language(self, attrsD):
self.push('language', 1)
_start_language = _start_dc_language
def _end_dc_language(self):
self.lang = self.pop('language')
_end_language = _end_dc_language
def _start_dc_publisher(self, attrsD):
self.push('publisher', 1)
_start_webmaster = _start_dc_publisher
def _end_dc_publisher(self):
self.pop('publisher')
self._sync_author_detail('publisher')
_end_webmaster = _end_dc_publisher
def _start_published(self, attrsD):
self.push('published', 1)
_start_dcterms_issued = _start_published
_start_issued = _start_published
_start_pubdate = _start_published
def _end_published(self):
value = self.pop('published')
self._save('published_parsed', _parse_date(value), overwrite=True)
_end_dcterms_issued = _end_published
_end_issued = _end_published
_end_pubdate = _end_published
def _start_updated(self, attrsD):
self.push('updated', 1)
_start_modified = _start_updated
_start_dcterms_modified = _start_updated
_start_dc_date = _start_updated
_start_lastbuilddate = _start_updated
def _end_updated(self):
value = self.pop('updated')
parsed_value = _parse_date(value)
self._save('updated_parsed', parsed_value, overwrite=True)
_end_modified = _end_updated
_end_dcterms_modified = _end_updated
_end_dc_date = _end_updated
_end_lastbuilddate = _end_updated
def _start_created(self, attrsD):
self.push('created', 1)
_start_dcterms_created = _start_created
def _end_created(self):
value = self.pop('created')
self._save('created_parsed', _parse_date(value), overwrite=True)
_end_dcterms_created = _end_created
def _start_expirationdate(self, attrsD):
self.push('expired', 1)
def _end_expirationdate(self):
self._save('expired_parsed', _parse_date(self.pop('expired')), overwrite=True)
def _start_cc_license(self, attrsD):
context = self._getContext()
value = self._getAttribute(attrsD, 'rdf:resource')
attrsD = FeedParserDict()
attrsD['rel'] = u'license'
if value:
attrsD['href']=value
context.setdefault('links', []).append(attrsD)
def _start_creativecommons_license(self, attrsD):
self.push('license', 1)
_start_creativeCommons_license = _start_creativecommons_license
def _end_creativecommons_license(self):
value = self.pop('license')
context = self._getContext()
attrsD = FeedParserDict()
attrsD['rel'] = u'license'
if value:
attrsD['href'] = value
context.setdefault('links', []).append(attrsD)
del context['license']
_end_creativeCommons_license = _end_creativecommons_license
def _addXFN(self, relationships, href, name):
context = self._getContext()
xfn = context.setdefault('xfn', [])
value = FeedParserDict({'relationships': relationships, 'href': href, 'name': name})
if value not in xfn:
xfn.append(value)
def _addTag(self, term, scheme, label):
context = self._getContext()
tags = context.setdefault('tags', [])
if (not term) and (not scheme) and (not label):
return
value = FeedParserDict({'term': term, 'scheme': scheme, 'label': label})
if value not in tags:
tags.append(value)
def _start_category(self, attrsD):
term = attrsD.get('term')
scheme = attrsD.get('scheme', attrsD.get('domain'))
label = attrsD.get('label')
self._addTag(term, scheme, label)
self.push('category', 1)
_start_dc_subject = _start_category
_start_keywords = _start_category
def _start_media_category(self, attrsD):
attrsD.setdefault('scheme', u'http://search.yahoo.com/mrss/category_schema')
self._start_category(attrsD)
def _end_itunes_keywords(self):
for term in self.pop('itunes_keywords').split(','):
if term.strip():
self._addTag(term.strip(), u'http://www.itunes.com/', None)
def _start_itunes_category(self, attrsD):
self._addTag(attrsD.get('text'), u'http://www.itunes.com/', None)
self.push('category', 1)
def _end_category(self):
value = self.pop('category')
if not value:
return
context = self._getContext()
tags = context['tags']
if value and len(tags) and not tags[-1]['term']:
tags[-1]['term'] = value
else:
self._addTag(value, None, None)
_end_dc_subject = _end_category
_end_keywords = _end_category
_end_itunes_category = _end_category
_end_media_category = _end_category
def _start_cloud(self, attrsD):
self._getContext()['cloud'] = FeedParserDict(attrsD)
def _start_link(self, attrsD):
attrsD.setdefault('rel', u'alternate')
if attrsD['rel'] == u'self':
attrsD.setdefault('type', u'application/atom+xml')
else:
attrsD.setdefault('type', u'text/html')
context = self._getContext()
attrsD = self._itsAnHrefDamnIt(attrsD)
if 'href' in attrsD:
attrsD['href'] = self.resolveURI(attrsD['href'])
expectingText = self.infeed or self.inentry or self.insource
context.setdefault('links', [])
if not (self.inentry and self.inimage):
context['links'].append(FeedParserDict(attrsD))
if 'href' in attrsD:
expectingText = 0
if (attrsD.get('rel') == u'alternate') and (self.mapContentType(attrsD.get('type')) in self.html_types):
context['link'] = attrsD['href']
else:
self.push('link', expectingText)
def _end_link(self):
value = self.pop('link')
def _start_guid(self, attrsD):
self.guidislink = (attrsD.get('ispermalink', 'true') == 'true')
self.push('id', 1)
_start_id = _start_guid
def _end_guid(self):
value = self.pop('id')
self._save('guidislink', self.guidislink and 'link' not in self._getContext())
if self.guidislink:
# guid acts as link, but only if 'ispermalink' is not present or is 'true',
# and only if the item doesn't already have a link element
self._save('link', value)
_end_id = _end_guid
def _start_title(self, attrsD):
if self.svgOK:
return self.unknown_starttag('title', attrsD.items())
self.pushContent('title', attrsD, u'text/plain', self.infeed or self.inentry or self.insource)
_start_dc_title = _start_title
_start_media_title = _start_title
def _end_title(self):
if self.svgOK:
return
value = self.popContent('title')
if not value:
return
self.title_depth = self.depth
_end_dc_title = _end_title
def _end_media_title(self):
title_depth = self.title_depth
self._end_title()
self.title_depth = title_depth
def _start_description(self, attrsD):
context = self._getContext()
if 'summary' in context:
self._summaryKey = 'content'
self._start_content(attrsD)
else:
self.pushContent('description', attrsD, u'text/html', self.infeed or self.inentry or self.insource)
_start_dc_description = _start_description
def _start_abstract(self, attrsD):
self.pushContent('description', attrsD, u'text/plain', self.infeed or self.inentry or self.insource)
def _end_description(self):
if self._summaryKey == 'content':
self._end_content()
else:
value = self.popContent('description')
self._summaryKey = None
_end_abstract = _end_description
_end_dc_description = _end_description
def _start_info(self, attrsD):
self.pushContent('info', attrsD, u'text/plain', 1)
_start_feedburner_browserfriendly = _start_info
def _end_info(self):
self.popContent('info')
_end_feedburner_browserfriendly = _end_info
def _start_generator(self, attrsD):
if attrsD:
attrsD = self._itsAnHrefDamnIt(attrsD)
if 'href' in attrsD:
attrsD['href'] = self.resolveURI(attrsD['href'])
self._getContext()['generator_detail'] = FeedParserDict(attrsD)
self.push('generator', 1)
def _end_generator(self):
value = self.pop('generator')
context = self._getContext()
if 'generator_detail' in context:
context['generator_detail']['name'] = value
def _start_admin_generatoragent(self, attrsD):
self.push('generator', 1)
value = self._getAttribute(attrsD, 'rdf:resource')
if value:
self.elementstack[-1][2].append(value)
self.pop('generator')
self._getContext()['generator_detail'] = FeedParserDict({'href': value})
def _start_admin_errorreportsto(self, attrsD):
self.push('errorreportsto', 1)
value = self._getAttribute(attrsD, 'rdf:resource')
if value:
self.elementstack[-1][2].append(value)
self.pop('errorreportsto')
def _start_summary(self, attrsD):
context = self._getContext()
if 'summary' in context:
self._summaryKey = 'content'
self._start_content(attrsD)
else:
self._summaryKey = 'summary'
self.pushContent(self._summaryKey, attrsD, u'text/plain', 1)
_start_itunes_summary = _start_summary
def _end_summary(self):
if self._summaryKey == 'content':
self._end_content()
else:
self.popContent(self._summaryKey or 'summary')
self._summaryKey = None
_end_itunes_summary = _end_summary
def _start_enclosure(self, attrsD):
attrsD = self._itsAnHrefDamnIt(attrsD)
context = self._getContext()
attrsD['rel'] = u'enclosure'
context.setdefault('links', []).append(FeedParserDict(attrsD))
def _start_source(self, attrsD):
if 'url' in attrsD:
# This means that we're processing a source element from an RSS 2.0 feed
self.sourcedata['href'] = attrsD[u'url']
self.push('source', 1)
self.insource = 1
self.title_depth = -1
def _end_source(self):
self.insource = 0
value = self.pop('source')
if value:
self.sourcedata['title'] = value
self._getContext()['source'] = copy.deepcopy(self.sourcedata)
self.sourcedata.clear()
def _start_content(self, attrsD):
self.pushContent('content', attrsD, u'text/plain', 1)
src = attrsD.get('src')
if src:
self.contentparams['src'] = src
self.push('content', 1)
def _start_body(self, attrsD):
self.pushContent('content', attrsD, u'application/xhtml+xml', 1)
_start_xhtml_body = _start_body
def _start_content_encoded(self, attrsD):
self.pushContent('content', attrsD, u'text/html', 1)
_start_fullitem = _start_content_encoded
def _end_content(self):
copyToSummary = self.mapContentType(self.contentparams.get('type')) in ([u'text/plain'] + self.html_types)
value = self.popContent('content')
if copyToSummary:
self._save('summary', value)
_end_body = _end_content
_end_xhtml_body = _end_content
_end_content_encoded = _end_content
_end_fullitem = _end_content
def _start_itunes_image(self, attrsD):
self.push('itunes_image', 0)
if attrsD.get('href'):
self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')})
elif attrsD.get('url'):
self._getContext()['image'] = FeedParserDict({'href': attrsD.get('url')})
_start_itunes_link = _start_itunes_image
def _end_itunes_block(self):
value = self.pop('itunes_block', 0)
self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0
def _end_itunes_explicit(self):
value = self.pop('itunes_explicit', 0)
# Convert 'yes' -> True, 'clean' to False, and any other value to None
# False and None both evaluate as False, so the difference can be ignored
# by applications that only need to know if the content is explicit.
self._getContext()['itunes_explicit'] = (None, False, True)[(value == 'yes' and 2) or value == 'clean' or 0]
def _start_media_content(self, attrsD):
context = self._getContext()
context.setdefault('media_content', [])
context['media_content'].append(attrsD)
def _start_media_thumbnail(self, attrsD):
context = self._getContext()
context.setdefault('media_thumbnail', [])
self.push('url', 1) # new
context['media_thumbnail'].append(attrsD)
def _end_media_thumbnail(self):
url = self.pop('url')
context = self._getContext()
if url != None and len(url.strip()) != 0:
if 'url' not in context['media_thumbnail'][-1]:
context['media_thumbnail'][-1]['url'] = url
def _start_media_player(self, attrsD):
self.push('media_player', 0)
self._getContext()['media_player'] = FeedParserDict(attrsD)
def _end_media_player(self):
value = self.pop('media_player')
context = self._getContext()
context['media_player']['content'] = value
def _start_newlocation(self, attrsD):
self.push('newlocation', 1)
def _end_newlocation(self):
url = self.pop('newlocation')
context = self._getContext()
# don't set newlocation if the context isn't right
if context is not self.feeddata:
return
context['newlocation'] = _makeSafeAbsoluteURI(self.baseuri, url.strip())
if _XML_AVAILABLE:
class _StrictFeedParser(_FeedParserMixin, xml.sax.handler.ContentHandler):
def __init__(self, baseuri, baselang, encoding):
xml.sax.handler.ContentHandler.__init__(self)
_FeedParserMixin.__init__(self, baseuri, baselang, encoding)
self.bozo = 0
self.exc = None
self.decls = {}
def startPrefixMapping(self, prefix, uri):
if not uri:
return
# Jython uses '' instead of None; standardize on None
prefix = prefix or None
self.trackNamespace(prefix, uri)
if prefix and uri == 'http://www.w3.org/1999/xlink':
self.decls['xmlns:' + prefix] = uri
def startElementNS(self, name, qname, attrs):
namespace, localname = name
lowernamespace = str(namespace or '').lower()
if lowernamespace.find(u'backend.userland.com/rss') <> -1:
# match any backend.userland.com namespace
namespace = u'http://backend.userland.com/rss'
lowernamespace = namespace
if qname and qname.find(':') > 0:
givenprefix = qname.split(':')[0]
else:
givenprefix = None
prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
if givenprefix and (prefix == None or (prefix == '' and lowernamespace == '')) and givenprefix not in self.namespacesInUse:
raise UndeclaredNamespace, "'%s' is not associated with a namespace" % givenprefix
localname = str(localname).lower()
# qname implementation is horribly broken in Python 2.1 (it
# doesn't report any), and slightly broken in Python 2.2 (it
# doesn't report the xml: namespace). So we match up namespaces
# with a known list first, and then possibly override them with
# the qnames the SAX parser gives us (if indeed it gives us any
# at all). Thanks to MatejC for helping me test this and
# tirelessly telling me that it didn't work yet.
attrsD, self.decls = self.decls, {}
if localname=='math' and namespace=='http://www.w3.org/1998/Math/MathML':
attrsD['xmlns']=namespace
if localname=='svg' and namespace=='http://www.w3.org/2000/svg':
attrsD['xmlns']=namespace
if prefix:
localname = prefix.lower() + ':' + localname
elif namespace and not qname: #Expat
for name,value in self.namespacesInUse.items():
if name and value == namespace:
localname = name + ':' + localname
break
for (namespace, attrlocalname), attrvalue in attrs.items():
lowernamespace = (namespace or '').lower()
prefix = self._matchnamespaces.get(lowernamespace, '')
if prefix:
attrlocalname = prefix + ':' + attrlocalname
attrsD[str(attrlocalname).lower()] = attrvalue
for qname in attrs.getQNames():
attrsD[str(qname).lower()] = attrs.getValueByQName(qname)
self.unknown_starttag(localname, attrsD.items())
def characters(self, text):
self.handle_data(text)
def endElementNS(self, name, qname):
namespace, localname = name
lowernamespace = str(namespace or '').lower()
if qname and qname.find(':') > 0:
givenprefix = qname.split(':')[0]
else:
givenprefix = ''
prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
if prefix:
localname = prefix + ':' + localname
elif namespace and not qname: #Expat
for name,value in self.namespacesInUse.items():
if name and value == namespace:
localname = name + ':' + localname
break
localname = str(localname).lower()
self.unknown_endtag(localname)
def error(self, exc):
self.bozo = 1
self.exc = exc
# drv_libxml2 calls warning() in some cases
warning = error
def fatalError(self, exc):
self.error(exc)
raise exc
class _BaseHTMLProcessor(sgmllib.SGMLParser):
special = re.compile('''[<>'"]''')
bare_ampersand = re.compile("&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)")
elements_no_end_tag = set([
'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame',
'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param',
'source', 'track', 'wbr'
])
def __init__(self, encoding, _type):
self.encoding = encoding
self._type = _type
sgmllib.SGMLParser.__init__(self)
def reset(self):
self.pieces = []
sgmllib.SGMLParser.reset(self)
def _shorttag_replace(self, match):
tag = match.group(1)
if tag in self.elements_no_end_tag:
return '<' + tag + ' />'
else:
return '<' + tag + '></' + tag + '>'
# By declaring these methods and overriding their compiled code
# with the code from sgmllib, the original code will execute in
# feedparser's scope instead of sgmllib's. This means that the
# `tagfind` and `charref` regular expressions will be found as
# they're declared above, not as they're declared in sgmllib.
def goahead(self, i):
pass
goahead.func_code = sgmllib.SGMLParser.goahead.func_code #@UndefinedVariable
def __parse_starttag(self, i):
pass
__parse_starttag.func_code = sgmllib.SGMLParser.parse_starttag.func_code #@UndefinedVariable
def parse_starttag(self,i):
j = self.__parse_starttag(i)
if self._type == 'application/xhtml+xml':
if j>2 and self.rawdata[j-2:j]=='/>':
self.unknown_endtag(self.lasttag)
return j
def feed(self, data):
data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'<!\1', data)
data = re.sub(r'<([^<>\s]+?)\s*/>', self._shorttag_replace, data)
data = data.replace(''', "'")
data = data.replace('"', '"')
try:
bytes
if bytes is str:
raise NameError
self.encoding = self.encoding + u'_INVALID_PYTHON_3'
except NameError:
if self.encoding and isinstance(data, unicode):
data = data.encode(self.encoding)
sgmllib.SGMLParser.feed(self, data)
sgmllib.SGMLParser.close(self)
def normalize_attrs(self, attrs):
if not attrs:
return attrs
# utility method to be called by descendants
attrs = dict([(k.lower(), v) for k, v in attrs]).items()
attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
attrs.sort()
return attrs
def unknown_starttag(self, tag, attrs):
# called for each start tag
# attrs is a list of (attr, value) tuples
# e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')]
uattrs = []
strattrs=''
if attrs:
for key, value in attrs:
value=value.replace('>','>').replace('<','<').replace('"','"')
value = self.bare_ampersand.sub("&", value)
# thanks to Kevin Marks for this breathtaking hack to deal with (valid) high-bit attribute values in UTF-8 feeds
if not isinstance(value, unicode):
value = value.decode(self.encoding, 'ignore')
try:
# Currently, in Python 3 the key is already a str, and cannot be decoded again
uattrs.append((unicode(key, self.encoding), value))
except TypeError:
uattrs.append((key, value))
strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs])
if self.encoding:
try:
strattrs = strattrs.encode(self.encoding)
except (UnicodeEncodeError, LookupError):
pass
if tag in self.elements_no_end_tag:
self.pieces.append('<%s%s />' % (tag, strattrs))
else:
self.pieces.append('<%s%s>' % (tag, strattrs))
def unknown_endtag(self, tag):
# called for each end tag, e.g. for </pre>, tag will be 'pre'
# Reconstruct the original end tag.
if tag not in self.elements_no_end_tag:
self.pieces.append("</%s>" % tag)
def handle_charref(self, ref):
# called for each character reference, e.g. for ' ', ref will be '160'
# Reconstruct the original character reference.
if ref.startswith('x'):
value = int(ref[1:], 16)
else:
value = int(ref)
if value in _cp1252:
self.pieces.append('&#%s;' % hex(ord(_cp1252[value]))[1:])
else:
self.pieces.append('&#%s;' % ref)
def handle_entityref(self, ref):
# called for each entity reference, e.g. for '©', ref will be 'copy'
# Reconstruct the original entity reference.
if ref in name2codepoint or ref == 'apos':
self.pieces.append('&%s;' % ref)
else:
self.pieces.append('&%s' % ref)
def handle_data(self, text):
# called for each block of plain text, i.e. outside of any tag and
# not containing any character or entity references
# Store the original text verbatim.
self.pieces.append(text)
def handle_comment(self, text):
# called for each HTML comment, e.g. <!-- insert Javascript code here -->
# Reconstruct the original comment.
self.pieces.append('<!--%s-->' % text)
def handle_pi(self, text):
# called for each processing instruction, e.g. <?instruction>
# Reconstruct original processing instruction.
self.pieces.append('<?%s>' % text)
def handle_decl(self, text):
# called for the DOCTYPE, if present, e.g.
# <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
# "http://www.w3.org/TR/html4/loose.dtd">
# Reconstruct original DOCTYPE
self.pieces.append('<!%s>' % text)
_new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*').match
def _scan_name(self, i, declstartpos):
rawdata = self.rawdata
n = len(rawdata)
if i == n:
return None, -1
m = self._new_declname_match(rawdata, i)
if m:
s = m.group()
name = s.strip()
if (i + len(s)) == n:
return None, -1 # end of buffer
return name.lower(), m.end()
else:
self.handle_data(rawdata)
# self.updatepos(declstartpos, i)
return None, -1
def convert_charref(self, name):
return '&#%s;' % name
def convert_entityref(self, name):
return '&%s;' % name
def output(self):
"""Return processed HTML as a single string"""
return ''.join([str(p) for p in self.pieces])
def parse_declaration(self, i):
try:
return sgmllib.SGMLParser.parse_declaration(self, i)
except sgmllib.SGMLParseError:
# escape the doctype declaration and continue parsing
self.handle_data('<')
return i+1
class _LooseFeedParser(_FeedParserMixin, _BaseHTMLProcessor):
def __init__(self, baseuri, baselang, encoding, entities):
sgmllib.SGMLParser.__init__(self)
_FeedParserMixin.__init__(self, baseuri, baselang, encoding)
_BaseHTMLProcessor.__init__(self, encoding, 'application/xhtml+xml')
self.entities=entities
def decodeEntities(self, element, data):
data = data.replace('<', '<')
data = data.replace('<', '<')
data = data.replace('<', '<')
data = data.replace('>', '>')
data = data.replace('>', '>')
data = data.replace('>', '>')
data = data.replace('&', '&')
data = data.replace('&', '&')
data = data.replace('"', '"')
data = data.replace('"', '"')
data = data.replace(''', ''')
data = data.replace(''', ''')
if not self.contentparams.get('type', u'xml').endswith(u'xml'):
data = data.replace('<', '<')
data = data.replace('>', '>')
data = data.replace('&', '&')
data = data.replace('"', '"')
data = data.replace(''', "'")
return data
def strattrs(self, attrs):
return ''.join([' %s="%s"' % (n,v.replace('"','"')) for n,v in attrs])
class _MicroformatsParser:
STRING = 1
DATE = 2
URI = 3
NODE = 4
EMAIL = 5
known_xfn_relationships = set(['contact', 'acquaintance', 'friend', 'met', 'co-worker', 'coworker', 'colleague', 'co-resident', 'coresident', 'neighbor', 'child', 'parent', 'sibling', 'brother', 'sister', 'spouse', 'wife', 'husband', 'kin', 'relative', 'muse', 'crush', 'date', 'sweetheart', 'me'])
known_binary_extensions = set(['zip','rar','exe','gz','tar','tgz','tbz2','bz2','z','7z','dmg','img','sit','sitx','hqx','deb','rpm','bz2','jar','rar','iso','bin','msi','mp2','mp3','ogg','ogm','mp4','m4v','m4a','avi','wma','wmv'])
def __init__(self, data, baseuri, encoding):
self.document = BeautifulSoup.BeautifulSoup(data)
self.baseuri = baseuri
self.encoding = encoding
if isinstance(data, unicode):
data = data.encode(encoding)
self.tags = []
self.enclosures = []
self.xfn = []
self.vcard = None
def vcardEscape(self, s):
if isinstance(s, basestring):
s = s.replace(',', '\\,').replace(';', '\\;').replace('\n', '\\n')
return s
def vcardFold(self, s):
s = re.sub(';+$', '', s)
sFolded = ''
iMax = 75
sPrefix = ''
while len(s) > iMax:
sFolded += sPrefix + s[:iMax] + '\n'
s = s[iMax:]
sPrefix = ' '
iMax = 74
sFolded += sPrefix + s
return sFolded
def normalize(self, s):
return re.sub(r'\s+', ' ', s).strip()
def unique(self, aList):
results = []
for element in aList:
if element not in results:
results.append(element)
return results
def toISO8601(self, dt):
return time.strftime('%Y-%m-%dT%H:%M:%SZ', dt)
def getPropertyValue(self, elmRoot, sProperty, iPropertyType=4, bAllowMultiple=0, bAutoEscape=0):
all = lambda x: 1
sProperty = sProperty.lower()
bFound = 0
bNormalize = 1
propertyMatch = {'class': re.compile(r'\b%s\b' % sProperty)}
if bAllowMultiple and (iPropertyType != self.NODE):
snapResults = []
containers = elmRoot(['ul', 'ol'], propertyMatch)
for container in containers:
snapResults.extend(container('li'))
bFound = (len(snapResults) != 0)
if not bFound:
snapResults = elmRoot(all, propertyMatch)
bFound = (len(snapResults) != 0)
if (not bFound) and (sProperty == 'value'):
snapResults = elmRoot('pre')
bFound = (len(snapResults) != 0)
bNormalize = not bFound
if not bFound:
snapResults = [elmRoot]
bFound = (len(snapResults) != 0)
arFilter = []
if sProperty == 'vcard':
snapFilter = elmRoot(all, propertyMatch)
for node in snapFilter:
if node.findParent(all, propertyMatch):
arFilter.append(node)
arResults = []
for node in snapResults:
if node not in arFilter:
arResults.append(node)
bFound = (len(arResults) != 0)
if not bFound:
if bAllowMultiple:
return []
elif iPropertyType == self.STRING:
return ''
elif iPropertyType == self.DATE:
return None
elif iPropertyType == self.URI:
return ''
elif iPropertyType == self.NODE:
return None
else:
return None
arValues = []
for elmResult in arResults:
sValue = None
if iPropertyType == self.NODE:
if bAllowMultiple:
arValues.append(elmResult)
continue
else:
return elmResult
sNodeName = elmResult.name.lower()
if (iPropertyType == self.EMAIL) and (sNodeName == 'a'):
sValue = (elmResult.get('href') or '').split('mailto:').pop().split('?')[0]
if sValue:
sValue = bNormalize and self.normalize(sValue) or sValue.strip()
if (not sValue) and (sNodeName == 'abbr'):
sValue = elmResult.get('title')
if sValue:
sValue = bNormalize and self.normalize(sValue) or sValue.strip()
if (not sValue) and (iPropertyType == self.URI):
if sNodeName == 'a':
sValue = elmResult.get('href')
elif sNodeName == 'img':
sValue = elmResult.get('src')
elif sNodeName == 'object':
sValue = elmResult.get('data')
if sValue:
sValue = bNormalize and self.normalize(sValue) or sValue.strip()
if (not sValue) and (sNodeName == 'img'):
sValue = elmResult.get('alt')
if sValue:
sValue = bNormalize and self.normalize(sValue) or sValue.strip()
if not sValue:
sValue = elmResult.renderContents()
sValue = re.sub(r'<\S[^>]*>', '', sValue)
sValue = sValue.replace('\r\n', '\n')
sValue = sValue.replace('\r', '\n')
if sValue:
sValue = bNormalize and self.normalize(sValue) or sValue.strip()
if not sValue:
continue
if iPropertyType == self.DATE:
sValue = _parse_date_iso8601(sValue)
if bAllowMultiple:
arValues.append(bAutoEscape and self.vcardEscape(sValue) or sValue)
else:
return bAutoEscape and self.vcardEscape(sValue) or sValue
return arValues
def findVCards(self, elmRoot, bAgentParsing=0):
sVCards = ''
if not bAgentParsing:
arCards = self.getPropertyValue(elmRoot, 'vcard', bAllowMultiple=1)
else:
arCards = [elmRoot]
for elmCard in arCards:
arLines = []
def processSingleString(sProperty):
sValue = self.getPropertyValue(elmCard, sProperty, self.STRING, bAutoEscape=1).decode(self.encoding)
if sValue:
arLines.append(self.vcardFold(sProperty.upper() + ':' + sValue))
return sValue or u''
def processSingleURI(sProperty):
sValue = self.getPropertyValue(elmCard, sProperty, self.URI)
if sValue:
sContentType = ''
sEncoding = ''
sValueKey = ''
if sValue.startswith('data:'):
sEncoding = ';ENCODING=b'
sContentType = sValue.split(';')[0].split('/').pop()
sValue = sValue.split(',', 1).pop()
else:
elmValue = self.getPropertyValue(elmCard, sProperty)
if elmValue:
if sProperty != 'url':
sValueKey = ';VALUE=uri'
sContentType = elmValue.get('type', '').strip().split('/').pop().strip()
sContentType = sContentType.upper()
if sContentType == 'OCTET-STREAM':
sContentType = ''
if sContentType:
sContentType = ';TYPE=' + sContentType.upper()
arLines.append(self.vcardFold(sProperty.upper() + sEncoding + sContentType + sValueKey + ':' + sValue))
def processTypeValue(sProperty, arDefaultType, arForceType=None):
arResults = self.getPropertyValue(elmCard, sProperty, bAllowMultiple=1)
for elmResult in arResults:
arType = self.getPropertyValue(elmResult, 'type', self.STRING, 1, 1)
if arForceType:
arType = self.unique(arForceType + arType)
if not arType:
arType = arDefaultType
sValue = self.getPropertyValue(elmResult, 'value', self.EMAIL, 0)
if sValue:
arLines.append(self.vcardFold(sProperty.upper() + ';TYPE=' + ','.join(arType) + ':' + sValue))
# AGENT
# must do this before all other properties because it is destructive
# (removes nested class="vcard" nodes so they don't interfere with
# this vcard's other properties)
arAgent = self.getPropertyValue(elmCard, 'agent', bAllowMultiple=1)
for elmAgent in arAgent:
if re.compile(r'\bvcard\b').search(elmAgent.get('class')):
sAgentValue = self.findVCards(elmAgent, 1) + '\n'
sAgentValue = sAgentValue.replace('\n', '\\n')
sAgentValue = sAgentValue.replace(';', '\\;')
if sAgentValue:
arLines.append(self.vcardFold('AGENT:' + sAgentValue))
# Completely remove the agent element from the parse tree
elmAgent.extract()
else:
sAgentValue = self.getPropertyValue(elmAgent, 'value', self.URI, bAutoEscape=1);
if sAgentValue:
arLines.append(self.vcardFold('AGENT;VALUE=uri:' + sAgentValue))
# FN (full name)
sFN = processSingleString('fn')
# N (name)
elmName = self.getPropertyValue(elmCard, 'n')
if elmName:
sFamilyName = self.getPropertyValue(elmName, 'family-name', self.STRING, bAutoEscape=1)
sGivenName = self.getPropertyValue(elmName, 'given-name', self.STRING, bAutoEscape=1)
arAdditionalNames = self.getPropertyValue(elmName, 'additional-name', self.STRING, 1, 1) + self.getPropertyValue(elmName, 'additional-names', self.STRING, 1, 1)
arHonorificPrefixes = self.getPropertyValue(elmName, 'honorific-prefix', self.STRING, 1, 1) + self.getPropertyValue(elmName, 'honorific-prefixes', self.STRING, 1, 1)
arHonorificSuffixes = self.getPropertyValue(elmName, 'honorific-suffix', self.STRING, 1, 1) + self.getPropertyValue(elmName, 'honorific-suffixes', self.STRING, 1, 1)
arLines.append(self.vcardFold('N:' + sFamilyName + ';' +
sGivenName + ';' +
','.join(arAdditionalNames) + ';' +
','.join(arHonorificPrefixes) + ';' +
','.join(arHonorificSuffixes)))
elif sFN:
# implied "N" optimization
# http://microformats.org/wiki/hcard#Implied_.22N.22_Optimization
arNames = self.normalize(sFN).split()
if len(arNames) == 2:
bFamilyNameFirst = (arNames[0].endswith(',') or
len(arNames[1]) == 1 or
((len(arNames[1]) == 2) and (arNames[1].endswith('.'))))
if bFamilyNameFirst:
arLines.append(self.vcardFold('N:' + arNames[0] + ';' + arNames[1]))
else:
arLines.append(self.vcardFold('N:' + arNames[1] + ';' + arNames[0]))
# SORT-STRING
sSortString = self.getPropertyValue(elmCard, 'sort-string', self.STRING, bAutoEscape=1)
if sSortString:
arLines.append(self.vcardFold('SORT-STRING:' + sSortString))
# NICKNAME
arNickname = self.getPropertyValue(elmCard, 'nickname', self.STRING, 1, 1)
if arNickname:
arLines.append(self.vcardFold('NICKNAME:' + ','.join(arNickname)))
# PHOTO
processSingleURI('photo')
# BDAY
dtBday = self.getPropertyValue(elmCard, 'bday', self.DATE)
if dtBday:
arLines.append(self.vcardFold('BDAY:' + self.toISO8601(dtBday)))
# ADR (address)
arAdr = self.getPropertyValue(elmCard, 'adr', bAllowMultiple=1)
for elmAdr in arAdr:
arType = self.getPropertyValue(elmAdr, 'type', self.STRING, 1, 1)
if not arType:
arType = ['intl','postal','parcel','work'] # default adr types, see RFC 2426 section 3.2.1
sPostOfficeBox = self.getPropertyValue(elmAdr, 'post-office-box', self.STRING, 0, 1)
sExtendedAddress = self.getPropertyValue(elmAdr, 'extended-address', self.STRING, 0, 1)
sStreetAddress = self.getPropertyValue(elmAdr, 'street-address', self.STRING, 0, 1)
sLocality = self.getPropertyValue(elmAdr, 'locality', self.STRING, 0, 1)
sRegion = self.getPropertyValue(elmAdr, 'region', self.STRING, 0, 1)
sPostalCode = self.getPropertyValue(elmAdr, 'postal-code', self.STRING, 0, 1)
sCountryName = self.getPropertyValue(elmAdr, 'country-name', self.STRING, 0, 1)
arLines.append(self.vcardFold('ADR;TYPE=' + ','.join(arType) + ':' +
sPostOfficeBox + ';' +
sExtendedAddress + ';' +
sStreetAddress + ';' +
sLocality + ';' +
sRegion + ';' +
sPostalCode + ';' +
sCountryName))
# LABEL
processTypeValue('label', ['intl','postal','parcel','work'])
# TEL (phone number)
processTypeValue('tel', ['voice'])
# EMAIL
processTypeValue('email', ['internet'], ['internet'])
# MAILER
processSingleString('mailer')
# TZ (timezone)
processSingleString('tz')
# GEO (geographical information)
elmGeo = self.getPropertyValue(elmCard, 'geo')
if elmGeo:
sLatitude = self.getPropertyValue(elmGeo, 'latitude', self.STRING, 0, 1)
sLongitude = self.getPropertyValue(elmGeo, 'longitude', self.STRING, 0, 1)
arLines.append(self.vcardFold('GEO:' + sLatitude + ';' + sLongitude))
# TITLE
processSingleString('title')
# ROLE
processSingleString('role')
# LOGO
processSingleURI('logo')
# ORG (organization)
elmOrg = self.getPropertyValue(elmCard, 'org')
if elmOrg:
sOrganizationName = self.getPropertyValue(elmOrg, 'organization-name', self.STRING, 0, 1)
if not sOrganizationName:
# implied "organization-name" optimization
# http://microformats.org/wiki/hcard#Implied_.22organization-name.22_Optimization
sOrganizationName = self.getPropertyValue(elmCard, 'org', self.STRING, 0, 1)
if sOrganizationName:
arLines.append(self.vcardFold('ORG:' + sOrganizationName))
else:
arOrganizationUnit = self.getPropertyValue(elmOrg, 'organization-unit', self.STRING, 1, 1)
arLines.append(self.vcardFold('ORG:' + sOrganizationName + ';' + ';'.join(arOrganizationUnit)))
# CATEGORY
arCategory = self.getPropertyValue(elmCard, 'category', self.STRING, 1, 1) + self.getPropertyValue(elmCard, 'categories', self.STRING, 1, 1)
if arCategory:
arLines.append(self.vcardFold('CATEGORIES:' + ','.join(arCategory)))
# NOTE
processSingleString('note')
# REV
processSingleString('rev')
# SOUND
processSingleURI('sound')
# UID
processSingleString('uid')
# URL
processSingleURI('url')
# CLASS
processSingleString('class')
# KEY
processSingleURI('key')
if arLines:
arLines = [u'BEGIN:vCard',u'VERSION:3.0'] + arLines + [u'END:vCard']
# XXX - this is super ugly; properly fix this with issue 148
for i, s in enumerate(arLines):
if not isinstance(s, unicode):
arLines[i] = s.decode('utf-8', 'ignore')
sVCards += u'\n'.join(arLines) + u'\n'
return sVCards.strip()
def isProbablyDownloadable(self, elm):
attrsD = elm.attrMap
if 'href' not in attrsD:
return 0
linktype = attrsD.get('type', '').strip()
if linktype.startswith('audio/') or \
linktype.startswith('video/') or \
(linktype.startswith('application/') and not linktype.endswith('xml')):
return 1
path = urlparse.urlparse(attrsD['href'])[2]
if path.find('.') == -1:
return 0
fileext = path.split('.').pop().lower()
return fileext in self.known_binary_extensions
def findTags(self):
all = lambda x: 1
for elm in self.document(all, {'rel': re.compile(r'\btag\b')}):
href = elm.get('href')
if not href:
continue
urlscheme, domain, path, params, query, fragment = \
urlparse.urlparse(_urljoin(self.baseuri, href))
segments = path.split('/')
tag = segments.pop()
if not tag:
if segments:
tag = segments.pop()
else:
# there are no tags
continue
tagscheme = urlparse.urlunparse((urlscheme, domain, '/'.join(segments), '', '', ''))
if not tagscheme.endswith('/'):
tagscheme += '/'
self.tags.append(FeedParserDict({"term": tag, "scheme": tagscheme, "label": elm.string or ''}))
def findEnclosures(self):
all = lambda x: 1
enclosure_match = re.compile(r'\benclosure\b')
for elm in self.document(all, {'href': re.compile(r'.+')}):
if not enclosure_match.search(elm.get('rel', u'')) and not self.isProbablyDownloadable(elm):
continue
if elm.attrMap not in self.enclosures:
self.enclosures.append(elm.attrMap)
if elm.string and not elm.get('title'):
self.enclosures[-1]['title'] = elm.string
def findXFN(self):
all = lambda x: 1
for elm in self.document(all, {'rel': re.compile('.+'), 'href': re.compile('.+')}):
rels = elm.get('rel', u'').split()
xfn_rels = [r for r in rels if r in self.known_xfn_relationships]
if xfn_rels:
self.xfn.append({"relationships": xfn_rels, "href": elm.get('href', ''), "name": elm.string})
def _parseMicroformats(htmlSource, baseURI, encoding):
if not BeautifulSoup:
return
try:
p = _MicroformatsParser(htmlSource, baseURI, encoding)
except UnicodeEncodeError:
# sgmllib throws this exception when performing lookups of tags
# with non-ASCII characters in them.
return
p.vcard = p.findVCards(p.document)
p.findTags()
p.findEnclosures()
p.findXFN()
return {"tags": p.tags, "enclosures": p.enclosures, "xfn": p.xfn, "vcard": p.vcard}
class _RelativeURIResolver(_BaseHTMLProcessor):
relative_uris = set([('a', 'href'),
('applet', 'codebase'),
('area', 'href'),
('blockquote', 'cite'),
('body', 'background'),
('del', 'cite'),
('form', 'action'),
('frame', 'longdesc'),
('frame', 'src'),
('iframe', 'longdesc'),
('iframe', 'src'),
('head', 'profile'),
('img', 'longdesc'),
('img', 'src'),
('img', 'usemap'),
('input', 'src'),
('input', 'usemap'),
('ins', 'cite'),
('link', 'href'),
('object', 'classid'),
('object', 'codebase'),
('object', 'data'),
('object', 'usemap'),
('q', 'cite'),
('script', 'src')])
def __init__(self, baseuri, encoding, _type):
_BaseHTMLProcessor.__init__(self, encoding, _type)
self.baseuri = baseuri
def resolveURI(self, uri):
return _makeSafeAbsoluteURI(self.baseuri, uri.strip())
def unknown_starttag(self, tag, attrs):
attrs = self.normalize_attrs(attrs)
attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs]
_BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
def _resolveRelativeURIs(htmlSource, baseURI, encoding, _type):
if not _SGML_AVAILABLE:
return htmlSource
p = _RelativeURIResolver(baseURI, encoding, _type)
p.feed(htmlSource)
return p.output()
def _makeSafeAbsoluteURI(base, rel=None):
# bail if ACCEPTABLE_URI_SCHEMES is empty
if not ACCEPTABLE_URI_SCHEMES:
try:
return _urljoin(base, rel or u'')
except ValueError:
return u''
if not base:
return rel or u''
if not rel:
try:
scheme = urlparse.urlparse(base)[0]
except ValueError:
return u''
if not scheme or scheme in ACCEPTABLE_URI_SCHEMES:
return base
return u''
try:
uri = _urljoin(base, rel)
except ValueError:
return u''
if uri.strip().split(':', 1)[0] not in ACCEPTABLE_URI_SCHEMES:
return u''
return uri
class _HTMLSanitizer(_BaseHTMLProcessor):
acceptable_elements = set(['a', 'abbr', 'acronym', 'address', 'area',
'article', 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button',
'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup',
'command', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn',
'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset',
'figcaption', 'figure', 'footer', 'font', 'form', 'header', 'h1',
'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', 'ins',
'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map', 'menu', 'meter',
'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup', 'option',
'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select',
'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong',
'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot',
'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video', 'noscript'])
acceptable_attributes = set(['abbr', 'accept', 'accept-charset', 'accesskey',
'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis',
'background', 'balance', 'bgcolor', 'bgproperties', 'border',
'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding',
'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff',
'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color', 'cols',
'colspan', 'compact', 'contenteditable', 'controls', 'coords', 'data',
'datafld', 'datapagesize', 'datasrc', 'datetime', 'default', 'delay',
'dir', 'disabled', 'draggable', 'dynsrc', 'enctype', 'end', 'face', 'for',
'form', 'frame', 'galleryimg', 'gutter', 'headers', 'height', 'hidefocus',
'hidden', 'high', 'href', 'hreflang', 'hspace', 'icon', 'id', 'inputmode',
'ismap', 'keytype', 'label', 'leftspacing', 'lang', 'list', 'longdesc',
'loop', 'loopcount', 'loopend', 'loopstart', 'low', 'lowsrc', 'max',
'maxlength', 'media', 'method', 'min', 'multiple', 'name', 'nohref',
'noshade', 'nowrap', 'open', 'optimum', 'pattern', 'ping', 'point-size',
'prompt', 'pqg', 'radiogroup', 'readonly', 'rel', 'repeat-max',
'repeat-min', 'replace', 'required', 'rev', 'rightspacing', 'rows',
'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src',
'start', 'step', 'summary', 'suppress', 'tabindex', 'target', 'template',
'title', 'toppadding', 'type', 'unselectable', 'usemap', 'urn', 'valign',
'value', 'variable', 'volume', 'vspace', 'vrml', 'width', 'wrap',
'xml:lang'])
unacceptable_elements_with_end_tag = set(['script', 'applet', 'style'])
acceptable_css_properties = set(['azimuth', 'background-color',
'border-bottom-color', 'border-collapse', 'border-color',
'border-left-color', 'border-right-color', 'border-top-color', 'clear',
'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font',
'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight',
'height', 'letter-spacing', 'line-height', 'overflow', 'pause',
'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness',
'speak', 'speak-header', 'speak-numeral', 'speak-punctuation',
'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent',
'unicode-bidi', 'vertical-align', 'voice-family', 'volume',
'white-space', 'width'])
# survey of common keywords found in feeds
acceptable_css_keywords = set(['auto', 'aqua', 'black', 'block', 'blue',
'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed',
'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left',
'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive',
'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top',
'transparent', 'underline', 'white', 'yellow'])
valid_css_values = re.compile('^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|' +
'\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$')
mathml_elements = set(['annotation', 'annotation-xml', 'maction', 'math',
'merror', 'mfenced', 'mfrac', 'mi', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded',
'mphantom', 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle',
'msub', 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',
'munderover', 'none', 'semantics'])
mathml_attributes = set(['actiontype', 'align', 'columnalign', 'columnalign',
'columnalign', 'close', 'columnlines', 'columnspacing', 'columnspan', 'depth',
'display', 'displaystyle', 'encoding', 'equalcolumns', 'equalrows',
'fence', 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness',
'lspace', 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant',
'maxsize', 'minsize', 'open', 'other', 'rowalign', 'rowalign', 'rowalign',
'rowlines', 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection',
'separator', 'separators', 'stretchy', 'width', 'width', 'xlink:href',
'xlink:show', 'xlink:type', 'xmlns', 'xmlns:xlink'])
# svgtiny - foreignObject + linearGradient + radialGradient + stop
svg_elements = set(['a', 'animate', 'animateColor', 'animateMotion',
'animateTransform', 'circle', 'defs', 'desc', 'ellipse', 'foreignObject',
'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern',
'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph', 'mpath',
'path', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'stop',
'svg', 'switch', 'text', 'title', 'tspan', 'use'])
# svgtiny + class + opacity + offset + xmlns + xmlns:xlink
svg_attributes = set(['accent-height', 'accumulate', 'additive', 'alphabetic',
'arabic-form', 'ascent', 'attributeName', 'attributeType',
'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height',
'class', 'color', 'color-rendering', 'content', 'cx', 'cy', 'd', 'dx',
'dy', 'descent', 'display', 'dur', 'end', 'fill', 'fill-opacity',
'fill-rule', 'font-family', 'font-size', 'font-stretch', 'font-style',
'font-variant', 'font-weight', 'from', 'fx', 'fy', 'g1', 'g2',
'glyph-name', 'gradientUnits', 'hanging', 'height', 'horiz-adv-x',
'horiz-origin-x', 'id', 'ideographic', 'k', 'keyPoints', 'keySplines',
'keyTimes', 'lang', 'mathematical', 'marker-end', 'marker-mid',
'marker-start', 'markerHeight', 'markerUnits', 'markerWidth', 'max',
'min', 'name', 'offset', 'opacity', 'orient', 'origin',
'overline-position', 'overline-thickness', 'panose-1', 'path',
'pathLength', 'points', 'preserveAspectRatio', 'r', 'refX', 'refY',
'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures',
'restart', 'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv',
'stop-color', 'stop-opacity', 'strikethrough-position',
'strikethrough-thickness', 'stroke', 'stroke-dasharray',
'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin',
'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'systemLanguage',
'target', 'text-anchor', 'to', 'transform', 'type', 'u1', 'u2',
'underline-position', 'underline-thickness', 'unicode', 'unicode-range',
'units-per-em', 'values', 'version', 'viewBox', 'visibility', 'width',
'widths', 'x', 'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole',
'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type',
'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y', 'y1',
'y2', 'zoomAndPan'])
svg_attr_map = None
svg_elem_map = None
acceptable_svg_properties = set([ 'fill', 'fill-opacity', 'fill-rule',
'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
'stroke-opacity'])
def reset(self):
_BaseHTMLProcessor.reset(self)
self.unacceptablestack = 0
self.mathmlOK = 0
self.svgOK = 0
def unknown_starttag(self, tag, attrs):
acceptable_attributes = self.acceptable_attributes
keymap = {}
if not tag in self.acceptable_elements or self.svgOK:
if tag in self.unacceptable_elements_with_end_tag:
self.unacceptablestack += 1
# add implicit namespaces to html5 inline svg/mathml
if self._type.endswith('html'):
if not dict(attrs).get('xmlns'):
if tag=='svg':
attrs.append( ('xmlns','http://www.w3.org/2000/svg') )
if tag=='math':
attrs.append( ('xmlns','http://www.w3.org/1998/Math/MathML') )
# not otherwise acceptable, perhaps it is MathML or SVG?
if tag=='math' and ('xmlns','http://www.w3.org/1998/Math/MathML') in attrs:
self.mathmlOK += 1
if tag=='svg' and ('xmlns','http://www.w3.org/2000/svg') in attrs:
self.svgOK += 1
# chose acceptable attributes based on tag class, else bail
if self.mathmlOK and tag in self.mathml_elements:
acceptable_attributes = self.mathml_attributes
elif self.svgOK and tag in self.svg_elements:
# for most vocabularies, lowercasing is a good idea. Many
# svg elements, however, are camel case
if not self.svg_attr_map:
lower=[attr.lower() for attr in self.svg_attributes]
mix=[a for a in self.svg_attributes if a not in lower]
self.svg_attributes = lower
self.svg_attr_map = dict([(a.lower(),a) for a in mix])
lower=[attr.lower() for attr in self.svg_elements]
mix=[a for a in self.svg_elements if a not in lower]
self.svg_elements = lower
self.svg_elem_map = dict([(a.lower(),a) for a in mix])
acceptable_attributes = self.svg_attributes
tag = self.svg_elem_map.get(tag,tag)
keymap = self.svg_attr_map
elif not tag in self.acceptable_elements:
return
# declare xlink namespace, if needed
if self.mathmlOK or self.svgOK:
if filter(lambda (n,v): n.startswith('xlink:'),attrs):
if not ('xmlns:xlink','http://www.w3.org/1999/xlink') in attrs:
attrs.append(('xmlns:xlink','http://www.w3.org/1999/xlink'))
clean_attrs = []
for key, value in self.normalize_attrs(attrs):
if key in acceptable_attributes:
key=keymap.get(key,key)
# make sure the uri uses an acceptable uri scheme
if key == u'href':
value = _makeSafeAbsoluteURI(value)
clean_attrs.append((key,value))
elif key=='style':
clean_value = self.sanitize_style(value)
if clean_value:
clean_attrs.append((key,clean_value))
_BaseHTMLProcessor.unknown_starttag(self, tag, clean_attrs)
def unknown_endtag(self, tag):
if not tag in self.acceptable_elements:
if tag in self.unacceptable_elements_with_end_tag:
self.unacceptablestack -= 1
if self.mathmlOK and tag in self.mathml_elements:
if tag == 'math' and self.mathmlOK:
self.mathmlOK -= 1
elif self.svgOK and tag in self.svg_elements:
tag = self.svg_elem_map.get(tag,tag)
if tag == 'svg' and self.svgOK:
self.svgOK -= 1
else:
return
_BaseHTMLProcessor.unknown_endtag(self, tag)
def handle_pi(self, text):
pass
def handle_decl(self, text):
pass
def handle_data(self, text):
if not self.unacceptablestack:
_BaseHTMLProcessor.handle_data(self, text)
def sanitize_style(self, style):
# disallow urls
style=re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ',style)
# gauntlet
if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style):
return ''
# This replaced a regexp that used re.match and was prone to pathological back-tracking.
if re.sub("\s*[-\w]+\s*:\s*[^:;]*;?", '', style).strip():
return ''
clean = []
for prop,value in re.findall("([-\w]+)\s*:\s*([^:;]*)",style):
if not value:
continue
if prop.lower() in self.acceptable_css_properties:
clean.append(prop + ': ' + value + ';')
elif prop.split('-')[0].lower() in ['background','border','margin','padding']:
for keyword in value.split():
if not keyword in self.acceptable_css_keywords and \
not self.valid_css_values.match(keyword):
break
else:
clean.append(prop + ': ' + value + ';')
elif self.svgOK and prop.lower() in self.acceptable_svg_properties:
clean.append(prop + ': ' + value + ';')
return ' '.join(clean)
def parse_comment(self, i, report=1):
ret = _BaseHTMLProcessor.parse_comment(self, i, report)
if ret >= 0:
return ret
# if ret == -1, this may be a malicious attempt to circumvent
# sanitization, or a page-destroying unclosed comment
match = re.compile(r'--[^>]*>').search(self.rawdata, i+4)
if match:
return match.end()
# unclosed comment; deliberately fail to handle_data()
return len(self.rawdata)
def _sanitizeHTML(htmlSource, encoding, _type):
if not _SGML_AVAILABLE:
return htmlSource
p = _HTMLSanitizer(encoding, _type)
htmlSource = htmlSource.replace('<![CDATA[', '<![CDATA[')
p.feed(htmlSource)
data = p.output()
if TIDY_MARKUP:
# loop through list of preferred Tidy interfaces looking for one that's installed,
# then set up a common _tidy function to wrap the interface-specific API.
_tidy = None
for tidy_interface in PREFERRED_TIDY_INTERFACES:
try:
if tidy_interface == "uTidy":
from tidy import parseString as _utidy #@UnresolvedImport
def _tidy(data, **kwargs):
return str(_utidy(data, **kwargs))
break
elif tidy_interface == "mxTidy":
from mx.Tidy import Tidy as _mxtidy #@UnresolvedImport
def _tidy(data, **kwargs):
nerrors, nwarnings, data, errordata = _mxtidy.tidy(data, **kwargs)
return data
break
except:
pass
if _tidy:
utf8 = isinstance(data, unicode)
if utf8:
data = data.encode('utf-8')
data = _tidy(data, output_xhtml=1, numeric_entities=1, wrap=0, char_encoding="utf8")
if utf8:
data = unicode(data, 'utf-8')
if data.count('<body'):
data = data.split('<body', 1)[1]
if data.count('>'):
data = data.split('>', 1)[1]
if data.count('</body'):
data = data.split('</body', 1)[0]
data = data.strip().replace('\r\n', '\n')
return data
class _FeedURLHandler(urllib2.HTTPDigestAuthHandler, urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler):
def http_error_default(self, req, fp, code, msg, headers):
# The default implementation just raises HTTPError.
# Forget that.
fp.status = code
return fp
def http_error_301(self, req, fp, code, msg, hdrs):
result = urllib2.HTTPRedirectHandler.http_error_301(self, req, fp,
code, msg, hdrs)
result.status = code
result.newurl = result.geturl()
return result
# The default implementations in urllib2.HTTPRedirectHandler
# are identical, so hardcoding a http_error_301 call above
# won't affect anything
http_error_300 = http_error_301
http_error_302 = http_error_301
http_error_303 = http_error_301
http_error_307 = http_error_301
def http_error_401(self, req, fp, code, msg, headers):
# Check if
# - server requires digest auth, AND
# - we tried (unsuccessfully) with basic auth, AND
# If all conditions hold, parse authentication information
# out of the Authorization header we sent the first time
# (for the username and password) and the WWW-Authenticate
# header the server sent back (for the realm) and retry
# the request with the appropriate digest auth headers instead.
# This evil genius hack has been brought to you by Aaron Swartz.
host = urlparse.urlparse(req.get_full_url())[1]
if base64 is None or 'Authorization' not in req.headers \
or 'WWW-Authenticate' not in headers:
return self.http_error_default(req, fp, code, msg, headers)
auth = _base64decode(req.headers['Authorization'].split(' ')[1])
user, passw = auth.split(':')
realm = re.findall('realm="([^"]*)"', headers['WWW-Authenticate'])[0]
self.add_password(realm, host, user, passw)
retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
self.reset_retry_count()
return retry
def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers, request_headers):
"""URL, filename, or string --> stream
This function lets you define parsers that take any input source
(URL, pathname to local or network file, or actual data as a string)
and deal with it in a uniform manner. Returned object is guaranteed
to have all the basic stdio read methods (read, readline, readlines).
Just .close() the object when you're done with it.
If the etag argument is supplied, it will be used as the value of an
If-None-Match request header.
If the modified argument is supplied, it can be a tuple of 9 integers
(as returned by gmtime() in the standard Python time module) or a date
string in any format supported by feedparser. Regardless, it MUST
be in GMT (Greenwich Mean Time). It will be reformatted into an
RFC 1123-compliant date and used as the value of an If-Modified-Since
request header.
If the agent argument is supplied, it will be used as the value of a
User-Agent request header.
If the referrer argument is supplied, it will be used as the value of a
Referer[sic] request header.
If handlers is supplied, it is a list of handlers used to build a
urllib2 opener.
if request_headers is supplied it is a dictionary of HTTP request headers
that will override the values generated by FeedParser.
"""
if hasattr(url_file_stream_or_string, 'read'):
return url_file_stream_or_string
if isinstance(url_file_stream_or_string, basestring) \
and urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp', 'file', 'feed'):
# Deal with the feed URI scheme
if url_file_stream_or_string.startswith('feed:http'):
url_file_stream_or_string = url_file_stream_or_string[5:]
elif url_file_stream_or_string.startswith('feed:'):
url_file_stream_or_string = 'http:' + url_file_stream_or_string[5:]
if not agent:
agent = USER_AGENT
# test for inline user:password for basic auth
auth = None
if base64:
urltype, rest = urllib.splittype(url_file_stream_or_string)
realhost, rest = urllib.splithost(rest)
if realhost:
user_passwd, realhost = urllib.splituser(realhost)
if user_passwd:
url_file_stream_or_string = '%s://%s%s' % (urltype, realhost, rest)
auth = base64.standard_b64encode(user_passwd).strip()
# iri support
if isinstance(url_file_stream_or_string, unicode):
url_file_stream_or_string = _convert_to_idn(url_file_stream_or_string)
# try to open with urllib2 (to use optional headers)
request = _build_urllib2_request(url_file_stream_or_string, agent, etag, modified, referrer, auth, request_headers)
opener = urllib2.build_opener(*tuple(handlers + [_FeedURLHandler()]))
opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent
try:
return opener.open(request)
finally:
opener.close() # JohnD
# try to open with native open function (if url_file_stream_or_string is a filename)
try:
return open(url_file_stream_or_string, 'rb')
except (IOError, UnicodeEncodeError, TypeError):
# if url_file_stream_or_string is a unicode object that
# cannot be converted to the encoding returned by
# sys.getfilesystemencoding(), a UnicodeEncodeError
# will be thrown
# If url_file_stream_or_string is a string that contains NULL
# (such as an XML document encoded in UTF-32), TypeError will
# be thrown.
pass
# treat url_file_stream_or_string as string
if isinstance(url_file_stream_or_string, unicode):
return _StringIO(url_file_stream_or_string.encode('utf-8'))
return _StringIO(url_file_stream_or_string)
def _convert_to_idn(url):
"""Convert a URL to IDN notation"""
# this function should only be called with a unicode string
# strategy: if the host cannot be encoded in ascii, then
# it'll be necessary to encode it in idn form
parts = list(urlparse.urlsplit(url))
try:
parts[1].encode('ascii')
except UnicodeEncodeError:
# the url needs to be converted to idn notation
host = parts[1].rsplit(':', 1)
newhost = []
port = u''
if len(host) == 2:
port = host.pop()
for h in host[0].split('.'):
newhost.append(h.encode('idna').decode('utf-8'))
parts[1] = '.'.join(newhost)
if port:
parts[1] += ':' + port
return urlparse.urlunsplit(parts)
else:
return url
def _build_urllib2_request(url, agent, etag, modified, referrer, auth, request_headers):
request = urllib2.Request(url)
request.add_header('User-Agent', agent)
if etag:
request.add_header('If-None-Match', etag)
if isinstance(modified, basestring):
modified = _parse_date(modified)
elif isinstance(modified, datetime.datetime):
modified = modified.utctimetuple()
if modified:
# format into an RFC 1123-compliant timestamp. We can't use
# time.strftime() since the %a and %b directives can be affected
# by the current locale, but RFC 2616 states that dates must be
# in English.
short_weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
request.add_header('If-Modified-Since', '%s, %02d %s %04d %02d:%02d:%02d GMT' % (short_weekdays[modified[6]], modified[2], months[modified[1] - 1], modified[0], modified[3], modified[4], modified[5]))
if referrer:
request.add_header('Referer', referrer)
if gzip and zlib:
request.add_header('Accept-encoding', 'gzip, deflate')
elif gzip:
request.add_header('Accept-encoding', 'gzip')
elif zlib:
request.add_header('Accept-encoding', 'deflate')
else:
request.add_header('Accept-encoding', '')
if auth:
request.add_header('Authorization', 'Basic %s' % auth)
if ACCEPT_HEADER:
request.add_header('Accept', ACCEPT_HEADER)
# use this for whatever -- cookies, special headers, etc
# [('Cookie','Something'),('x-special-header','Another Value')]
for header_name, header_value in request_headers.items():
request.add_header(header_name, header_value)
request.add_header('A-IM', 'feed') # RFC 3229 support
return request
_date_handlers = []
def registerDateHandler(func):
"""Register a date handler function (takes string, returns 9-tuple date in GMT)"""
_date_handlers.insert(0, func)
# ISO-8601 date parsing routines written by Fazal Majid.
# The ISO 8601 standard is very convoluted and irregular - a full ISO 8601
# parser is beyond the scope of feedparser and would be a worthwhile addition
# to the Python library.
# A single regular expression cannot parse ISO 8601 date formats into groups
# as the standard is highly irregular (for instance is 030104 2003-01-04 or
# 0301-04-01), so we use templates instead.
# Please note the order in templates is significant because we need a
# greedy match.
_iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-0MM?-?DD', 'YYYY-MM', 'YYYY-?OOO',
'YY-?MM-?DD', 'YY-?OOO', 'YYYY',
'-YY-?MM', '-OOO', '-YY',
'--MM-?DD', '--MM',
'---DD',
'CC', '']
_iso8601_re = [
tmpl.replace(
'YYYY', r'(?P<year>\d{4})').replace(
'YY', r'(?P<year>\d\d)').replace(
'MM', r'(?P<month>[01]\d)').replace(
'DD', r'(?P<day>[0123]\d)').replace(
'OOO', r'(?P<ordinal>[0123]\d\d)').replace(
'CC', r'(?P<century>\d\d$)')
+ r'(T?(?P<hour>\d{2}):(?P<minute>\d{2})'
+ r'(:(?P<second>\d{2}))?'
+ r'(\.(?P<fracsecond>\d+))?'
+ r'(?P<tz>[+-](?P<tzhour>\d{2})(:(?P<tzmin>\d{2}))?|Z)?)?'
for tmpl in _iso8601_tmpl]
try:
del tmpl
except NameError:
pass
_iso8601_matches = [re.compile(regex).match for regex in _iso8601_re]
try:
del regex
except NameError:
pass
def _parse_date_iso8601(dateString):
"""Parse a variety of ISO-8601-compatible formats like 20040105"""
m = None
for _iso8601_match in _iso8601_matches:
m = _iso8601_match(dateString)
if m:
break
if not m:
return
if m.span() == (0, 0):
return
params = m.groupdict()
ordinal = params.get('ordinal', 0)
if ordinal:
ordinal = int(ordinal)
else:
ordinal = 0
year = params.get('year', '--')
if not year or year == '--':
year = time.gmtime()[0]
elif len(year) == 2:
# ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993
year = 100 * int(time.gmtime()[0] / 100) + int(year)
else:
year = int(year)
month = params.get('month', '-')
if not month or month == '-':
# ordinals are NOT normalized by mktime, we simulate them
# by setting month=1, day=ordinal
if ordinal:
month = 1
else:
month = time.gmtime()[1]
month = int(month)
day = params.get('day', 0)
if not day:
# see above
if ordinal:
day = ordinal
elif params.get('century', 0) or \
params.get('year', 0) or params.get('month', 0):
day = 1
else:
day = time.gmtime()[2]
else:
day = int(day)
# special case of the century - is the first year of the 21st century
# 2000 or 2001 ? The debate goes on...
if 'century' in params:
year = (int(params['century']) - 1) * 100 + 1
# in ISO 8601 most fields are optional
for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']:
if not params.get(field, None):
params[field] = 0
hour = int(params.get('hour', 0))
minute = int(params.get('minute', 0))
second = int(float(params.get('second', 0)))
# weekday is normalized by mktime(), we can ignore it
weekday = 0
daylight_savings_flag = -1
tm = [year, month, day, hour, minute, second, weekday,
ordinal, daylight_savings_flag]
# ISO 8601 time zone adjustments
tz = params.get('tz')
if tz and tz != 'Z':
if tz[0] == '-':
tm[3] += int(params.get('tzhour', 0))
tm[4] += int(params.get('tzmin', 0))
elif tz[0] == '+':
tm[3] -= int(params.get('tzhour', 0))
tm[4] -= int(params.get('tzmin', 0))
else:
return None
# Python's time.mktime() is a wrapper around the ANSI C mktime(3c)
# which is guaranteed to normalize d/m/y/h/m/s.
# Many implementations have bugs, but we'll pretend they don't.
return time.localtime(time.mktime(tuple(tm)))
registerDateHandler(_parse_date_iso8601)
# 8-bit date handling routines written by ytrewq1.
_korean_year = u'\ub144' # b3e2 in euc-kr
_korean_month = u'\uc6d4' # bff9 in euc-kr
_korean_day = u'\uc77c' # c0cf in euc-kr
_korean_am = u'\uc624\uc804' # bfc0 c0fc in euc-kr
_korean_pm = u'\uc624\ud6c4' # bfc0 c8c4 in euc-kr
_korean_onblog_date_re = \
re.compile('(\d{4})%s\s+(\d{2})%s\s+(\d{2})%s\s+(\d{2}):(\d{2}):(\d{2})' % \
(_korean_year, _korean_month, _korean_day))
_korean_nate_date_re = \
re.compile(u'(\d{4})-(\d{2})-(\d{2})\s+(%s|%s)\s+(\d{,2}):(\d{,2}):(\d{,2})' % \
(_korean_am, _korean_pm))
def _parse_date_onblog(dateString):
"""Parse a string according to the OnBlog 8-bit date format"""
m = _korean_onblog_date_re.match(dateString)
if not m:
return
w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
{'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\
'zonediff': '+09:00'}
return _parse_date_w3dtf(w3dtfdate)
registerDateHandler(_parse_date_onblog)
def _parse_date_nate(dateString):
"""Parse a string according to the Nate 8-bit date format"""
m = _korean_nate_date_re.match(dateString)
if not m:
return
hour = int(m.group(5))
ampm = m.group(4)
if (ampm == _korean_pm):
hour += 12
hour = str(hour)
if len(hour) == 1:
hour = '0' + hour
w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
{'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
'hour': hour, 'minute': m.group(6), 'second': m.group(7),\
'zonediff': '+09:00'}
return _parse_date_w3dtf(w3dtfdate)
registerDateHandler(_parse_date_nate)
# Unicode strings for Greek date strings
_greek_months = \
{ \
u'\u0399\u03b1\u03bd': u'Jan', # c9e1ed in iso-8859-7
u'\u03a6\u03b5\u03b2': u'Feb', # d6e5e2 in iso-8859-7
u'\u039c\u03ac\u03ce': u'Mar', # ccdcfe in iso-8859-7
u'\u039c\u03b1\u03ce': u'Mar', # cce1fe in iso-8859-7
u'\u0391\u03c0\u03c1': u'Apr', # c1f0f1 in iso-8859-7
u'\u039c\u03ac\u03b9': u'May', # ccdce9 in iso-8859-7
u'\u039c\u03b1\u03ca': u'May', # cce1fa in iso-8859-7
u'\u039c\u03b1\u03b9': u'May', # cce1e9 in iso-8859-7
u'\u0399\u03bf\u03cd\u03bd': u'Jun', # c9effded in iso-8859-7
u'\u0399\u03bf\u03bd': u'Jun', # c9efed in iso-8859-7
u'\u0399\u03bf\u03cd\u03bb': u'Jul', # c9effdeb in iso-8859-7
u'\u0399\u03bf\u03bb': u'Jul', # c9f9eb in iso-8859-7
u'\u0391\u03cd\u03b3': u'Aug', # c1fde3 in iso-8859-7
u'\u0391\u03c5\u03b3': u'Aug', # c1f5e3 in iso-8859-7
u'\u03a3\u03b5\u03c0': u'Sep', # d3e5f0 in iso-8859-7
u'\u039f\u03ba\u03c4': u'Oct', # cfeaf4 in iso-8859-7
u'\u039d\u03bf\u03ad': u'Nov', # cdefdd in iso-8859-7
u'\u039d\u03bf\u03b5': u'Nov', # cdefe5 in iso-8859-7
u'\u0394\u03b5\u03ba': u'Dec', # c4e5ea in iso-8859-7
}
_greek_wdays = \
{ \
u'\u039a\u03c5\u03c1': u'Sun', # caf5f1 in iso-8859-7
u'\u0394\u03b5\u03c5': u'Mon', # c4e5f5 in iso-8859-7
u'\u03a4\u03c1\u03b9': u'Tue', # d4f1e9 in iso-8859-7
u'\u03a4\u03b5\u03c4': u'Wed', # d4e5f4 in iso-8859-7
u'\u03a0\u03b5\u03bc': u'Thu', # d0e5ec in iso-8859-7
u'\u03a0\u03b1\u03c1': u'Fri', # d0e1f1 in iso-8859-7
u'\u03a3\u03b1\u03b2': u'Sat', # d3e1e2 in iso-8859-7
}
_greek_date_format_re = \
re.compile(u'([^,]+),\s+(\d{2})\s+([^\s]+)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+([^\s]+)')
def _parse_date_greek(dateString):
"""Parse a string according to a Greek 8-bit date format."""
m = _greek_date_format_re.match(dateString)
if not m:
return
wday = _greek_wdays[m.group(1)]
month = _greek_months[m.group(3)]
rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s' % \
{'wday': wday, 'day': m.group(2), 'month': month, 'year': m.group(4),\
'hour': m.group(5), 'minute': m.group(6), 'second': m.group(7),\
'zonediff': m.group(8)}
return _parse_date_rfc822(rfc822date)
registerDateHandler(_parse_date_greek)
# Unicode strings for Hungarian date strings
_hungarian_months = \
{ \
u'janu\u00e1r': u'01', # e1 in iso-8859-2
u'febru\u00e1ri': u'02', # e1 in iso-8859-2
u'm\u00e1rcius': u'03', # e1 in iso-8859-2
u'\u00e1prilis': u'04', # e1 in iso-8859-2
u'm\u00e1ujus': u'05', # e1 in iso-8859-2
u'j\u00fanius': u'06', # fa in iso-8859-2
u'j\u00falius': u'07', # fa in iso-8859-2
u'augusztus': u'08',
u'szeptember': u'09',
u'okt\u00f3ber': u'10', # f3 in iso-8859-2
u'november': u'11',
u'december': u'12',
}
_hungarian_date_format_re = \
re.compile(u'(\d{4})-([^-]+)-(\d{,2})T(\d{,2}):(\d{2})((\+|-)(\d{,2}:\d{2}))')
def _parse_date_hungarian(dateString):
"""Parse a string according to a Hungarian 8-bit date format."""
m = _hungarian_date_format_re.match(dateString)
if not m or m.group(2) not in _hungarian_months:
return None
month = _hungarian_months[m.group(2)]
day = m.group(3)
if len(day) == 1:
day = '0' + day
hour = m.group(4)
if len(hour) == 1:
hour = '0' + hour
w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s%(zonediff)s' % \
{'year': m.group(1), 'month': month, 'day': day,\
'hour': hour, 'minute': m.group(5),\
'zonediff': m.group(6)}
return _parse_date_w3dtf(w3dtfdate)
registerDateHandler(_parse_date_hungarian)
# W3DTF-style date parsing adapted from PyXML xml.utils.iso8601, written by
# Drake and licensed under the Python license. Removed all range checking
# for month, day, hour, minute, and second, since mktime will normalize
# these later
# Modified to also support MSSQL-style datetimes as defined at:
# http://msdn.microsoft.com/en-us/library/ms186724.aspx
# (which basically means allowing a space as a date/time/timezone separator)
def _parse_date_w3dtf(dateString):
def __extract_date(m):
year = int(m.group('year'))
if year < 100:
year = 100 * int(time.gmtime()[0] / 100) + int(year)
if year < 1000:
return 0, 0, 0
julian = m.group('julian')
if julian:
julian = int(julian)
month = julian / 30 + 1
day = julian % 30 + 1
jday = None
while jday != julian:
t = time.mktime((year, month, day, 0, 0, 0, 0, 0, 0))
jday = time.gmtime(t)[-2]
diff = abs(jday - julian)
if jday > julian:
if diff < day:
day = day - diff
else:
month = month - 1
day = 31
elif jday < julian:
if day + diff < 28:
day = day + diff
else:
month = month + 1
return year, month, day
month = m.group('month')
day = 1
if month is None:
month = 1
else:
month = int(month)
day = m.group('day')
if day:
day = int(day)
else:
day = 1
return year, month, day
def __extract_time(m):
if not m:
return 0, 0, 0
hours = m.group('hours')
if not hours:
return 0, 0, 0
hours = int(hours)
minutes = int(m.group('minutes'))
seconds = m.group('seconds')
if seconds:
seconds = int(seconds)
else:
seconds = 0
return hours, minutes, seconds
def __extract_tzd(m):
"""Return the Time Zone Designator as an offset in seconds from UTC."""
if not m:
return 0
tzd = m.group('tzd')
if not tzd:
return 0
if tzd == 'Z':
return 0
hours = int(m.group('tzdhours'))
minutes = m.group('tzdminutes')
if minutes:
minutes = int(minutes)
else:
minutes = 0
offset = (hours*60 + minutes) * 60
if tzd[0] == '+':
return -offset
return offset
__date_re = ('(?P<year>\d\d\d\d)'
'(?:(?P<dsep>-|)'
'(?:(?P<month>\d\d)(?:(?P=dsep)(?P<day>\d\d))?'
'|(?P<julian>\d\d\d)))?')
__tzd_re = ' ?(?P<tzd>[-+](?P<tzdhours>\d\d)(?::?(?P<tzdminutes>\d\d))|Z)?'
__time_re = ('(?P<hours>\d\d)(?P<tsep>:|)(?P<minutes>\d\d)'
'(?:(?P=tsep)(?P<seconds>\d\d)(?:[.,]\d+)?)?'
+ __tzd_re)
__datetime_re = '%s(?:[T ]%s)?' % (__date_re, __time_re)
__datetime_rx = re.compile(__datetime_re)
m = __datetime_rx.match(dateString)
if (m is None) or (m.group() != dateString):
return
gmt = __extract_date(m) + __extract_time(m) + (0, 0, 0)
if gmt[0] == 0:
return
return time.gmtime(time.mktime(gmt) + __extract_tzd(m) - time.timezone)
registerDateHandler(_parse_date_w3dtf)
# Define the strings used by the RFC822 datetime parser
_rfc822_months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun',
'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
_rfc822_daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
# Only the first three letters of the month name matter
_rfc822_month = "(?P<month>%s)(?:[a-z]*,?)" % ('|'.join(_rfc822_months))
# The year may be 2 or 4 digits; capture the century if it exists
_rfc822_year = "(?P<year>(?:\d{2})?\d{2})"
_rfc822_day = "(?P<day> *\d{1,2})"
_rfc822_date = "%s %s %s" % (_rfc822_day, _rfc822_month, _rfc822_year)
_rfc822_hour = "(?P<hour>\d{2}):(?P<minute>\d{2})(?::(?P<second>\d{2}))?"
_rfc822_tz = "(?P<tz>ut|gmt(?:[+-]\d{2}:\d{2})?|[aecmp][sd]?t|[zamny]|[+-]\d{4})"
_rfc822_tznames = {
'ut': 0, 'gmt': 0, 'z': 0,
'adt': -3, 'ast': -4, 'at': -4,
'edt': -4, 'est': -5, 'et': -5,
'cdt': -5, 'cst': -6, 'ct': -6,
'mdt': -6, 'mst': -7, 'mt': -7,
'pdt': -7, 'pst': -8, 'pt': -8,
'a': -1, 'n': 1,
'm': -12, 'y': 12,
}
# The timezone may be prefixed by 'Etc/'
_rfc822_time = "%s (?:etc/)?%s" % (_rfc822_hour, _rfc822_tz)
_rfc822_dayname = "(?P<dayname>%s)" % ('|'.join(_rfc822_daynames))
_rfc822_match = re.compile(
"(?:%s, )?%s(?: %s)?" % (_rfc822_dayname, _rfc822_date, _rfc822_time)
).match
def _parse_date_rfc822(dt):
"""Parse RFC 822 dates and times, with one minor
difference: years may be 4DIGIT or 2DIGIT.
http://tools.ietf.org/html/rfc822#section-5"""
try:
m = _rfc822_match(dt.lower()).groupdict(0)
except AttributeError:
return None
# Calculate a date and timestamp
for k in ('year', 'day', 'hour', 'minute', 'second'):
m[k] = int(m[k])
m['month'] = _rfc822_months.index(m['month']) + 1
# If the year is 2 digits, assume everything in the 90's is the 1990's
if m['year'] < 100:
m['year'] += (1900, 2000)[m['year'] < 90]
stamp = datetime.datetime(*[m[i] for i in
('year', 'month', 'day', 'hour', 'minute', 'second')])
# Use the timezone information to calculate the difference between
# the given date and timestamp and Universal Coordinated Time
tzhour = 0
tzmin = 0
if m['tz'] and m['tz'].startswith('gmt'):
# Handle GMT and GMT+hh:mm timezone syntax (the trailing
# timezone info will be handled by the next `if` block)
m['tz'] = ''.join(m['tz'][3:].split(':')) or 'gmt'
if not m['tz']:
pass
elif m['tz'].startswith('+'):
tzhour = int(m['tz'][1:3])
tzmin = int(m['tz'][3:])
elif m['tz'].startswith('-'):
tzhour = int(m['tz'][1:3]) * -1
tzmin = int(m['tz'][3:]) * -1
else:
tzhour = _rfc822_tznames[m['tz']]
delta = datetime.timedelta(0, 0, 0, 0, tzmin, tzhour)
# Return the date and timestamp in UTC
return (stamp - delta).utctimetuple()
registerDateHandler(_parse_date_rfc822)
def _parse_date_asctime(dt):
"""Parse asctime-style dates"""
dayname, month, day, remainder = dt.split(None, 3)
# Convert month and day into zero-padded integers
month = '%02i ' % (_rfc822_months.index(month.lower()) + 1)
day = '%02i ' % (int(day),)
dt = month + day + remainder
return time.strptime(dt, '%m %d %H:%M:%S %Y')[:-1] + (0, )
registerDateHandler(_parse_date_asctime)
def _parse_date_perforce(aDateString):
"""parse a date in yyyy/mm/dd hh:mm:ss TTT format"""
# Fri, 2006/09/15 08:19:53 EDT
_my_date_pattern = re.compile( \
r'(\w{,3}), (\d{,4})/(\d{,2})/(\d{2}) (\d{,2}):(\d{2}):(\d{2}) (\w{,3})')
m = _my_date_pattern.search(aDateString)
if m is None:
return None
dow, year, month, day, hour, minute, second, tz = m.groups()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
dateString = "%s, %s %s %s %s:%s:%s %s" % (dow, day, months[int(month) - 1], year, hour, minute, second, tz)
tm = rfc822.parsedate_tz(dateString)
if tm:
return time.gmtime(rfc822.mktime_tz(tm))
registerDateHandler(_parse_date_perforce)
def _parse_date(dateString):
"""Parses a variety of date formats into a 9-tuple in GMT"""
if not dateString:
return None
for handler in _date_handlers:
try:
date9tuple = handler(dateString)
except (KeyError, OverflowError, ValueError):
continue
if not date9tuple:
continue
if len(date9tuple) != 9:
continue
return date9tuple
return None
def _getCharacterEncoding(http_headers, xml_data):
"""Get the character encoding of the XML document
http_headers is a dictionary
xml_data is a raw string (not Unicode)
This is so much trickier than it sounds, it's not even funny.
According to RFC 3023 ('XML Media Types'), if the HTTP Content-Type
is application/xml, application/*+xml,
application/xml-external-parsed-entity, or application/xml-dtd,
the encoding given in the charset parameter of the HTTP Content-Type
takes precedence over the encoding given in the XML prefix within the
document, and defaults to 'utf-8' if neither are specified. But, if
the HTTP Content-Type is text/xml, text/*+xml, or
text/xml-external-parsed-entity, the encoding given in the XML prefix
within the document is ALWAYS IGNORED and only the encoding given in
the charset parameter of the HTTP Content-Type header should be
respected, and it defaults to 'us-ascii' if not specified.
Furthermore, discussion on the atom-syntax mailing list with the
author of RFC 3023 leads me to the conclusion that any document
served with a Content-Type of text/* and no charset parameter
must be treated as us-ascii. (We now do this.) And also that it
must always be flagged as non-well-formed. (We now do this too.)
If Content-Type is unspecified (input was local file or non-HTTP source)
or unrecognized (server just got it totally wrong), then go by the
encoding given in the XML prefix of the document and default to
'iso-8859-1' as per the HTTP specification (RFC 2616).
Then, assuming we didn't find a character encoding in the HTTP headers
(and the HTTP Content-type allowed us to look in the body), we need
to sniff the first few bytes of the XML data and try to determine
whether the encoding is ASCII-compatible. Section F of the XML
specification shows the way here:
http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
If the sniffed encoding is not ASCII-compatible, we need to make it
ASCII compatible so that we can sniff further into the XML declaration
to find the encoding attribute, which will tell us the true encoding.
Of course, none of this guarantees that we will be able to parse the
feed in the declared character encoding (assuming it was declared
correctly, which many are not). iconv_codec can help a lot;
you should definitely install it if you can.
http://cjkpython.i18n.org/
"""
def _parseHTTPContentType(content_type):
"""takes HTTP Content-Type header and returns (content type, charset)
If no charset is specified, returns (content type, '')
If no content type is specified, returns ('', '')
Both return parameters are guaranteed to be lowercase strings
"""
content_type = content_type or ''
content_type, params = cgi.parse_header(content_type)
charset = params.get('charset', '').replace("'", "")
if not isinstance(charset, unicode):
charset = charset.decode('utf-8', 'ignore')
return content_type, charset
sniffed_xml_encoding = u''
xml_encoding = u''
true_encoding = u''
http_content_type, http_encoding = _parseHTTPContentType(http_headers.get('content-type'))
# Must sniff for non-ASCII-compatible character encodings before
# searching for XML declaration. This heuristic is defined in
# section F of the XML specification:
# http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
try:
if xml_data[:4] == _l2bytes([0x4c, 0x6f, 0xa7, 0x94]):
# In all forms of EBCDIC, these four bytes correspond
# to the string '<?xm'; try decoding using CP037
sniffed_xml_encoding = u'cp037'
xml_data = xml_data.decode('cp037').encode('utf-8')
elif xml_data[:4] == _l2bytes([0x00, 0x3c, 0x00, 0x3f]):
# UTF-16BE
sniffed_xml_encoding = u'utf-16be'
xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == _l2bytes([0xfe, 0xff])) and (xml_data[2:4] != _l2bytes([0x00, 0x00])):
# UTF-16BE with BOM
sniffed_xml_encoding = u'utf-16be'
xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
elif xml_data[:4] == _l2bytes([0x3c, 0x00, 0x3f, 0x00]):
# UTF-16LE
sniffed_xml_encoding = u'utf-16le'
xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == _l2bytes([0xff, 0xfe])) and (xml_data[2:4] != _l2bytes([0x00, 0x00])):
# UTF-16LE with BOM
sniffed_xml_encoding = u'utf-16le'
xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
elif xml_data[:4] == _l2bytes([0x00, 0x00, 0x00, 0x3c]):
# UTF-32BE
sniffed_xml_encoding = u'utf-32be'
if _UTF32_AVAILABLE:
xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
elif xml_data[:4] == _l2bytes([0x3c, 0x00, 0x00, 0x00]):
# UTF-32LE
sniffed_xml_encoding = u'utf-32le'
if _UTF32_AVAILABLE:
xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
elif xml_data[:4] == _l2bytes([0x00, 0x00, 0xfe, 0xff]):
# UTF-32BE with BOM
sniffed_xml_encoding = u'utf-32be'
if _UTF32_AVAILABLE:
xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
elif xml_data[:4] == _l2bytes([0xff, 0xfe, 0x00, 0x00]):
# UTF-32LE with BOM
sniffed_xml_encoding = u'utf-32le'
if _UTF32_AVAILABLE:
xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
elif xml_data[:3] == _l2bytes([0xef, 0xbb, 0xbf]):
# UTF-8 with BOM
sniffed_xml_encoding = u'utf-8'
xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
else:
# ASCII-compatible
pass
xml_encoding_match = re.compile(_s2bytes('^<\?.*encoding=[\'"](.*?)[\'"].*\?>')).match(xml_data)
except UnicodeDecodeError:
xml_encoding_match = None
if xml_encoding_match:
xml_encoding = xml_encoding_match.groups()[0].decode('utf-8').lower()
if sniffed_xml_encoding and (xml_encoding in (u'iso-10646-ucs-2', u'ucs-2', u'csunicode', u'iso-10646-ucs-4', u'ucs-4', u'csucs4', u'utf-16', u'utf-32', u'utf_16', u'utf_32', u'utf16', u'u16')):
xml_encoding = sniffed_xml_encoding
acceptable_content_type = 0
application_content_types = (u'application/xml', u'application/xml-dtd', u'application/xml-external-parsed-entity')
text_content_types = (u'text/xml', u'text/xml-external-parsed-entity')
if (http_content_type in application_content_types) or \
(http_content_type.startswith(u'application/') and http_content_type.endswith(u'+xml')):
acceptable_content_type = 1
true_encoding = http_encoding or xml_encoding or u'utf-8'
elif (http_content_type in text_content_types) or \
(http_content_type.startswith(u'text/')) and http_content_type.endswith(u'+xml'):
acceptable_content_type = 1
true_encoding = http_encoding or u'us-ascii'
elif http_content_type.startswith(u'text/'):
true_encoding = http_encoding or u'us-ascii'
elif http_headers and 'content-type' not in http_headers:
true_encoding = xml_encoding or u'iso-8859-1'
else:
true_encoding = xml_encoding or u'utf-8'
# some feeds claim to be gb2312 but are actually gb18030.
# apparently MSIE and Firefox both do the following switch:
if true_encoding.lower() == u'gb2312':
true_encoding = u'gb18030'
return true_encoding, http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type
def _toUTF8(data, encoding):
"""Changes an XML data stream on the fly to specify a new encoding
data is a raw sequence of bytes (not Unicode) that is presumed to be in %encoding already
encoding is a string recognized by encodings.aliases
"""
# strip Byte Order Mark (if present)
if (len(data) >= 4) and (data[:2] == _l2bytes([0xfe, 0xff])) and (data[2:4] != _l2bytes([0x00, 0x00])):
encoding = 'utf-16be'
data = data[2:]
elif (len(data) >= 4) and (data[:2] == _l2bytes([0xff, 0xfe])) and (data[2:4] != _l2bytes([0x00, 0x00])):
encoding = 'utf-16le'
data = data[2:]
elif data[:3] == _l2bytes([0xef, 0xbb, 0xbf]):
encoding = 'utf-8'
data = data[3:]
elif data[:4] == _l2bytes([0x00, 0x00, 0xfe, 0xff]):
encoding = 'utf-32be'
data = data[4:]
elif data[:4] == _l2bytes([0xff, 0xfe, 0x00, 0x00]):
encoding = 'utf-32le'
data = data[4:]
newdata = unicode(data, encoding)
declmatch = re.compile('^<\?xml[^>]*?>')
newdecl = '''<?xml version='1.0' encoding='utf-8'?>'''
if declmatch.search(newdata):
newdata = declmatch.sub(newdecl, newdata)
else:
newdata = newdecl + u'\n' + newdata
return newdata.encode('utf-8')
def _stripDoctype(data):
"""Strips DOCTYPE from XML document, returns (rss_version, stripped_data)
rss_version may be 'rss091n' or None
stripped_data is the same XML document, minus the DOCTYPE
"""
start = re.search(_s2bytes('<\w'), data)
start = start and start.start() or -1
head,data = data[:start+1], data[start+1:]
entity_pattern = re.compile(_s2bytes(r'^\s*<!ENTITY([^>]*?)>'), re.MULTILINE)
entity_results=entity_pattern.findall(head)
head = entity_pattern.sub(_s2bytes(''), head)
doctype_pattern = re.compile(_s2bytes(r'^\s*<!DOCTYPE([^>]*?)>'), re.MULTILINE)
doctype_results = doctype_pattern.findall(head)
doctype = doctype_results and doctype_results[0] or _s2bytes('')
if doctype.lower().count(_s2bytes('netscape')):
version = u'rss091n'
else:
version = None
# only allow in 'safe' inline entity definitions
replacement=_s2bytes('')
if len(doctype_results)==1 and entity_results:
safe_pattern=re.compile(_s2bytes('\s+(\w+)\s+"(&#\w+;|[^&"]*)"'))
safe_entities=filter(lambda e: safe_pattern.match(e),entity_results)
if safe_entities:
replacement=_s2bytes('<!DOCTYPE feed [\n <!ENTITY') + _s2bytes('>\n <!ENTITY ').join(safe_entities) + _s2bytes('>\n]>')
data = doctype_pattern.sub(replacement, head) + data
return version, data, dict(replacement and [(k.decode('utf-8'), v.decode('utf-8')) for k, v in safe_pattern.findall(replacement)])
def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=None, request_headers=None, response_headers=None):
"""Parse a feed from a URL, file, stream, or string.
request_headers, if given, is a dict from http header name to value to add
to the request; this overrides internally generated values.
"""
if handlers is None:
handlers = []
if request_headers is None:
request_headers = {}
if response_headers is None:
response_headers = {}
result = FeedParserDict()
result['feed'] = FeedParserDict()
result['entries'] = []
result['bozo'] = 0
if not isinstance(handlers, list):
handlers = [handlers]
try:
f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers, request_headers)
data = f.read()
except Exception, e:
result['bozo'] = 1
result['bozo_exception'] = e
data = None
f = None
if hasattr(f, 'headers'):
result['headers'] = dict(f.headers)
# overwrite existing headers using response_headers
if 'headers' in result:
result['headers'].update(response_headers)
elif response_headers:
result['headers'] = copy.deepcopy(response_headers)
# lowercase all of the HTTP headers for comparisons per RFC 2616
if 'headers' in result:
http_headers = dict((k.lower(), v) for k, v in result['headers'].items())
else:
http_headers = {}
# if feed is gzip-compressed, decompress it
if f and data and http_headers:
if gzip and 'gzip' in http_headers.get('content-encoding', ''):
try:
data = gzip.GzipFile(fileobj=_StringIO(data)).read()
except (IOError, struct.error), e:
# IOError can occur if the gzip header is bad.
# struct.error can occur if the data is damaged.
result['bozo'] = 1
result['bozo_exception'] = e
if isinstance(e, struct.error):
# A gzip header was found but the data is corrupt.
# Ideally, we should re-request the feed without the
# 'Accept-encoding: gzip' header, but we don't.
data = None
elif zlib and 'deflate' in http_headers.get('content-encoding', ''):
try:
data = zlib.decompress(data)
except zlib.error, e:
try:
# The data may have no headers and no checksum.
data = zlib.decompress(data, -15)
except zlib.error, e:
result['bozo'] = 1
result['bozo_exception'] = e
# save HTTP headers
if http_headers:
if 'etag' in http_headers:
etag = http_headers.get('etag', u'')
if not isinstance(etag, unicode):
etag = etag.decode('utf-8', 'ignore')
if etag:
result['etag'] = etag
if 'last-modified' in http_headers:
modified = http_headers.get('last-modified', u'')
if modified:
result['modified'] = modified
result['modified_parsed'] = _parse_date(modified)
if hasattr(f, 'url'):
if not isinstance(f.url, unicode):
result['href'] = f.url.decode('utf-8', 'ignore')
else:
result['href'] = f.url
result['status'] = 200
if hasattr(f, 'status'):
result['status'] = f.status
if hasattr(f, 'close'):
f.close()
if data is None:
return result
# there are four encodings to keep track of:
# - http_encoding is the encoding declared in the Content-Type HTTP header
# - xml_encoding is the encoding declared in the <?xml declaration
# - sniffed_encoding is the encoding sniffed from the first 4 bytes of the XML data
# - result['encoding'] is the actual encoding, as per RFC 3023 and a variety of other conflicting specifications
result['encoding'], http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type = \
_getCharacterEncoding(http_headers, data)
if http_headers and (not acceptable_content_type):
if 'content-type' in http_headers:
bozo_message = '%s is not an XML media type' % http_headers['content-type']
else:
bozo_message = 'no Content-type specified'
result['bozo'] = 1
result['bozo_exception'] = NonXMLContentType(bozo_message)
# ensure that baseuri is an absolute uri using an acceptable URI scheme
contentloc = http_headers.get('content-location', u'')
href = result.get('href', u'')
baseuri = _makeSafeAbsoluteURI(href, contentloc) or _makeSafeAbsoluteURI(contentloc) or href
baselang = http_headers.get('content-language', None)
if not isinstance(baselang, unicode) and baselang is not None:
baselang = baselang.decode('utf-8', 'ignore')
# if server sent 304, we're done
if getattr(f, 'code', 0) == 304:
result['version'] = u''
result['debug_message'] = 'The feed has not changed since you last checked, ' + \
'so the server sent no data. This is a feature, not a bug!'
return result
# if there was a problem downloading, we're done
if data is None:
return result
# determine character encoding
use_strict_parser = 0
known_encoding = 0
tried_encodings = []
# try: HTTP encoding, declared XML encoding, encoding sniffed from BOM
for proposed_encoding in (result['encoding'], xml_encoding, sniffed_xml_encoding):
if not proposed_encoding:
continue
if proposed_encoding in tried_encodings:
continue
tried_encodings.append(proposed_encoding)
try:
data = _toUTF8(data, proposed_encoding)
except (UnicodeDecodeError, LookupError):
pass
else:
known_encoding = use_strict_parser = 1
break
# if no luck and we have auto-detection library, try that
if (not known_encoding) and chardet:
proposed_encoding = unicode(chardet.detect(data)['encoding'], 'ascii', 'ignore')
if proposed_encoding and (proposed_encoding not in tried_encodings):
tried_encodings.append(proposed_encoding)
try:
data = _toUTF8(data, proposed_encoding)
except (UnicodeDecodeError, LookupError):
pass
else:
known_encoding = use_strict_parser = 1
# if still no luck and we haven't tried utf-8 yet, try that
if (not known_encoding) and (u'utf-8' not in tried_encodings):
proposed_encoding = u'utf-8'
tried_encodings.append(proposed_encoding)
try:
data = _toUTF8(data, proposed_encoding)
except UnicodeDecodeError:
pass
else:
known_encoding = use_strict_parser = 1
# if still no luck and we haven't tried windows-1252 yet, try that
if (not known_encoding) and (u'windows-1252' not in tried_encodings):
proposed_encoding = u'windows-1252'
tried_encodings.append(proposed_encoding)
try:
data = _toUTF8(data, proposed_encoding)
except UnicodeDecodeError:
pass
else:
known_encoding = use_strict_parser = 1
# if still no luck and we haven't tried iso-8859-2 yet, try that.
if (not known_encoding) and (u'iso-8859-2' not in tried_encodings):
proposed_encoding = u'iso-8859-2'
tried_encodings.append(proposed_encoding)
try:
data = _toUTF8(data, proposed_encoding)
except UnicodeDecodeError:
pass
else:
known_encoding = use_strict_parser = 1
# if still no luck, give up
if not known_encoding:
result['bozo'] = 1
result['bozo_exception'] = CharacterEncodingUnknown( \
'document encoding unknown, I tried ' + \
'%s, %s, utf-8, windows-1252, and iso-8859-2 but nothing worked' % \
(result['encoding'], xml_encoding))
result['encoding'] = u''
elif proposed_encoding != result['encoding']:
result['bozo'] = 1
result['bozo_exception'] = CharacterEncodingOverride( \
'document declared as %s, but parsed as %s' % \
(result['encoding'], proposed_encoding))
result['encoding'] = proposed_encoding
result['version'], data, entities = _stripDoctype(data)
if not _XML_AVAILABLE:
use_strict_parser = 0
if use_strict_parser:
# initialize the SAX parser
feedparser = _StrictFeedParser(baseuri, baselang, 'utf-8')
saxparser = xml.sax.make_parser(PREFERRED_XML_PARSERS)
saxparser.setFeature(xml.sax.handler.feature_namespaces, 1)
try:
# disable downloading external doctype references, if possible
saxparser.setFeature(xml.sax.handler.feature_external_ges, 0)
except xml.sax.SAXNotSupportedException:
pass
saxparser.setContentHandler(feedparser)
saxparser.setErrorHandler(feedparser)
source = xml.sax.xmlreader.InputSource()
source.setByteStream(_StringIO(data))
try:
saxparser.parse(source)
except xml.sax.SAXParseException, e:
result['bozo'] = 1
result['bozo_exception'] = feedparser.exc or e
use_strict_parser = 0
if not use_strict_parser and _SGML_AVAILABLE:
feedparser = _LooseFeedParser(baseuri, baselang, 'utf-8', entities)
feedparser.feed(data.decode('utf-8', 'replace'))
result['feed'] = feedparser.feeddata
result['entries'] = feedparser.entries
result['version'] = result['version'] or feedparser.version
result['namespaces'] = feedparser.namespacesInUse
return result
|
rinze/rank-es
|
feedparser.py
|
Python
|
gpl-3.0
| 167,978
|
[
"NetCDF",
"VisIt"
] |
a986164c8038f1a68d8bac59b94551e67cd4b485ea30a980de7999ae1490f05b
|
#!/usr/bin/env python
# Copyright (c) 2012 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.
# Copyright (C) 2008 Evan Martin <martine@danga.com>
"""A git-command for integrating reviews on Rietveld."""
from distutils.version import LooseVersion
from multiprocessing.pool import ThreadPool
import base64
import collections
import glob
import httplib
import json
import logging
import optparse
import os
import Queue
import re
import stat
import sys
import tempfile
import textwrap
import time
import traceback
import urllib2
import urlparse
import webbrowser
import zlib
try:
import readline # pylint: disable=F0401,W0611
except ImportError:
pass
from third_party import colorama
from third_party import httplib2
from third_party import upload
import auth
import breakpad # pylint: disable=W0611
import clang_format
import dart_format
import fix_encoding
import gclient_utils
import git_common
from git_footers import get_footer_svn_id
import owners
import owners_finder
import presubmit_support
import rietveld
import scm
import subcommand
import subprocess2
import watchlists
__version__ = '1.0'
DEFAULT_SERVER = 'https://codereview.appspot.com'
POSTUPSTREAM_HOOK_PATTERN = '.git/hooks/post-cl-%s'
DESCRIPTION_BACKUP_FILE = '~/.git_cl_description_backup'
GIT_INSTRUCTIONS_URL = 'http://code.google.com/p/chromium/wiki/UsingGit'
CHANGE_ID = 'Change-Id:'
REFS_THAT_ALIAS_TO_OTHER_REFS = {
'refs/remotes/origin/lkgr': 'refs/remotes/origin/master',
'refs/remotes/origin/lkcr': 'refs/remotes/origin/master',
}
# Valid extensions for files we want to lint.
DEFAULT_LINT_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)"
DEFAULT_LINT_IGNORE_REGEX = r"$^"
# Shortcut since it quickly becomes redundant.
Fore = colorama.Fore
# Initialized in main()
settings = None
def DieWithError(message):
print >> sys.stderr, message
sys.exit(1)
def GetNoGitPagerEnv():
env = os.environ.copy()
# 'cat' is a magical git string that disables pagers on all platforms.
env['GIT_PAGER'] = 'cat'
return env
def RunCommand(args, error_ok=False, error_message=None, **kwargs):
try:
return subprocess2.check_output(args, shell=False, **kwargs)
except subprocess2.CalledProcessError as e:
logging.debug('Failed running %s', args)
if not error_ok:
DieWithError(
'Command "%s" failed.\n%s' % (
' '.join(args), error_message or e.stdout or ''))
return e.stdout
def RunGit(args, **kwargs):
"""Returns stdout."""
return RunCommand(['git'] + args, **kwargs)
def RunGitWithCode(args, suppress_stderr=False):
"""Returns return code and stdout."""
try:
if suppress_stderr:
stderr = subprocess2.VOID
else:
stderr = sys.stderr
out, code = subprocess2.communicate(['git'] + args,
env=GetNoGitPagerEnv(),
stdout=subprocess2.PIPE,
stderr=stderr)
return code, out[0]
except ValueError:
# When the subprocess fails, it returns None. That triggers a ValueError
# when trying to unpack the return value into (out, code).
return 1, ''
def RunGitSilent(args):
"""Returns stdout, suppresses stderr and ingores the return code."""
return RunGitWithCode(args, suppress_stderr=True)[1]
def IsGitVersionAtLeast(min_version):
prefix = 'git version '
version = RunGit(['--version']).strip()
return (version.startswith(prefix) and
LooseVersion(version[len(prefix):]) >= LooseVersion(min_version))
def BranchExists(branch):
"""Return True if specified branch exists."""
code, _ = RunGitWithCode(['rev-parse', '--verify', branch],
suppress_stderr=True)
return not code
def ask_for_data(prompt):
try:
return raw_input(prompt)
except KeyboardInterrupt:
# Hide the exception.
sys.exit(1)
def git_set_branch_value(key, value):
branch = Changelist().GetBranch()
if not branch:
return
cmd = ['config']
if isinstance(value, int):
cmd.append('--int')
git_key = 'branch.%s.%s' % (branch, key)
RunGit(cmd + [git_key, str(value)])
def git_get_branch_default(key, default):
branch = Changelist().GetBranch()
if branch:
git_key = 'branch.%s.%s' % (branch, key)
(_, stdout) = RunGitWithCode(['config', '--int', '--get', git_key])
try:
return int(stdout.strip())
except ValueError:
pass
return default
def add_git_similarity(parser):
parser.add_option(
'--similarity', metavar='SIM', type='int', action='store',
help='Sets the percentage that a pair of files need to match in order to'
' be considered copies (default 50)')
parser.add_option(
'--find-copies', action='store_true',
help='Allows git to look for copies.')
parser.add_option(
'--no-find-copies', action='store_false', dest='find_copies',
help='Disallows git from looking for copies.')
old_parser_args = parser.parse_args
def Parse(args):
options, args = old_parser_args(args)
if options.similarity is None:
options.similarity = git_get_branch_default('git-cl-similarity', 50)
else:
print('Note: Saving similarity of %d%% in git config.'
% options.similarity)
git_set_branch_value('git-cl-similarity', options.similarity)
options.similarity = max(0, min(options.similarity, 100))
if options.find_copies is None:
options.find_copies = bool(
git_get_branch_default('git-find-copies', True))
else:
git_set_branch_value('git-find-copies', int(options.find_copies))
print('Using %d%% similarity for rename/copy detection. '
'Override with --similarity.' % options.similarity)
return options, args
parser.parse_args = Parse
def _prefix_master(master):
"""Convert user-specified master name to full master name.
Buildbucket uses full master name(master.tryserver.chromium.linux) as bucket
name, while the developers always use shortened master name
(tryserver.chromium.linux) by stripping off the prefix 'master.'. This
function does the conversion for buildbucket migration.
"""
prefix = 'master.'
if master.startswith(prefix):
return master
return '%s%s' % (prefix, master)
def trigger_try_jobs(auth_config, changelist, options, masters, category,
override_properties=None):
rietveld_url = settings.GetDefaultServerUrl()
rietveld_host = urlparse.urlparse(rietveld_url).hostname
authenticator = auth.get_authenticator_for_host(rietveld_host, auth_config)
http = authenticator.authorize(httplib2.Http())
http.force_exception_to_status_code = True
issue_props = changelist.GetIssueProperties()
issue = changelist.GetIssue()
patchset = changelist.GetMostRecentPatchset()
buildbucket_put_url = (
'https://{hostname}/_ah/api/buildbucket/v1/builds/batch'.format(
hostname=options.buildbucket_host))
buildset = 'patch/rietveld/{hostname}/{issue}/{patch}'.format(
hostname=rietveld_host,
issue=issue,
patch=patchset)
batch_req_body = {'builds': []}
print_text = []
print_text.append('Tried jobs on:')
for master, builders_and_tests in sorted(masters.iteritems()):
print_text.append('Master: %s' % master)
bucket = _prefix_master(master)
for builder, tests in sorted(builders_and_tests.iteritems()):
print_text.append(' %s: %s' % (builder, tests))
parameters = {
'builder_name': builder,
'changes': [
{'author': {'email': issue_props['owner_email']}},
],
'properties': {
'category': category,
'issue': issue,
'master': master,
'patch_project': issue_props['project'],
'patch_storage': 'rietveld',
'patchset': patchset,
'reason': options.name,
'revision': options.revision,
'rietveld': rietveld_url,
'testfilter': tests,
},
}
if override_properties:
parameters['properties'].update(override_properties)
if options.clobber:
parameters['properties']['clobber'] = True
batch_req_body['builds'].append(
{
'bucket': bucket,
'parameters_json': json.dumps(parameters),
'tags': ['builder:%s' % builder,
'buildset:%s' % buildset,
'master:%s' % master,
'user_agent:git_cl_try']
}
)
for try_count in xrange(3):
response, content = http.request(
buildbucket_put_url,
'PUT',
body=json.dumps(batch_req_body),
headers={'Content-Type': 'application/json'},
)
content_json = None
try:
content_json = json.loads(content)
except ValueError:
pass
# Buildbucket could return an error even if status==200.
if content_json and content_json.get('error'):
msg = 'Error in response. Code: %d. Reason: %s. Message: %s.' % (
content_json['error'].get('code', ''),
content_json['error'].get('reason', ''),
content_json['error'].get('message', ''))
raise BuildbucketResponseException(msg)
if response.status == 200:
if not content_json:
raise BuildbucketResponseException(
'Buildbucket returns invalid json content: %s.\n'
'Please file bugs at crbug.com, label "Infra-BuildBucket".' %
content)
break
if response.status < 500 or try_count >= 2:
raise httplib2.HttpLib2Error(content)
# status >= 500 means transient failures.
logging.debug('Transient errors when triggering tryjobs. Will retry.')
time.sleep(0.5 + 1.5*try_count)
print '\n'.join(print_text)
def MatchSvnGlob(url, base_url, glob_spec, allow_wildcards):
"""Return the corresponding git ref if |base_url| together with |glob_spec|
matches the full |url|.
If |allow_wildcards| is true, |glob_spec| can contain wildcards (see below).
"""
fetch_suburl, as_ref = glob_spec.split(':')
if allow_wildcards:
glob_match = re.match('(.+/)?(\*|{[^/]*})(/.+)?', fetch_suburl)
if glob_match:
# Parse specs like "branches/*/src:refs/remotes/svn/*" or
# "branches/{472,597,648}/src:refs/remotes/svn/*".
branch_re = re.escape(base_url)
if glob_match.group(1):
branch_re += '/' + re.escape(glob_match.group(1))
wildcard = glob_match.group(2)
if wildcard == '*':
branch_re += '([^/]*)'
else:
# Escape and replace surrounding braces with parentheses and commas
# with pipe symbols.
wildcard = re.escape(wildcard)
wildcard = re.sub('^\\\\{', '(', wildcard)
wildcard = re.sub('\\\\,', '|', wildcard)
wildcard = re.sub('\\\\}$', ')', wildcard)
branch_re += wildcard
if glob_match.group(3):
branch_re += re.escape(glob_match.group(3))
match = re.match(branch_re, url)
if match:
return re.sub('\*$', match.group(1), as_ref)
# Parse specs like "trunk/src:refs/remotes/origin/trunk".
if fetch_suburl:
full_url = base_url + '/' + fetch_suburl
else:
full_url = base_url
if full_url == url:
return as_ref
return None
def print_stats(similarity, find_copies, args):
"""Prints statistics about the change to the user."""
# --no-ext-diff is broken in some versions of Git, so try to work around
# this by overriding the environment (but there is still a problem if the
# git config key "diff.external" is used).
env = GetNoGitPagerEnv()
if 'GIT_EXTERNAL_DIFF' in env:
del env['GIT_EXTERNAL_DIFF']
if find_copies:
similarity_options = ['--find-copies-harder', '-l100000',
'-C%s' % similarity]
else:
similarity_options = ['-M%s' % similarity]
try:
stdout = sys.stdout.fileno()
except AttributeError:
stdout = None
return subprocess2.call(
['git',
'diff', '--no-ext-diff', '--stat'] + similarity_options + args,
stdout=stdout, env=env)
class BuildbucketResponseException(Exception):
pass
class Settings(object):
def __init__(self):
self.default_server = None
self.cc = None
self.root = None
self.is_git_svn = None
self.svn_branch = None
self.tree_status_url = None
self.viewvc_url = None
self.updated = False
self.is_gerrit = None
self.git_editor = None
self.project = None
self.force_https_commit_url = None
self.pending_ref_prefix = None
def LazyUpdateIfNeeded(self):
"""Updates the settings from a codereview.settings file, if available."""
if not self.updated:
# The only value that actually changes the behavior is
# autoupdate = "false". Everything else means "true".
autoupdate = RunGit(['config', 'rietveld.autoupdate'],
error_ok=True
).strip().lower()
cr_settings_file = FindCodereviewSettingsFile()
if autoupdate != 'false' and cr_settings_file:
LoadCodereviewSettingsFromFile(cr_settings_file)
# set updated to True to avoid infinite calling loop
# through DownloadHooks
self.updated = True
DownloadHooks(False)
self.updated = True
def GetDefaultServerUrl(self, error_ok=False):
if not self.default_server:
self.LazyUpdateIfNeeded()
self.default_server = gclient_utils.UpgradeToHttps(
self._GetRietveldConfig('server', error_ok=True))
if error_ok:
return self.default_server
if not self.default_server:
error_message = ('Could not find settings file. You must configure '
'your review setup by running "git cl config".')
self.default_server = gclient_utils.UpgradeToHttps(
self._GetRietveldConfig('server', error_message=error_message))
return self.default_server
@staticmethod
def GetRelativeRoot():
return RunGit(['rev-parse', '--show-cdup']).strip()
def GetRoot(self):
if self.root is None:
self.root = os.path.abspath(self.GetRelativeRoot())
return self.root
def GetIsGitSvn(self):
"""Return true if this repo looks like it's using git-svn."""
if self.is_git_svn is None:
if self.GetPendingRefPrefix():
# If PENDING_REF_PREFIX is set then it's a pure git repo no matter what.
self.is_git_svn = False
else:
# If you have any "svn-remote.*" config keys, we think you're using svn.
self.is_git_svn = RunGitWithCode(
['config', '--local', '--get-regexp', r'^svn-remote\.'])[0] == 0
return self.is_git_svn
def GetSVNBranch(self):
if self.svn_branch is None:
if not self.GetIsGitSvn():
DieWithError('Repo doesn\'t appear to be a git-svn repo.')
# Try to figure out which remote branch we're based on.
# Strategy:
# 1) iterate through our branch history and find the svn URL.
# 2) find the svn-remote that fetches from the URL.
# regexp matching the git-svn line that contains the URL.
git_svn_re = re.compile(r'^\s*git-svn-id: (\S+)@', re.MULTILINE)
# We don't want to go through all of history, so read a line from the
# pipe at a time.
# The -100 is an arbitrary limit so we don't search forever.
cmd = ['git', 'log', '-100', '--pretty=medium']
proc = subprocess2.Popen(cmd, stdout=subprocess2.PIPE,
env=GetNoGitPagerEnv())
url = None
for line in proc.stdout:
match = git_svn_re.match(line)
if match:
url = match.group(1)
proc.stdout.close() # Cut pipe.
break
if url:
svn_remote_re = re.compile(r'^svn-remote\.([^.]+)\.url (.*)$')
remotes = RunGit(['config', '--get-regexp',
r'^svn-remote\..*\.url']).splitlines()
for remote in remotes:
match = svn_remote_re.match(remote)
if match:
remote = match.group(1)
base_url = match.group(2)
rewrite_root = RunGit(
['config', 'svn-remote.%s.rewriteRoot' % remote],
error_ok=True).strip()
if rewrite_root:
base_url = rewrite_root
fetch_spec = RunGit(
['config', 'svn-remote.%s.fetch' % remote],
error_ok=True).strip()
if fetch_spec:
self.svn_branch = MatchSvnGlob(url, base_url, fetch_spec, False)
if self.svn_branch:
break
branch_spec = RunGit(
['config', 'svn-remote.%s.branches' % remote],
error_ok=True).strip()
if branch_spec:
self.svn_branch = MatchSvnGlob(url, base_url, branch_spec, True)
if self.svn_branch:
break
tag_spec = RunGit(
['config', 'svn-remote.%s.tags' % remote],
error_ok=True).strip()
if tag_spec:
self.svn_branch = MatchSvnGlob(url, base_url, tag_spec, True)
if self.svn_branch:
break
if not self.svn_branch:
DieWithError('Can\'t guess svn branch -- try specifying it on the '
'command line')
return self.svn_branch
def GetTreeStatusUrl(self, error_ok=False):
if not self.tree_status_url:
error_message = ('You must configure your tree status URL by running '
'"git cl config".')
self.tree_status_url = self._GetRietveldConfig(
'tree-status-url', error_ok=error_ok, error_message=error_message)
return self.tree_status_url
def GetViewVCUrl(self):
if not self.viewvc_url:
self.viewvc_url = self._GetRietveldConfig('viewvc-url', error_ok=True)
return self.viewvc_url
def GetBugPrefix(self):
return self._GetRietveldConfig('bug-prefix', error_ok=True)
def GetIsSkipDependencyUpload(self, branch_name):
"""Returns true if specified branch should skip dep uploads."""
return self._GetBranchConfig(branch_name, 'skip-deps-uploads',
error_ok=True)
def GetRunPostUploadHook(self):
run_post_upload_hook = self._GetRietveldConfig(
'run-post-upload-hook', error_ok=True)
return run_post_upload_hook == "True"
def GetDefaultCCList(self):
return self._GetRietveldConfig('cc', error_ok=True)
def GetDefaultPrivateFlag(self):
return self._GetRietveldConfig('private', error_ok=True)
def GetIsGerrit(self):
"""Return true if this repo is assosiated with gerrit code review system."""
if self.is_gerrit is None:
self.is_gerrit = self._GetConfig('gerrit.host', error_ok=True)
return self.is_gerrit
def GetGitEditor(self):
"""Return the editor specified in the git config, or None if none is."""
if self.git_editor is None:
self.git_editor = self._GetConfig('core.editor', error_ok=True)
return self.git_editor or None
def GetLintRegex(self):
return (self._GetRietveldConfig('cpplint-regex', error_ok=True) or
DEFAULT_LINT_REGEX)
def GetLintIgnoreRegex(self):
return (self._GetRietveldConfig('cpplint-ignore-regex', error_ok=True) or
DEFAULT_LINT_IGNORE_REGEX)
def GetProject(self):
if not self.project:
self.project = self._GetRietveldConfig('project', error_ok=True)
return self.project
def GetForceHttpsCommitUrl(self):
if not self.force_https_commit_url:
self.force_https_commit_url = self._GetRietveldConfig(
'force-https-commit-url', error_ok=True)
return self.force_https_commit_url
def GetPendingRefPrefix(self):
if not self.pending_ref_prefix:
self.pending_ref_prefix = self._GetRietveldConfig(
'pending-ref-prefix', error_ok=True)
return self.pending_ref_prefix
def _GetRietveldConfig(self, param, **kwargs):
return self._GetConfig('rietveld.' + param, **kwargs)
def _GetBranchConfig(self, branch_name, param, **kwargs):
return self._GetConfig('branch.' + branch_name + '.' + param, **kwargs)
def _GetConfig(self, param, **kwargs):
self.LazyUpdateIfNeeded()
return RunGit(['config', param], **kwargs).strip()
def ShortBranchName(branch):
"""Convert a name like 'refs/heads/foo' to just 'foo'."""
return branch.replace('refs/heads/', '')
class Changelist(object):
def __init__(self, branchref=None, issue=None, auth_config=None):
# Poke settings so we get the "configure your server" message if necessary.
global settings
if not settings:
# Happens when git_cl.py is used as a utility library.
settings = Settings()
settings.GetDefaultServerUrl()
self.branchref = branchref
if self.branchref:
self.branch = ShortBranchName(self.branchref)
else:
self.branch = None
self.rietveld_server = None
self.upstream_branch = None
self.lookedup_issue = False
self.issue = issue or None
self.has_description = False
self.description = None
self.lookedup_patchset = False
self.patchset = None
self.cc = None
self.watchers = ()
self._auth_config = auth_config
self._props = None
self._remote = None
self._rpc_server = None
@property
def auth_config(self):
return self._auth_config
def GetCCList(self):
"""Return the users cc'd on this CL.
Return is a string suitable for passing to gcl with the --cc flag.
"""
if self.cc is None:
base_cc = settings.GetDefaultCCList()
more_cc = ','.join(self.watchers)
self.cc = ','.join(filter(None, (base_cc, more_cc))) or ''
return self.cc
def GetCCListWithoutDefault(self):
"""Return the users cc'd on this CL excluding default ones."""
if self.cc is None:
self.cc = ','.join(self.watchers)
return self.cc
def SetWatchers(self, watchers):
"""Set the list of email addresses that should be cc'd based on the changed
files in this CL.
"""
self.watchers = watchers
def GetBranch(self):
"""Returns the short branch name, e.g. 'master'."""
if not self.branch:
branchref = RunGit(['symbolic-ref', 'HEAD'],
stderr=subprocess2.VOID, error_ok=True).strip()
if not branchref:
return None
self.branchref = branchref
self.branch = ShortBranchName(self.branchref)
return self.branch
def GetBranchRef(self):
"""Returns the full branch name, e.g. 'refs/heads/master'."""
self.GetBranch() # Poke the lazy loader.
return self.branchref
@staticmethod
def FetchUpstreamTuple(branch):
"""Returns a tuple containing remote and remote ref,
e.g. 'origin', 'refs/heads/master'
"""
remote = '.'
upstream_branch = RunGit(['config', 'branch.%s.merge' % branch],
error_ok=True).strip()
if upstream_branch:
remote = RunGit(['config', 'branch.%s.remote' % branch]).strip()
else:
upstream_branch = RunGit(['config', 'rietveld.upstream-branch'],
error_ok=True).strip()
if upstream_branch:
remote = RunGit(['config', 'rietveld.upstream-remote']).strip()
else:
# Fall back on trying a git-svn upstream branch.
if settings.GetIsGitSvn():
upstream_branch = settings.GetSVNBranch()
else:
# Else, try to guess the origin remote.
remote_branches = RunGit(['branch', '-r']).split()
if 'origin/master' in remote_branches:
# Fall back on origin/master if it exits.
remote = 'origin'
upstream_branch = 'refs/heads/master'
elif 'origin/trunk' in remote_branches:
# Fall back on origin/trunk if it exists. Generally a shared
# git-svn clone
remote = 'origin'
upstream_branch = 'refs/heads/trunk'
else:
DieWithError("""Unable to determine default branch to diff against.
Either pass complete "git diff"-style arguments, like
git cl upload origin/master
or verify this branch is set up to track another (via the --track argument to
"git checkout -b ...").""")
return remote, upstream_branch
def GetCommonAncestorWithUpstream(self):
upstream_branch = self.GetUpstreamBranch()
if not BranchExists(upstream_branch):
DieWithError('The upstream for the current branch (%s) does not exist '
'anymore.\nPlease fix it and try again.' % self.GetBranch())
return git_common.get_or_create_merge_base(self.GetBranch(),
upstream_branch)
def GetUpstreamBranch(self):
if self.upstream_branch is None:
remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
if remote is not '.':
upstream_branch = upstream_branch.replace('refs/heads/',
'refs/remotes/%s/' % remote)
upstream_branch = upstream_branch.replace('refs/branch-heads/',
'refs/remotes/branch-heads/')
self.upstream_branch = upstream_branch
return self.upstream_branch
def GetRemoteBranch(self):
if not self._remote:
remote, branch = None, self.GetBranch()
seen_branches = set()
while branch not in seen_branches:
seen_branches.add(branch)
remote, branch = self.FetchUpstreamTuple(branch)
branch = ShortBranchName(branch)
if remote != '.' or branch.startswith('refs/remotes'):
break
else:
remotes = RunGit(['remote'], error_ok=True).split()
if len(remotes) == 1:
remote, = remotes
elif 'origin' in remotes:
remote = 'origin'
logging.warning('Could not determine which remote this change is '
'associated with, so defaulting to "%s". This may '
'not be what you want. You may prevent this message '
'by running "git svn info" as documented here: %s',
self._remote,
GIT_INSTRUCTIONS_URL)
else:
logging.warn('Could not determine which remote this change is '
'associated with. You may prevent this message by '
'running "git svn info" as documented here: %s',
GIT_INSTRUCTIONS_URL)
branch = 'HEAD'
if branch.startswith('refs/remotes'):
self._remote = (remote, branch)
elif branch.startswith('refs/branch-heads/'):
self._remote = (remote, branch.replace('refs/', 'refs/remotes/'))
else:
self._remote = (remote, 'refs/remotes/%s/%s' % (remote, branch))
return self._remote
def GitSanityChecks(self, upstream_git_obj):
"""Checks git repo status and ensures diff is from local commits."""
if upstream_git_obj is None:
if self.GetBranch() is None:
print >> sys.stderr, (
'ERROR: unable to determine current branch (detached HEAD?)')
else:
print >> sys.stderr, (
'ERROR: no upstream branch')
return False
# Verify the commit we're diffing against is in our current branch.
upstream_sha = RunGit(['rev-parse', '--verify', upstream_git_obj]).strip()
common_ancestor = RunGit(['merge-base', upstream_sha, 'HEAD']).strip()
if upstream_sha != common_ancestor:
print >> sys.stderr, (
'ERROR: %s is not in the current branch. You may need to rebase '
'your tracking branch' % upstream_sha)
return False
# List the commits inside the diff, and verify they are all local.
commits_in_diff = RunGit(
['rev-list', '^%s' % upstream_sha, 'HEAD']).splitlines()
code, remote_branch = RunGitWithCode(['config', 'gitcl.remotebranch'])
remote_branch = remote_branch.strip()
if code != 0:
_, remote_branch = self.GetRemoteBranch()
commits_in_remote = RunGit(
['rev-list', '^%s' % upstream_sha, remote_branch]).splitlines()
common_commits = set(commits_in_diff) & set(commits_in_remote)
if common_commits:
print >> sys.stderr, (
'ERROR: Your diff contains %d commits already in %s.\n'
'Run "git log --oneline %s..HEAD" to get a list of commits in '
'the diff. If you are using a custom git flow, you can override'
' the reference used for this check with "git config '
'gitcl.remotebranch <git-ref>".' % (
len(common_commits), remote_branch, upstream_git_obj))
return False
return True
def GetGitBaseUrlFromConfig(self):
"""Return the configured base URL from branch.<branchname>.baseurl.
Returns None if it is not set.
"""
return RunGit(['config', 'branch.%s.base-url' % self.GetBranch()],
error_ok=True).strip()
def GetGitSvnRemoteUrl(self):
"""Return the configured git-svn remote URL parsed from git svn info.
Returns None if it is not set.
"""
# URL is dependent on the current directory.
data = RunGit(['svn', 'info'], cwd=settings.GetRoot())
if data:
keys = dict(line.split(': ', 1) for line in data.splitlines()
if ': ' in line)
return keys.get('URL', None)
return None
def GetRemoteUrl(self):
"""Return the configured remote URL, e.g. 'git://example.org/foo.git/'.
Returns None if there is no remote.
"""
remote, _ = self.GetRemoteBranch()
url = RunGit(['config', 'remote.%s.url' % remote], error_ok=True).strip()
# If URL is pointing to a local directory, it is probably a git cache.
if os.path.isdir(url):
url = RunGit(['config', 'remote.%s.url' % remote],
error_ok=True,
cwd=url).strip()
return url
def GetIssue(self):
"""Returns the issue number as a int or None if not set."""
if self.issue is None and not self.lookedup_issue:
issue = RunGit(['config', self._IssueSetting()], error_ok=True).strip()
self.issue = int(issue) or None if issue else None
self.lookedup_issue = True
return self.issue
def GetRietveldServer(self):
if not self.rietveld_server:
# If we're on a branch then get the server potentially associated
# with that branch.
if self.GetIssue():
rietveld_server_config = self._RietveldServer()
if rietveld_server_config:
self.rietveld_server = gclient_utils.UpgradeToHttps(RunGit(
['config', rietveld_server_config], error_ok=True).strip())
if not self.rietveld_server:
self.rietveld_server = settings.GetDefaultServerUrl()
return self.rietveld_server
def GetIssueURL(self):
"""Get the URL for a particular issue."""
if not self.GetIssue():
return None
return '%s/%s' % (self.GetRietveldServer(), self.GetIssue())
def GetDescription(self, pretty=False):
if not self.has_description:
if self.GetIssue():
issue = self.GetIssue()
try:
self.description = self.RpcServer().get_description(issue).strip()
except urllib2.HTTPError as e:
if e.code == 404:
DieWithError(
('\nWhile fetching the description for issue %d, received a '
'404 (not found)\n'
'error. It is likely that you deleted this '
'issue on the server. If this is the\n'
'case, please run\n\n'
' git cl issue 0\n\n'
'to clear the association with the deleted issue. Then run '
'this command again.') % issue)
else:
DieWithError(
'\nFailed to fetch issue description. HTTP error %d' % e.code)
except urllib2.URLError as e:
print >> sys.stderr, (
'Warning: Failed to retrieve CL description due to network '
'failure.')
self.description = ''
self.has_description = True
if pretty:
wrapper = textwrap.TextWrapper()
wrapper.initial_indent = wrapper.subsequent_indent = ' '
return wrapper.fill(self.description)
return self.description
def GetPatchset(self):
"""Returns the patchset number as a int or None if not set."""
if self.patchset is None and not self.lookedup_patchset:
patchset = RunGit(['config', self._PatchsetSetting()],
error_ok=True).strip()
self.patchset = int(patchset) or None if patchset else None
self.lookedup_patchset = True
return self.patchset
def SetPatchset(self, patchset):
"""Set this branch's patchset. If patchset=0, clears the patchset."""
if patchset:
RunGit(['config', self._PatchsetSetting(), str(patchset)])
self.patchset = patchset
else:
RunGit(['config', '--unset', self._PatchsetSetting()],
stderr=subprocess2.PIPE, error_ok=True)
self.patchset = None
def GetMostRecentPatchset(self):
return self.GetIssueProperties()['patchsets'][-1]
def GetPatchSetDiff(self, issue, patchset):
return self.RpcServer().get(
'/download/issue%s_%s.diff' % (issue, patchset))
def GetIssueProperties(self):
if self._props is None:
issue = self.GetIssue()
if not issue:
self._props = {}
else:
self._props = self.RpcServer().get_issue_properties(issue, True)
return self._props
def GetApprovingReviewers(self):
return get_approving_reviewers(self.GetIssueProperties())
def AddComment(self, message):
return self.RpcServer().add_comment(self.GetIssue(), message)
def SetIssue(self, issue):
"""Set this branch's issue. If issue=0, clears the issue."""
if issue:
self.issue = issue
RunGit(['config', self._IssueSetting(), str(issue)])
if self.rietveld_server:
RunGit(['config', self._RietveldServer(), self.rietveld_server])
else:
current_issue = self.GetIssue()
if current_issue:
RunGit(['config', '--unset', self._IssueSetting()])
self.issue = None
self.SetPatchset(None)
def GetChange(self, upstream_branch, author):
if not self.GitSanityChecks(upstream_branch):
DieWithError('\nGit sanity check failure')
root = settings.GetRelativeRoot()
if not root:
root = '.'
absroot = os.path.abspath(root)
# We use the sha1 of HEAD as a name of this change.
name = RunGitWithCode(['rev-parse', 'HEAD'])[1].strip()
# Need to pass a relative path for msysgit.
try:
files = scm.GIT.CaptureStatus([root], '.', upstream_branch)
except subprocess2.CalledProcessError:
DieWithError(
('\nFailed to diff against upstream branch %s\n\n'
'This branch probably doesn\'t exist anymore. To reset the\n'
'tracking branch, please run\n'
' git branch --set-upstream %s trunk\n'
'replacing trunk with origin/master or the relevant branch') %
(upstream_branch, self.GetBranch()))
issue = self.GetIssue()
patchset = self.GetPatchset()
if issue:
description = self.GetDescription()
else:
# If the change was never uploaded, use the log messages of all commits
# up to the branch point, as git cl upload will prefill the description
# with these log messages.
args = ['log', '--pretty=format:%s%n%n%b', '%s...' % (upstream_branch)]
description = RunGitWithCode(args)[1].strip()
if not author:
author = RunGit(['config', 'user.email']).strip() or None
return presubmit_support.GitChange(
name,
description,
absroot,
files,
issue,
patchset,
author,
upstream=upstream_branch)
def GetStatus(self):
"""Apply a rough heuristic to give a simple summary of an issue's review
or CQ status, assuming adherence to a common workflow.
Returns None if no issue for this branch, or one of the following keywords:
* 'error' - error from review tool (including deleted issues)
* 'unsent' - not sent for review
* 'waiting' - waiting for review
* 'reply' - waiting for owner to reply to review
* 'lgtm' - LGTM from at least one approved reviewer
* 'commit' - in the commit queue
* 'closed' - closed
"""
if not self.GetIssue():
return None
try:
props = self.GetIssueProperties()
except urllib2.HTTPError:
return 'error'
if props.get('closed'):
# Issue is closed.
return 'closed'
if props.get('commit'):
# Issue is in the commit queue.
return 'commit'
try:
reviewers = self.GetApprovingReviewers()
except urllib2.HTTPError:
return 'error'
if reviewers:
# Was LGTM'ed.
return 'lgtm'
messages = props.get('messages') or []
if not messages:
# No message was sent.
return 'unsent'
if messages[-1]['sender'] != props.get('owner_email'):
# Non-LGTM reply from non-owner
return 'reply'
return 'waiting'
def RunHook(self, committing, may_prompt, verbose, change):
"""Calls sys.exit() if the hook fails; returns a HookResults otherwise."""
try:
return presubmit_support.DoPresubmitChecks(change, committing,
verbose=verbose, output_stream=sys.stdout, input_stream=sys.stdin,
default_presubmit=None, may_prompt=may_prompt,
rietveld_obj=self.RpcServer())
except presubmit_support.PresubmitFailure, e:
DieWithError(
('%s\nMaybe your depot_tools is out of date?\n'
'If all fails, contact maruel@') % e)
def UpdateDescription(self, description):
self.description = description
return self.RpcServer().update_description(
self.GetIssue(), self.description)
def CloseIssue(self):
"""Updates the description and closes the issue."""
return self.RpcServer().close_issue(self.GetIssue())
def SetFlag(self, flag, value):
"""Patchset must match."""
if not self.GetPatchset():
DieWithError('The patchset needs to match. Send another patchset.')
try:
return self.RpcServer().set_flag(
self.GetIssue(), self.GetPatchset(), flag, value)
except urllib2.HTTPError, e:
if e.code == 404:
DieWithError('The issue %s doesn\'t exist.' % self.GetIssue())
if e.code == 403:
DieWithError(
('Access denied to issue %s. Maybe the patchset %s doesn\'t '
'match?') % (self.GetIssue(), self.GetPatchset()))
raise
def RpcServer(self):
"""Returns an upload.RpcServer() to access this review's rietveld instance.
"""
if not self._rpc_server:
self._rpc_server = rietveld.CachingRietveld(
self.GetRietveldServer(),
self._auth_config or auth.make_auth_config())
return self._rpc_server
def _IssueSetting(self):
"""Return the git setting that stores this change's issue."""
return 'branch.%s.rietveldissue' % self.GetBranch()
def _PatchsetSetting(self):
"""Return the git setting that stores this change's most recent patchset."""
return 'branch.%s.rietveldpatchset' % self.GetBranch()
def _RietveldServer(self):
"""Returns the git setting that stores this change's rietveld server."""
branch = self.GetBranch()
if branch:
return 'branch.%s.rietveldserver' % branch
return None
def GetCodereviewSettingsInteractively():
"""Prompt the user for settings."""
# TODO(ukai): ask code review system is rietveld or gerrit?
server = settings.GetDefaultServerUrl(error_ok=True)
prompt = 'Rietveld server (host[:port])'
prompt += ' [%s]' % (server or DEFAULT_SERVER)
newserver = ask_for_data(prompt + ':')
if not server and not newserver:
newserver = DEFAULT_SERVER
if newserver:
newserver = gclient_utils.UpgradeToHttps(newserver)
if newserver != server:
RunGit(['config', 'rietveld.server', newserver])
def SetProperty(initial, caption, name, is_url):
prompt = caption
if initial:
prompt += ' ("x" to clear) [%s]' % initial
new_val = ask_for_data(prompt + ':')
if new_val == 'x':
RunGit(['config', '--unset-all', 'rietveld.' + name], error_ok=True)
elif new_val:
if is_url:
new_val = gclient_utils.UpgradeToHttps(new_val)
if new_val != initial:
RunGit(['config', 'rietveld.' + name, new_val])
SetProperty(settings.GetDefaultCCList(), 'CC list', 'cc', False)
SetProperty(settings.GetDefaultPrivateFlag(),
'Private flag (rietveld only)', 'private', False)
SetProperty(settings.GetTreeStatusUrl(error_ok=True), 'Tree status URL',
'tree-status-url', False)
SetProperty(settings.GetViewVCUrl(), 'ViewVC URL', 'viewvc-url', True)
SetProperty(settings.GetBugPrefix(), 'Bug Prefix', 'bug-prefix', False)
SetProperty(settings.GetRunPostUploadHook(), 'Run Post Upload Hook',
'run-post-upload-hook', False)
# TODO: configure a default branch to diff against, rather than this
# svn-based hackery.
class ChangeDescription(object):
"""Contains a parsed form of the change description."""
R_LINE = r'^[ \t]*(TBR|R)[ \t]*=[ \t]*(.*?)[ \t]*$'
BUG_LINE = r'^[ \t]*(BUG)[ \t]*=[ \t]*(.*?)[ \t]*$'
def __init__(self, description):
self._description_lines = (description or '').strip().splitlines()
@property # www.logilab.org/ticket/89786
def description(self): # pylint: disable=E0202
return '\n'.join(self._description_lines)
def set_description(self, desc):
if isinstance(desc, basestring):
lines = desc.splitlines()
else:
lines = [line.rstrip() for line in desc]
while lines and not lines[0]:
lines.pop(0)
while lines and not lines[-1]:
lines.pop(-1)
self._description_lines = lines
def update_reviewers(self, reviewers, add_owners_tbr=False, change=None):
"""Rewrites the R=/TBR= line(s) as a single line each."""
assert isinstance(reviewers, list), reviewers
if not reviewers and not add_owners_tbr:
return
reviewers = reviewers[:]
# Get the set of R= and TBR= lines and remove them from the desciption.
regexp = re.compile(self.R_LINE)
matches = [regexp.match(line) for line in self._description_lines]
new_desc = [l for i, l in enumerate(self._description_lines)
if not matches[i]]
self.set_description(new_desc)
# Construct new unified R= and TBR= lines.
r_names = []
tbr_names = []
for match in matches:
if not match:
continue
people = cleanup_list([match.group(2).strip()])
if match.group(1) == 'TBR':
tbr_names.extend(people)
else:
r_names.extend(people)
for name in r_names:
if name not in reviewers:
reviewers.append(name)
if add_owners_tbr:
owners_db = owners.Database(change.RepositoryRoot(),
fopen=file, os_path=os.path, glob=glob.glob)
all_reviewers = set(tbr_names + reviewers)
missing_files = owners_db.files_not_covered_by(change.LocalPaths(),
all_reviewers)
tbr_names.extend(owners_db.reviewers_for(missing_files,
change.author_email))
new_r_line = 'R=' + ', '.join(reviewers) if reviewers else None
new_tbr_line = 'TBR=' + ', '.join(tbr_names) if tbr_names else None
# Put the new lines in the description where the old first R= line was.
line_loc = next((i for i, match in enumerate(matches) if match), -1)
if 0 <= line_loc < len(self._description_lines):
if new_tbr_line:
self._description_lines.insert(line_loc, new_tbr_line)
if new_r_line:
self._description_lines.insert(line_loc, new_r_line)
else:
if new_r_line:
self.append_footer(new_r_line)
if new_tbr_line:
self.append_footer(new_tbr_line)
def prompt(self):
"""Asks the user to update the description."""
self.set_description([
'# Enter a description of the change.',
'# This will be displayed on the codereview site.',
'# The first line will also be used as the subject of the review.',
'#--------------------This line is 72 characters long'
'--------------------',
] + self._description_lines)
regexp = re.compile(self.BUG_LINE)
if not any((regexp.match(line) for line in self._description_lines)):
self.append_footer('BUG=%s' % settings.GetBugPrefix())
content = gclient_utils.RunEditor(self.description, True,
git_editor=settings.GetGitEditor())
if not content:
DieWithError('Running editor failed')
lines = content.splitlines()
# Strip off comments.
clean_lines = [line.rstrip() for line in lines if not line.startswith('#')]
if not clean_lines:
DieWithError('No CL description, aborting')
self.set_description(clean_lines)
def append_footer(self, line):
if self._description_lines:
# Add an empty line if either the last line or the new line isn't a tag.
last_line = self._description_lines[-1]
if (not presubmit_support.Change.TAG_LINE_RE.match(last_line) or
not presubmit_support.Change.TAG_LINE_RE.match(line)):
self._description_lines.append('')
self._description_lines.append(line)
def get_reviewers(self):
"""Retrieves the list of reviewers."""
matches = [re.match(self.R_LINE, line) for line in self._description_lines]
reviewers = [match.group(2).strip() for match in matches if match]
return cleanup_list(reviewers)
def get_approving_reviewers(props):
"""Retrieves the reviewers that approved a CL from the issue properties with
messages.
Note that the list may contain reviewers that are not committer, thus are not
considered by the CQ.
"""
return sorted(
set(
message['sender']
for message in props['messages']
if message['approval'] and message['sender'] in props['reviewers']
)
)
def FindCodereviewSettingsFile(filename='codereview.settings'):
"""Finds the given file starting in the cwd and going up.
Only looks up to the top of the repository unless an
'inherit-review-settings-ok' file exists in the root of the repository.
"""
inherit_ok_file = 'inherit-review-settings-ok'
cwd = os.getcwd()
root = settings.GetRoot()
if os.path.isfile(os.path.join(root, inherit_ok_file)):
root = '/'
while True:
if filename in os.listdir(cwd):
if os.path.isfile(os.path.join(cwd, filename)):
return open(os.path.join(cwd, filename))
if cwd == root:
break
cwd = os.path.dirname(cwd)
def LoadCodereviewSettingsFromFile(fileobj):
"""Parse a codereview.settings file and updates hooks."""
keyvals = gclient_utils.ParseCodereviewSettingsContent(fileobj.read())
def SetProperty(name, setting, unset_error_ok=False):
fullname = 'rietveld.' + name
if setting in keyvals:
RunGit(['config', fullname, keyvals[setting]])
else:
RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok)
SetProperty('server', 'CODE_REVIEW_SERVER')
# Only server setting is required. Other settings can be absent.
# In that case, we ignore errors raised during option deletion attempt.
SetProperty('cc', 'CC_LIST', unset_error_ok=True)
SetProperty('private', 'PRIVATE', unset_error_ok=True)
SetProperty('tree-status-url', 'STATUS', unset_error_ok=True)
SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True)
SetProperty('bug-prefix', 'BUG_PREFIX', unset_error_ok=True)
SetProperty('cpplint-regex', 'LINT_REGEX', unset_error_ok=True)
SetProperty('force-https-commit-url', 'FORCE_HTTPS_COMMIT_URL',
unset_error_ok=True)
SetProperty('cpplint-ignore-regex', 'LINT_IGNORE_REGEX', unset_error_ok=True)
SetProperty('project', 'PROJECT', unset_error_ok=True)
SetProperty('pending-ref-prefix', 'PENDING_REF_PREFIX', unset_error_ok=True)
SetProperty('run-post-upload-hook', 'RUN_POST_UPLOAD_HOOK',
unset_error_ok=True)
if 'GERRIT_HOST' in keyvals:
RunGit(['config', 'gerrit.host', keyvals['GERRIT_HOST']])
if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals:
#should be of the form
#PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof
#ORIGIN_URL_CONFIG: http://src.chromium.org/git
RunGit(['config', keyvals['PUSH_URL_CONFIG'],
keyvals['ORIGIN_URL_CONFIG']])
def urlretrieve(source, destination):
"""urllib is broken for SSL connections via a proxy therefore we
can't use urllib.urlretrieve()."""
with open(destination, 'w') as f:
f.write(urllib2.urlopen(source).read())
def hasSheBang(fname):
"""Checks fname is a #! script."""
with open(fname) as f:
return f.read(2).startswith('#!')
def DownloadHooks(force):
"""downloads hooks
Args:
force: True to update hooks. False to install hooks if not present.
"""
if not settings.GetIsGerrit():
return
src = 'https://gerrit-review.googlesource.com/tools/hooks/commit-msg'
dst = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg')
if not os.access(dst, os.X_OK):
if os.path.exists(dst):
if not force:
return
try:
urlretrieve(src, dst)
if not hasSheBang(dst):
DieWithError('Not a script: %s\n'
'You need to download from\n%s\n'
'into .git/hooks/commit-msg and '
'chmod +x .git/hooks/commit-msg' % (dst, src))
os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
except Exception:
if os.path.exists(dst):
os.remove(dst)
DieWithError('\nFailed to download hooks.\n'
'You need to download from\n%s\n'
'into .git/hooks/commit-msg and '
'chmod +x .git/hooks/commit-msg' % src)
@subcommand.usage('[repo root containing codereview.settings]')
def CMDconfig(parser, args):
"""Edits configuration for this tree."""
parser.add_option('--activate-update', action='store_true',
help='activate auto-updating [rietveld] section in '
'.git/config')
parser.add_option('--deactivate-update', action='store_true',
help='deactivate auto-updating [rietveld] section in '
'.git/config')
options, args = parser.parse_args(args)
if options.deactivate_update:
RunGit(['config', 'rietveld.autoupdate', 'false'])
return
if options.activate_update:
RunGit(['config', '--unset', 'rietveld.autoupdate'])
return
if len(args) == 0:
GetCodereviewSettingsInteractively()
DownloadHooks(True)
return 0
url = args[0]
if not url.endswith('codereview.settings'):
url = os.path.join(url, 'codereview.settings')
# Load code review settings and download hooks (if available).
LoadCodereviewSettingsFromFile(urllib2.urlopen(url))
DownloadHooks(True)
return 0
def CMDbaseurl(parser, args):
"""Gets or sets base-url for this branch."""
branchref = RunGit(['symbolic-ref', 'HEAD']).strip()
branch = ShortBranchName(branchref)
_, args = parser.parse_args(args)
if not args:
print("Current base-url:")
return RunGit(['config', 'branch.%s.base-url' % branch],
error_ok=False).strip()
else:
print("Setting base-url to %s" % args[0])
return RunGit(['config', 'branch.%s.base-url' % branch, args[0]],
error_ok=False).strip()
def color_for_status(status):
"""Maps a Changelist status to color, for CMDstatus and other tools."""
return {
'unsent': Fore.RED,
'waiting': Fore.BLUE,
'reply': Fore.YELLOW,
'lgtm': Fore.GREEN,
'commit': Fore.MAGENTA,
'closed': Fore.CYAN,
'error': Fore.WHITE,
}.get(status, Fore.WHITE)
def fetch_cl_status(branch, auth_config=None):
"""Fetches information for an issue and returns (branch, issue, status)."""
cl = Changelist(branchref=branch, auth_config=auth_config)
url = cl.GetIssueURL()
status = cl.GetStatus()
if url and (not status or status == 'error'):
# The issue probably doesn't exist anymore.
url += ' (broken)'
return (branch, url, status)
def get_cl_statuses(
branches, fine_grained, max_processes=None, auth_config=None):
"""Returns a blocking iterable of (branch, issue, color) for given branches.
If fine_grained is true, this will fetch CL statuses from the server.
Otherwise, simply indicate if there's a matching url for the given branches.
If max_processes is specified, it is used as the maximum number of processes
to spawn to fetch CL status from the server. Otherwise 1 process per branch is
spawned.
"""
# Silence upload.py otherwise it becomes unwieldly.
upload.verbosity = 0
if fine_grained:
# Process one branch synchronously to work through authentication, then
# spawn processes to process all the other branches in parallel.
if branches:
fetch = lambda branch: fetch_cl_status(branch, auth_config=auth_config)
yield fetch(branches[0])
branches_to_fetch = branches[1:]
pool = ThreadPool(
min(max_processes, len(branches_to_fetch))
if max_processes is not None
else len(branches_to_fetch))
for x in pool.imap_unordered(fetch, branches_to_fetch):
yield x
else:
# Do not use GetApprovingReviewers(), since it requires an HTTP request.
for b in branches:
cl = Changelist(branchref=b, auth_config=auth_config)
url = cl.GetIssueURL()
yield (b, url, 'waiting' if url else 'error')
def upload_branch_deps(cl, args):
"""Uploads CLs of local branches that are dependents of the current branch.
If the local branch dependency tree looks like:
test1 -> test2.1 -> test3.1
-> test3.2
-> test2.2 -> test3.3
and you run "git cl upload --dependencies" from test1 then "git cl upload" is
run on the dependent branches in this order:
test2.1, test3.1, test3.2, test2.2, test3.3
Note: This function does not rebase your local dependent branches. Use it when
you make a change to the parent branch that will not conflict with its
dependent branches, and you would like their dependencies updated in
Rietveld.
"""
if git_common.is_dirty_git_tree('upload-branch-deps'):
return 1
root_branch = cl.GetBranch()
if root_branch is None:
DieWithError('Can\'t find dependent branches from detached HEAD state. '
'Get on a branch!')
if not cl.GetIssue() or not cl.GetPatchset():
DieWithError('Current branch does not have an uploaded CL. We cannot set '
'patchset dependencies without an uploaded CL.')
branches = RunGit(['for-each-ref',
'--format=%(refname:short) %(upstream:short)',
'refs/heads'])
if not branches:
print('No local branches found.')
return 0
# Create a dictionary of all local branches to the branches that are dependent
# on it.
tracked_to_dependents = collections.defaultdict(list)
for b in branches.splitlines():
tokens = b.split()
if len(tokens) == 2:
branch_name, tracked = tokens
tracked_to_dependents[tracked].append(branch_name)
print
print 'The dependent local branches of %s are:' % root_branch
dependents = []
def traverse_dependents_preorder(branch, padding=''):
dependents_to_process = tracked_to_dependents.get(branch, [])
padding += ' '
for dependent in dependents_to_process:
print '%s%s' % (padding, dependent)
dependents.append(dependent)
traverse_dependents_preorder(dependent, padding)
traverse_dependents_preorder(root_branch)
print
if not dependents:
print 'There are no dependent local branches for %s' % root_branch
return 0
print ('This command will checkout all dependent branches and run '
'"git cl upload".')
ask_for_data('[Press enter to continue or ctrl-C to quit]')
# Add a default patchset title to all upload calls.
args.extend(['-t', 'Updated patchset dependency'])
# Record all dependents that failed to upload.
failures = {}
# Go through all dependents, checkout the branch and upload.
try:
for dependent_branch in dependents:
print
print '--------------------------------------'
print 'Running "git cl upload" from %s:' % dependent_branch
RunGit(['checkout', '-q', dependent_branch])
print
try:
if CMDupload(OptionParser(), args) != 0:
print 'Upload failed for %s!' % dependent_branch
failures[dependent_branch] = 1
except: # pylint: disable=W0702
failures[dependent_branch] = 1
print
finally:
# Swap back to the original root branch.
RunGit(['checkout', '-q', root_branch])
print
print 'Upload complete for dependent branches!'
for dependent_branch in dependents:
upload_status = 'failed' if failures.get(dependent_branch) else 'succeeded'
print ' %s : %s' % (dependent_branch, upload_status)
print
return 0
def CMDstatus(parser, args):
"""Show status of changelists.
Colors are used to tell the state of the CL unless --fast is used:
- Red not sent for review or broken
- Blue waiting for review
- Yellow waiting for you to reply to review
- Green LGTM'ed
- Magenta in the commit queue
- Cyan was committed, branch can be deleted
Also see 'git cl comments'.
"""
parser.add_option('--field',
help='print only specific field (desc|id|patch|url)')
parser.add_option('-f', '--fast', action='store_true',
help='Do not retrieve review status')
parser.add_option(
'-j', '--maxjobs', action='store', type=int,
help='The maximum number of jobs to use when retrieving review status')
auth.add_auth_options(parser)
options, args = parser.parse_args(args)
if args:
parser.error('Unsupported args: %s' % args)
auth_config = auth.extract_auth_config_from_options(options)
if options.field:
cl = Changelist(auth_config=auth_config)
if options.field.startswith('desc'):
print cl.GetDescription()
elif options.field == 'id':
issueid = cl.GetIssue()
if issueid:
print issueid
elif options.field == 'patch':
patchset = cl.GetPatchset()
if patchset:
print patchset
elif options.field == 'url':
url = cl.GetIssueURL()
if url:
print url
return 0
branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads'])
if not branches:
print('No local branch found.')
return 0
changes = (
Changelist(branchref=b, auth_config=auth_config)
for b in branches.splitlines())
branches = [c.GetBranch() for c in changes]
alignment = max(5, max(len(b) for b in branches))
print 'Branches associated with reviews:'
output = get_cl_statuses(branches,
fine_grained=not options.fast,
max_processes=options.maxjobs,
auth_config=auth_config)
branch_statuses = {}
alignment = max(5, max(len(ShortBranchName(b)) for b in branches))
for branch in sorted(branches):
while branch not in branch_statuses:
b, i, status = output.next()
branch_statuses[b] = (i, status)
issue_url, status = branch_statuses.pop(branch)
color = color_for_status(status)
reset = Fore.RESET
if not sys.stdout.isatty():
color = ''
reset = ''
status_str = '(%s)' % status if status else ''
print ' %*s : %s%s %s%s' % (
alignment, ShortBranchName(branch), color, issue_url, status_str,
reset)
cl = Changelist(auth_config=auth_config)
print
print 'Current branch:',
print cl.GetBranch()
if not cl.GetIssue():
print 'No issue assigned.'
return 0
print 'Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())
if not options.fast:
print 'Issue description:'
print cl.GetDescription(pretty=True)
return 0
def colorize_CMDstatus_doc():
"""To be called once in main() to add colors to git cl status help."""
colors = [i for i in dir(Fore) if i[0].isupper()]
def colorize_line(line):
for color in colors:
if color in line.upper():
# Extract whitespaces first and the leading '-'.
indent = len(line) - len(line.lstrip(' ')) + 1
return line[:indent] + getattr(Fore, color) + line[indent:] + Fore.RESET
return line
lines = CMDstatus.__doc__.splitlines()
CMDstatus.__doc__ = '\n'.join(colorize_line(l) for l in lines)
@subcommand.usage('[issue_number]')
def CMDissue(parser, args):
"""Sets or displays the current code review issue number.
Pass issue number 0 to clear the current issue.
"""
parser.add_option('-r', '--reverse', action='store_true',
help='Lookup the branch(es) for the specified issues. If '
'no issues are specified, all branches with mapped '
'issues will be listed.')
options, args = parser.parse_args(args)
if options.reverse:
branches = RunGit(['for-each-ref', 'refs/heads',
'--format=%(refname:short)']).splitlines()
# Reverse issue lookup.
issue_branch_map = {}
for branch in branches:
cl = Changelist(branchref=branch)
issue_branch_map.setdefault(cl.GetIssue(), []).append(branch)
if not args:
args = sorted(issue_branch_map.iterkeys())
for issue in args:
if not issue:
continue
print 'Branch for issue number %s: %s' % (
issue, ', '.join(issue_branch_map.get(int(issue)) or ('None',)))
else:
cl = Changelist()
if len(args) > 0:
try:
issue = int(args[0])
except ValueError:
DieWithError('Pass a number to set the issue or none to list it.\n'
'Maybe you want to run git cl status?')
cl.SetIssue(issue)
print 'Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())
return 0
def CMDcomments(parser, args):
"""Shows or posts review comments for any changelist."""
parser.add_option('-a', '--add-comment', dest='comment',
help='comment to add to an issue')
parser.add_option('-i', dest='issue',
help="review issue id (defaults to current issue)")
auth.add_auth_options(parser)
options, args = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
issue = None
if options.issue:
try:
issue = int(options.issue)
except ValueError:
DieWithError('A review issue id is expected to be a number')
cl = Changelist(issue=issue, auth_config=auth_config)
if options.comment:
cl.AddComment(options.comment)
return 0
data = cl.GetIssueProperties()
for message in sorted(data.get('messages', []), key=lambda x: x['date']):
if message['disapproval']:
color = Fore.RED
elif message['approval']:
color = Fore.GREEN
elif message['sender'] == data['owner_email']:
color = Fore.MAGENTA
else:
color = Fore.BLUE
print '\n%s%s %s%s' % (
color, message['date'].split('.', 1)[0], message['sender'],
Fore.RESET)
if message['text'].strip():
print '\n'.join(' ' + l for l in message['text'].splitlines())
return 0
def CMDdescription(parser, args):
"""Brings up the editor for the current CL's description."""
parser.add_option('-d', '--display', action='store_true',
help='Display the description instead of opening an editor')
auth.add_auth_options(parser)
options, _ = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
cl = Changelist(auth_config=auth_config)
if not cl.GetIssue():
DieWithError('This branch has no associated changelist.')
description = ChangeDescription(cl.GetDescription())
if options.display:
print description.description
return 0
description.prompt()
if cl.GetDescription() != description.description:
cl.UpdateDescription(description.description)
return 0
def CreateDescriptionFromLog(args):
"""Pulls out the commit log to use as a base for the CL description."""
log_args = []
if len(args) == 1 and not args[0].endswith('.'):
log_args = [args[0] + '..']
elif len(args) == 1 and args[0].endswith('...'):
log_args = [args[0][:-1]]
elif len(args) == 2:
log_args = [args[0] + '..' + args[1]]
else:
log_args = args[:] # Hope for the best!
return RunGit(['log', '--pretty=format:%s\n\n%b'] + log_args)
def CMDlint(parser, args):
"""Runs cpplint on the current changelist."""
parser.add_option('--filter', action='append', metavar='-x,+y',
help='Comma-separated list of cpplint\'s category-filters')
auth.add_auth_options(parser)
options, args = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
# Access to a protected member _XX of a client class
# pylint: disable=W0212
try:
import cpplint
import cpplint_chromium
except ImportError:
print "Your depot_tools is missing cpplint.py and/or cpplint_chromium.py."
return 1
# Change the current working directory before calling lint so that it
# shows the correct base.
previous_cwd = os.getcwd()
os.chdir(settings.GetRoot())
try:
cl = Changelist(auth_config=auth_config)
change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
files = [f.LocalPath() for f in change.AffectedFiles()]
if not files:
print "Cannot lint an empty CL"
return 1
# Process cpplints arguments if any.
command = args + files
if options.filter:
command = ['--filter=' + ','.join(options.filter)] + command
filenames = cpplint.ParseArguments(command)
white_regex = re.compile(settings.GetLintRegex())
black_regex = re.compile(settings.GetLintIgnoreRegex())
extra_check_functions = [cpplint_chromium.CheckPointerDeclarationWhitespace]
for filename in filenames:
if white_regex.match(filename):
if black_regex.match(filename):
print "Ignoring file %s" % filename
else:
cpplint.ProcessFile(filename, cpplint._cpplint_state.verbose_level,
extra_check_functions)
else:
print "Skipping file %s" % filename
finally:
os.chdir(previous_cwd)
print "Total errors found: %d\n" % cpplint._cpplint_state.error_count
if cpplint._cpplint_state.error_count != 0:
return 1
return 0
def CMDpresubmit(parser, args):
"""Runs presubmit tests on the current changelist."""
parser.add_option('-u', '--upload', action='store_true',
help='Run upload hook instead of the push/dcommit hook')
parser.add_option('-f', '--force', action='store_true',
help='Run checks even if tree is dirty')
auth.add_auth_options(parser)
options, args = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if not options.force and git_common.is_dirty_git_tree('presubmit'):
print 'use --force to check even if tree is dirty.'
return 1
cl = Changelist(auth_config=auth_config)
if args:
base_branch = args[0]
else:
# Default to diffing against the common ancestor of the upstream branch.
base_branch = cl.GetCommonAncestorWithUpstream()
cl.RunHook(
committing=not options.upload,
may_prompt=False,
verbose=options.verbose,
change=cl.GetChange(base_branch, None))
return 0
def AddChangeIdToCommitMessage(options, args):
"""Re-commits using the current message, assumes the commit hook is in
place.
"""
log_desc = options.message or CreateDescriptionFromLog(args)
git_command = ['commit', '--amend', '-m', log_desc]
RunGit(git_command)
new_log_desc = CreateDescriptionFromLog(args)
if CHANGE_ID in new_log_desc:
print 'git-cl: Added Change-Id to commit message.'
else:
print >> sys.stderr, 'ERROR: Gerrit commit-msg hook not available.'
def GerritUpload(options, args, cl, change):
"""upload the current branch to gerrit."""
# We assume the remote called "origin" is the one we want.
# It is probably not worthwhile to support different workflows.
gerrit_remote = 'origin'
remote, remote_branch = cl.GetRemoteBranch()
branch = GetTargetRef(remote, remote_branch, options.target_branch,
pending_prefix='')
change_desc = ChangeDescription(
options.message or CreateDescriptionFromLog(args))
if not change_desc.description:
print "Description is empty; aborting."
return 1
if options.squash:
# Try to get the message from a previous upload.
shadow_branch = 'refs/heads/git_cl_uploads/' + cl.GetBranch()
message = RunGitSilent(['show', '--format=%s\n\n%b', '-s', shadow_branch])
if not message:
if not options.force:
change_desc.prompt()
if CHANGE_ID not in change_desc.description:
# Run the commit-msg hook without modifying the head commit by writing
# the commit message to a temporary file and running the hook over it,
# then reading the file back in.
commit_msg_hook = os.path.join(settings.GetRoot(), '.git', 'hooks',
'commit-msg')
file_handle, msg_file = tempfile.mkstemp(text=True,
prefix='commit_msg')
try:
try:
with os.fdopen(file_handle, 'w') as fileobj:
fileobj.write(change_desc.description)
finally:
os.close(file_handle)
RunCommand([commit_msg_hook, msg_file])
change_desc.set_description(gclient_utils.FileRead(msg_file))
finally:
os.remove(msg_file)
if not change_desc.description:
print "Description is empty; aborting."
return 1
message = change_desc.description
remote, upstream_branch = cl.FetchUpstreamTuple(cl.GetBranch())
if remote is '.':
# If our upstream branch is local, we base our squashed commit on its
# squashed version.
parent = ('refs/heads/git_cl_uploads/' +
scm.GIT.ShortBranchName(upstream_branch))
# Verify that the upstream branch has been uploaded too, otherwise Gerrit
# will create additional CLs when uploading.
if (RunGitSilent(['rev-parse', upstream_branch + ':']) !=
RunGitSilent(['rev-parse', parent + ':'])):
print 'Upload upstream branch ' + upstream_branch + ' first.'
return 1
else:
parent = cl.GetCommonAncestorWithUpstream()
tree = RunGit(['rev-parse', 'HEAD:']).strip()
ref_to_push = RunGit(['commit-tree', tree, '-p', parent,
'-m', message]).strip()
else:
if CHANGE_ID not in change_desc.description:
AddChangeIdToCommitMessage(options, args)
ref_to_push = 'HEAD'
parent = '%s/%s' % (gerrit_remote, branch)
commits = RunGitSilent(['rev-list', '%s..%s' % (parent,
ref_to_push)]).splitlines()
if len(commits) > 1:
print('WARNING: This will upload %d commits. Run the following command '
'to see which commits will be uploaded: ' % len(commits))
print('git log %s..%s' % (parent, ref_to_push))
print('You can also use `git squash-branch` to squash these into a single '
'commit.')
ask_for_data('About to upload; enter to confirm.')
if options.reviewers or options.tbr_owners:
change_desc.update_reviewers(options.reviewers, options.tbr_owners, change)
receive_options = []
cc = cl.GetCCList().split(',')
if options.cc:
cc.extend(options.cc)
cc = filter(None, cc)
if cc:
receive_options += ['--cc=' + email for email in cc]
if change_desc.get_reviewers():
receive_options.extend(
'--reviewer=' + email for email in change_desc.get_reviewers())
git_command = ['push']
if receive_options:
git_command.append('--receive-pack=git receive-pack %s' %
' '.join(receive_options))
git_command += [gerrit_remote, ref_to_push + ':refs/for/' + branch]
RunGit(git_command)
if options.squash:
head = RunGit(['rev-parse', 'HEAD']).strip()
RunGit(['update-ref', '-m', 'Uploaded ' + head, shadow_branch, ref_to_push])
# TODO(ukai): parse Change-Id: and set issue number?
return 0
def GetTargetRef(remote, remote_branch, target_branch, pending_prefix):
"""Computes the remote branch ref to use for the CL.
Args:
remote (str): The git remote for the CL.
remote_branch (str): The git remote branch for the CL.
target_branch (str): The target branch specified by the user.
pending_prefix (str): The pending prefix from the settings.
"""
if not (remote and remote_branch):
return None
if target_branch:
# Cannonicalize branch references to the equivalent local full symbolic
# refs, which are then translated into the remote full symbolic refs
# below.
if '/' not in target_branch:
remote_branch = 'refs/remotes/%s/%s' % (remote, target_branch)
else:
prefix_replacements = (
('^((refs/)?remotes/)?branch-heads/', 'refs/remotes/branch-heads/'),
('^((refs/)?remotes/)?%s/' % remote, 'refs/remotes/%s/' % remote),
('^(refs/)?heads/', 'refs/remotes/%s/' % remote),
)
match = None
for regex, replacement in prefix_replacements:
match = re.search(regex, target_branch)
if match:
remote_branch = target_branch.replace(match.group(0), replacement)
break
if not match:
# This is a branch path but not one we recognize; use as-is.
remote_branch = target_branch
elif remote_branch in REFS_THAT_ALIAS_TO_OTHER_REFS:
# Handle the refs that need to land in different refs.
remote_branch = REFS_THAT_ALIAS_TO_OTHER_REFS[remote_branch]
# Create the true path to the remote branch.
# Does the following translation:
# * refs/remotes/origin/refs/diff/test -> refs/diff/test
# * refs/remotes/origin/master -> refs/heads/master
# * refs/remotes/branch-heads/test -> refs/branch-heads/test
if remote_branch.startswith('refs/remotes/%s/refs/' % remote):
remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, '')
elif remote_branch.startswith('refs/remotes/%s/' % remote):
remote_branch = remote_branch.replace('refs/remotes/%s/' % remote,
'refs/heads/')
elif remote_branch.startswith('refs/remotes/branch-heads'):
remote_branch = remote_branch.replace('refs/remotes/', 'refs/')
# If a pending prefix exists then replace refs/ with it.
if pending_prefix:
remote_branch = remote_branch.replace('refs/', pending_prefix)
return remote_branch
def RietveldUpload(options, args, cl, change):
"""upload the patch to rietveld."""
upload_args = ['--assume_yes'] # Don't ask about untracked files.
upload_args.extend(['--server', cl.GetRietveldServer()])
upload_args.extend(auth.auth_config_to_command_options(cl.auth_config))
if options.emulate_svn_auto_props:
upload_args.append('--emulate_svn_auto_props')
change_desc = None
if options.email is not None:
upload_args.extend(['--email', options.email])
if cl.GetIssue():
if options.title:
upload_args.extend(['--title', options.title])
if options.message:
upload_args.extend(['--message', options.message])
upload_args.extend(['--issue', str(cl.GetIssue())])
print ("This branch is associated with issue %s. "
"Adding patch to that issue." % cl.GetIssue())
else:
if options.title:
upload_args.extend(['--title', options.title])
message = options.title or options.message or CreateDescriptionFromLog(args)
change_desc = ChangeDescription(message)
if options.reviewers or options.tbr_owners:
change_desc.update_reviewers(options.reviewers,
options.tbr_owners,
change)
if not options.force:
change_desc.prompt()
if not change_desc.description:
print "Description is empty; aborting."
return 1
upload_args.extend(['--message', change_desc.description])
if change_desc.get_reviewers():
upload_args.append('--reviewers=' + ','.join(change_desc.get_reviewers()))
if options.send_mail:
if not change_desc.get_reviewers():
DieWithError("Must specify reviewers to send email.")
upload_args.append('--send_mail')
# We check this before applying rietveld.private assuming that in
# rietveld.cc only addresses which we can send private CLs to are listed
# if rietveld.private is set, and so we should ignore rietveld.cc only when
# --private is specified explicitly on the command line.
if options.private:
logging.warn('rietveld.cc is ignored since private flag is specified. '
'You need to review and add them manually if necessary.')
cc = cl.GetCCListWithoutDefault()
else:
cc = cl.GetCCList()
cc = ','.join(filter(None, (cc, ','.join(options.cc))))
if cc:
upload_args.extend(['--cc', cc])
if options.private or settings.GetDefaultPrivateFlag() == "True":
upload_args.append('--private')
upload_args.extend(['--git_similarity', str(options.similarity)])
if not options.find_copies:
upload_args.extend(['--git_no_find_copies'])
# Include the upstream repo's URL in the change -- this is useful for
# projects that have their source spread across multiple repos.
remote_url = cl.GetGitBaseUrlFromConfig()
if not remote_url:
if settings.GetIsGitSvn():
remote_url = cl.GetGitSvnRemoteUrl()
else:
if cl.GetRemoteUrl() and '/' in cl.GetUpstreamBranch():
remote_url = (cl.GetRemoteUrl() + '@'
+ cl.GetUpstreamBranch().split('/')[-1])
if remote_url:
upload_args.extend(['--base_url', remote_url])
remote, remote_branch = cl.GetRemoteBranch()
target_ref = GetTargetRef(remote, remote_branch, options.target_branch,
settings.GetPendingRefPrefix())
if target_ref:
upload_args.extend(['--target_ref', target_ref])
# Look for dependent patchsets. See crbug.com/480453 for more details.
remote, upstream_branch = cl.FetchUpstreamTuple(cl.GetBranch())
upstream_branch = ShortBranchName(upstream_branch)
if remote is '.':
# A local branch is being tracked.
local_branch = ShortBranchName(upstream_branch)
if settings.GetIsSkipDependencyUpload(local_branch):
print
print ('Skipping dependency patchset upload because git config '
'branch.%s.skip-deps-uploads is set to True.' % local_branch)
print
else:
auth_config = auth.extract_auth_config_from_options(options)
branch_cl = Changelist(branchref=local_branch, auth_config=auth_config)
branch_cl_issue_url = branch_cl.GetIssueURL()
branch_cl_issue = branch_cl.GetIssue()
branch_cl_patchset = branch_cl.GetPatchset()
if branch_cl_issue_url and branch_cl_issue and branch_cl_patchset:
upload_args.extend(
['--depends_on_patchset', '%s:%s' % (
branch_cl_issue, branch_cl_patchset)])
print
print ('The current branch (%s) is tracking a local branch (%s) with '
'an associated CL.') % (cl.GetBranch(), local_branch)
print 'Adding %s/#ps%s as a dependency patchset.' % (
branch_cl_issue_url, branch_cl_patchset)
print
project = settings.GetProject()
if project:
upload_args.extend(['--project', project])
if options.cq_dry_run:
upload_args.extend(['--cq_dry_run'])
try:
upload_args = ['upload'] + upload_args + args
logging.info('upload.RealMain(%s)', upload_args)
issue, patchset = upload.RealMain(upload_args)
issue = int(issue)
patchset = int(patchset)
except KeyboardInterrupt:
sys.exit(1)
except:
# If we got an exception after the user typed a description for their
# change, back up the description before re-raising.
if change_desc:
backup_path = os.path.expanduser(DESCRIPTION_BACKUP_FILE)
print '\nGot exception while uploading -- saving description to %s\n' \
% backup_path
backup_file = open(backup_path, 'w')
backup_file.write(change_desc.description)
backup_file.close()
raise
if not cl.GetIssue():
cl.SetIssue(issue)
cl.SetPatchset(patchset)
if options.use_commit_queue:
cl.SetFlag('commit', '1')
return 0
def cleanup_list(l):
"""Fixes a list so that comma separated items are put as individual items.
So that "--reviewers joe@c,john@c --reviewers joa@c" results in
options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']).
"""
items = sum((i.split(',') for i in l), [])
stripped_items = (i.strip() for i in items)
return sorted(filter(None, stripped_items))
@subcommand.usage('[args to "git diff"]')
def CMDupload(parser, args):
"""Uploads the current changelist to codereview.
Can skip dependency patchset uploads for a branch by running:
git config branch.branch_name.skip-deps-uploads True
To unset run:
git config --unset branch.branch_name.skip-deps-uploads
Can also set the above globally by using the --global flag.
"""
parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks',
help='bypass upload presubmit hook')
parser.add_option('--bypass-watchlists', action='store_true',
dest='bypass_watchlists',
help='bypass watchlists auto CC-ing reviewers')
parser.add_option('-f', action='store_true', dest='force',
help="force yes to questions (don't prompt)")
parser.add_option('-m', dest='message', help='message for patchset')
parser.add_option('-t', dest='title', help='title for patchset')
parser.add_option('-r', '--reviewers',
action='append', default=[],
help='reviewer email addresses')
parser.add_option('--cc',
action='append', default=[],
help='cc email addresses')
parser.add_option('-s', '--send-mail', action='store_true',
help='send email to reviewer immediately')
parser.add_option('--emulate_svn_auto_props',
'--emulate-svn-auto-props',
action="store_true",
dest="emulate_svn_auto_props",
help="Emulate Subversion's auto properties feature.")
parser.add_option('-c', '--use-commit-queue', action='store_true',
help='tell the commit queue to commit this patchset')
parser.add_option('--private', action='store_true',
help='set the review private (rietveld only)')
parser.add_option('--target_branch',
'--target-branch',
metavar='TARGET',
help='Apply CL to remote ref TARGET. ' +
'Default: remote branch head, or master')
parser.add_option('--squash', action='store_true',
help='Squash multiple commits into one (Gerrit only)')
parser.add_option('--email', default=None,
help='email address to use to connect to Rietveld')
parser.add_option('--tbr-owners', dest='tbr_owners', action='store_true',
help='add a set of OWNERS to TBR')
parser.add_option('--cq-dry-run', dest='cq_dry_run', action='store_true',
help='Send the patchset to do a CQ dry run right after '
'upload.')
parser.add_option('--dependencies', action='store_true',
help='Uploads CLs of all the local branches that depend on '
'the current branch')
orig_args = args
add_git_similarity(parser)
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if git_common.is_dirty_git_tree('upload'):
return 1
options.reviewers = cleanup_list(options.reviewers)
options.cc = cleanup_list(options.cc)
cl = Changelist(auth_config=auth_config)
if args:
# TODO(ukai): is it ok for gerrit case?
base_branch = args[0]
else:
if cl.GetBranch() is None:
DieWithError('Can\'t upload from detached HEAD state. Get on a branch!')
# Default to diffing against common ancestor of upstream branch
base_branch = cl.GetCommonAncestorWithUpstream()
args = [base_branch, 'HEAD']
# Make sure authenticated to Rietveld before running expensive hooks. It is
# a fast, best efforts check. Rietveld still can reject the authentication
# during the actual upload.
if not settings.GetIsGerrit() and auth_config.use_oauth2:
authenticator = auth.get_authenticator_for_host(
cl.GetRietveldServer(), auth_config)
if not authenticator.has_cached_credentials():
raise auth.LoginRequiredError(cl.GetRietveldServer())
# Apply watchlists on upload.
change = cl.GetChange(base_branch, None)
watchlist = watchlists.Watchlists(change.RepositoryRoot())
files = [f.LocalPath() for f in change.AffectedFiles()]
if not options.bypass_watchlists:
cl.SetWatchers(watchlist.GetWatchersForPaths(files))
if not options.bypass_hooks:
if options.reviewers or options.tbr_owners:
# Set the reviewer list now so that presubmit checks can access it.
change_description = ChangeDescription(change.FullDescriptionText())
change_description.update_reviewers(options.reviewers,
options.tbr_owners,
change)
change.SetDescriptionText(change_description.description)
hook_results = cl.RunHook(committing=False,
may_prompt=not options.force,
verbose=options.verbose,
change=change)
if not hook_results.should_continue():
return 1
if not options.reviewers and hook_results.reviewers:
options.reviewers = hook_results.reviewers.split(',')
if cl.GetIssue():
latest_patchset = cl.GetMostRecentPatchset()
local_patchset = cl.GetPatchset()
if latest_patchset and local_patchset and local_patchset != latest_patchset:
print ('The last upload made from this repository was patchset #%d but '
'the most recent patchset on the server is #%d.'
% (local_patchset, latest_patchset))
print ('Uploading will still work, but if you\'ve uploaded to this issue '
'from another machine or branch the patch you\'re uploading now '
'might not include those changes.')
ask_for_data('About to upload; enter to confirm.')
print_stats(options.similarity, options.find_copies, args)
if settings.GetIsGerrit():
return GerritUpload(options, args, cl, change)
ret = RietveldUpload(options, args, cl, change)
if not ret:
git_set_branch_value('last-upload-hash',
RunGit(['rev-parse', 'HEAD']).strip())
# Run post upload hooks, if specified.
if settings.GetRunPostUploadHook():
presubmit_support.DoPostUploadExecuter(
change,
cl,
settings.GetRoot(),
options.verbose,
sys.stdout)
# Upload all dependencies if specified.
if options.dependencies:
print
print '--dependencies has been specified.'
print 'All dependent local branches will be re-uploaded.'
print
# Remove the dependencies flag from args so that we do not end up in a
# loop.
orig_args.remove('--dependencies')
upload_branch_deps(cl, orig_args)
return ret
def IsSubmoduleMergeCommit(ref):
# When submodules are added to the repo, we expect there to be a single
# non-git-svn merge commit at remote HEAD with a signature comment.
pattern = '^SVN changes up to revision [0-9]*$'
cmd = ['rev-list', '--merges', '--grep=%s' % pattern, '%s^!' % ref]
return RunGit(cmd) != ''
def SendUpstream(parser, args, cmd):
"""Common code for CMDland and CmdDCommit
Squashes branch into a single commit.
Updates changelog with metadata (e.g. pointer to review).
Pushes/dcommits the code upstream.
Updates review and closes.
"""
parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks',
help='bypass upload presubmit hook')
parser.add_option('-m', dest='message',
help="override review description")
parser.add_option('-f', action='store_true', dest='force',
help="force yes to questions (don't prompt)")
parser.add_option('-c', dest='contributor',
help="external contributor for patch (appended to " +
"description and used as author for git). Should be " +
"formatted as 'First Last <email@example.com>'")
add_git_similarity(parser)
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
cl = Changelist(auth_config=auth_config)
current = cl.GetBranch()
remote, upstream_branch = cl.FetchUpstreamTuple(cl.GetBranch())
if not settings.GetIsGitSvn() and remote == '.':
print
print 'Attempting to push branch %r into another local branch!' % current
print
print 'Either reparent this branch on top of origin/master:'
print ' git reparent-branch --root'
print
print 'OR run `git rebase-update` if you think the parent branch is already'
print 'committed.'
print
print ' Current parent: %r' % upstream_branch
return 1
if not args or cmd == 'land':
# Default to merging against our best guess of the upstream branch.
args = [cl.GetUpstreamBranch()]
if options.contributor:
if not re.match('^.*\s<\S+@\S+>$', options.contributor):
print "Please provide contibutor as 'First Last <email@example.com>'"
return 1
base_branch = args[0]
base_has_submodules = IsSubmoduleMergeCommit(base_branch)
if git_common.is_dirty_git_tree(cmd):
return 1
# This rev-list syntax means "show all commits not in my branch that
# are in base_branch".
upstream_commits = RunGit(['rev-list', '^' + cl.GetBranchRef(),
base_branch]).splitlines()
if upstream_commits:
print ('Base branch "%s" has %d commits '
'not in this branch.' % (base_branch, len(upstream_commits)))
print 'Run "git merge %s" before attempting to %s.' % (base_branch, cmd)
return 1
# This is the revision `svn dcommit` will commit on top of.
svn_head = None
if cmd == 'dcommit' or base_has_submodules:
svn_head = RunGit(['log', '--grep=^git-svn-id:', '-1',
'--pretty=format:%H'])
if cmd == 'dcommit':
# If the base_head is a submodule merge commit, the first parent of the
# base_head should be a git-svn commit, which is what we're interested in.
base_svn_head = base_branch
if base_has_submodules:
base_svn_head += '^1'
extra_commits = RunGit(['rev-list', '^' + svn_head, base_svn_head])
if extra_commits:
print ('This branch has %d additional commits not upstreamed yet.'
% len(extra_commits.splitlines()))
print ('Upstream "%s" or rebase this branch on top of the upstream trunk '
'before attempting to %s.' % (base_branch, cmd))
return 1
merge_base = RunGit(['merge-base', base_branch, 'HEAD']).strip()
if not options.bypass_hooks:
author = None
if options.contributor:
author = re.search(r'\<(.*)\>', options.contributor).group(1)
hook_results = cl.RunHook(
committing=True,
may_prompt=not options.force,
verbose=options.verbose,
change=cl.GetChange(merge_base, author))
if not hook_results.should_continue():
return 1
# Check the tree status if the tree status URL is set.
status = GetTreeStatus()
if 'closed' == status:
print('The tree is closed. Please wait for it to reopen. Use '
'"git cl %s --bypass-hooks" to commit on a closed tree.' % cmd)
return 1
elif 'unknown' == status:
print('Unable to determine tree status. Please verify manually and '
'use "git cl %s --bypass-hooks" to commit on a closed tree.' % cmd)
return 1
else:
breakpad.SendStack(
'GitClHooksBypassedCommit',
'Issue %s/%s bypassed hook when committing (tree status was "%s")' %
(cl.GetRietveldServer(), cl.GetIssue(), GetTreeStatus()),
verbose=False)
change_desc = ChangeDescription(options.message)
if not change_desc.description and cl.GetIssue():
change_desc = ChangeDescription(cl.GetDescription())
if not change_desc.description:
if not cl.GetIssue() and options.bypass_hooks:
change_desc = ChangeDescription(CreateDescriptionFromLog([merge_base]))
else:
print 'No description set.'
print 'Visit %s/edit to set it.' % (cl.GetIssueURL())
return 1
# Keep a separate copy for the commit message, because the commit message
# contains the link to the Rietveld issue, while the Rietveld message contains
# the commit viewvc url.
# Keep a separate copy for the commit message.
if cl.GetIssue():
change_desc.update_reviewers(cl.GetApprovingReviewers())
commit_desc = ChangeDescription(change_desc.description)
if cl.GetIssue():
# Xcode won't linkify this URL unless there is a non-whitespace character
# after it. Add a period on a new line to circumvent this. Also add a space
# before the period to make sure that Gitiles continues to correctly resolve
# the URL.
commit_desc.append_footer('Review URL: %s .' % cl.GetIssueURL())
if options.contributor:
commit_desc.append_footer('Patch from %s.' % options.contributor)
print('Description:')
print(commit_desc.description)
branches = [merge_base, cl.GetBranchRef()]
if not options.force:
print_stats(options.similarity, options.find_copies, branches)
# We want to squash all this branch's commits into one commit with the proper
# description. We do this by doing a "reset --soft" to the base branch (which
# keeps the working copy the same), then dcommitting that. If origin/master
# has a submodule merge commit, we'll also need to cherry-pick the squashed
# commit onto a branch based on the git-svn head.
MERGE_BRANCH = 'git-cl-commit'
CHERRY_PICK_BRANCH = 'git-cl-cherry-pick'
# Delete the branches if they exist.
for branch in [MERGE_BRANCH, CHERRY_PICK_BRANCH]:
showref_cmd = ['show-ref', '--quiet', '--verify', 'refs/heads/%s' % branch]
result = RunGitWithCode(showref_cmd)
if result[0] == 0:
RunGit(['branch', '-D', branch])
# We might be in a directory that's present in this branch but not in the
# trunk. Move up to the top of the tree so that git commands that expect a
# valid CWD won't fail after we check out the merge branch.
rel_base_path = settings.GetRelativeRoot()
if rel_base_path:
os.chdir(rel_base_path)
# Stuff our change into the merge branch.
# We wrap in a try...finally block so if anything goes wrong,
# we clean up the branches.
retcode = -1
pushed_to_pending = False
pending_ref = None
revision = None
try:
RunGit(['checkout', '-q', '-b', MERGE_BRANCH])
RunGit(['reset', '--soft', merge_base])
if options.contributor:
RunGit(
[
'commit', '--author', options.contributor,
'-m', commit_desc.description,
])
else:
RunGit(['commit', '-m', commit_desc.description])
if base_has_submodules:
cherry_pick_commit = RunGit(['rev-list', 'HEAD^!']).rstrip()
RunGit(['branch', CHERRY_PICK_BRANCH, svn_head])
RunGit(['checkout', CHERRY_PICK_BRANCH])
RunGit(['cherry-pick', cherry_pick_commit])
if cmd == 'land':
remote, branch = cl.FetchUpstreamTuple(cl.GetBranch())
pending_prefix = settings.GetPendingRefPrefix()
if not pending_prefix or branch.startswith(pending_prefix):
# If not using refs/pending/heads/* at all, or target ref is already set
# to pending, then push to the target ref directly.
retcode, output = RunGitWithCode(
['push', '--porcelain', remote, 'HEAD:%s' % branch])
pushed_to_pending = pending_prefix and branch.startswith(pending_prefix)
else:
# Cherry-pick the change on top of pending ref and then push it.
assert branch.startswith('refs/'), branch
assert pending_prefix[-1] == '/', pending_prefix
pending_ref = pending_prefix + branch[len('refs/'):]
retcode, output = PushToGitPending(remote, pending_ref, branch)
pushed_to_pending = (retcode == 0)
if retcode == 0:
revision = RunGit(['rev-parse', 'HEAD']).strip()
else:
# dcommit the merge branch.
cmd_args = [
'svn', 'dcommit',
'-C%s' % options.similarity,
'--no-rebase', '--rmdir',
]
if settings.GetForceHttpsCommitUrl():
# Allow forcing https commit URLs for some projects that don't allow
# committing to http URLs (like Google Code).
remote_url = cl.GetGitSvnRemoteUrl()
if urlparse.urlparse(remote_url).scheme == 'http':
remote_url = remote_url.replace('http://', 'https://')
cmd_args.append('--commit-url=%s' % remote_url)
_, output = RunGitWithCode(cmd_args)
if 'Committed r' in output:
revision = re.match(
'.*?\nCommitted r(\\d+)', output, re.DOTALL).group(1)
logging.debug(output)
finally:
# And then swap back to the original branch and clean up.
RunGit(['checkout', '-q', cl.GetBranch()])
RunGit(['branch', '-D', MERGE_BRANCH])
if base_has_submodules:
RunGit(['branch', '-D', CHERRY_PICK_BRANCH])
if not revision:
print 'Failed to push. If this persists, please file a bug.'
return 1
killed = False
if pushed_to_pending:
try:
revision = WaitForRealCommit(remote, revision, base_branch, branch)
# We set pushed_to_pending to False, since it made it all the way to the
# real ref.
pushed_to_pending = False
except KeyboardInterrupt:
killed = True
if cl.GetIssue():
to_pending = ' to pending queue' if pushed_to_pending else ''
viewvc_url = settings.GetViewVCUrl()
if not to_pending:
if viewvc_url and revision:
change_desc.append_footer(
'Committed: %s%s' % (viewvc_url, revision))
elif revision:
change_desc.append_footer('Committed: %s' % (revision,))
print ('Closing issue '
'(you may be prompted for your codereview password)...')
cl.UpdateDescription(change_desc.description)
cl.CloseIssue()
props = cl.GetIssueProperties()
patch_num = len(props['patchsets'])
comment = "Committed patchset #%d (id:%d)%s manually as %s" % (
patch_num, props['patchsets'][-1], to_pending, revision)
if options.bypass_hooks:
comment += ' (tree was closed).' if GetTreeStatus() == 'closed' else '.'
else:
comment += ' (presubmit successful).'
cl.RpcServer().add_comment(cl.GetIssue(), comment)
cl.SetIssue(None)
if pushed_to_pending:
_, branch = cl.FetchUpstreamTuple(cl.GetBranch())
print 'The commit is in the pending queue (%s).' % pending_ref
print (
'It will show up on %s in ~1 min, once it gets a Cr-Commit-Position '
'footer.' % branch)
hook = POSTUPSTREAM_HOOK_PATTERN % cmd
if os.path.isfile(hook):
RunCommand([hook, merge_base], error_ok=True)
return 1 if killed else 0
def WaitForRealCommit(remote, pushed_commit, local_base_ref, real_ref):
print
print 'Waiting for commit to be landed on %s...' % real_ref
print '(If you are impatient, you may Ctrl-C once without harm)'
target_tree = RunGit(['rev-parse', '%s:' % pushed_commit]).strip()
current_rev = RunGit(['rev-parse', local_base_ref]).strip()
loop = 0
while True:
sys.stdout.write('fetching (%d)... \r' % loop)
sys.stdout.flush()
loop += 1
RunGit(['retry', 'fetch', remote, real_ref], stderr=subprocess2.VOID)
to_rev = RunGit(['rev-parse', 'FETCH_HEAD']).strip()
commits = RunGit(['rev-list', '%s..%s' % (current_rev, to_rev)])
for commit in commits.splitlines():
if RunGit(['rev-parse', '%s:' % commit]).strip() == target_tree:
print 'Found commit on %s' % real_ref
return commit
current_rev = to_rev
def PushToGitPending(remote, pending_ref, upstream_ref):
"""Fetches pending_ref, cherry-picks current HEAD on top of it, pushes.
Returns:
(retcode of last operation, output log of last operation).
"""
assert pending_ref.startswith('refs/'), pending_ref
local_pending_ref = 'refs/git-cl/' + pending_ref[len('refs/'):]
cherry = RunGit(['rev-parse', 'HEAD']).strip()
code = 0
out = ''
max_attempts = 3
attempts_left = max_attempts
while attempts_left:
if attempts_left != max_attempts:
print 'Retrying, %d attempts left...' % (attempts_left - 1,)
attempts_left -= 1
# Fetch. Retry fetch errors.
print 'Fetching pending ref %s...' % pending_ref
code, out = RunGitWithCode(
['retry', 'fetch', remote, '+%s:%s' % (pending_ref, local_pending_ref)])
if code:
print 'Fetch failed with exit code %d.' % code
if out.strip():
print out.strip()
continue
# Try to cherry pick. Abort on merge conflicts.
print 'Cherry-picking commit on top of pending ref...'
RunGitWithCode(['checkout', local_pending_ref], suppress_stderr=True)
code, out = RunGitWithCode(['cherry-pick', cherry])
if code:
print (
'Your patch doesn\'t apply cleanly to ref \'%s\', '
'the following files have merge conflicts:' % pending_ref)
print RunGit(['diff', '--name-status', '--diff-filter=U']).strip()
print 'Please rebase your patch and try again.'
RunGitWithCode(['cherry-pick', '--abort'])
return code, out
# Applied cleanly, try to push now. Retry on error (flake or non-ff push).
print 'Pushing commit to %s... It can take a while.' % pending_ref
code, out = RunGitWithCode(
['retry', 'push', '--porcelain', remote, 'HEAD:%s' % pending_ref])
if code == 0:
# Success.
print 'Commit pushed to pending ref successfully!'
return code, out
print 'Push failed with exit code %d.' % code
if out.strip():
print out.strip()
if IsFatalPushFailure(out):
print (
'Fatal push error. Make sure your .netrc credentials and git '
'user.email are correct and you have push access to the repo.')
return code, out
print 'All attempts to push to pending ref failed.'
return code, out
def IsFatalPushFailure(push_stdout):
"""True if retrying push won't help."""
return '(prohibited by Gerrit)' in push_stdout
@subcommand.usage('[upstream branch to apply against]')
def CMDdcommit(parser, args):
"""Commits the current changelist via git-svn."""
if not settings.GetIsGitSvn():
if get_footer_svn_id():
# If it looks like previous commits were mirrored with git-svn.
message = """This repository appears to be a git-svn mirror, but no
upstream SVN master is set. You probably need to run 'git auto-svn' once."""
else:
message = """This doesn't appear to be an SVN repository.
If your project has a true, writeable git repository, you probably want to run
'git cl land' instead.
If your project has a git mirror of an upstream SVN master, you probably need
to run 'git svn init'.
Using the wrong command might cause your commit to appear to succeed, and the
review to be closed, without actually landing upstream. If you choose to
proceed, please verify that the commit lands upstream as expected."""
print(message)
ask_for_data('[Press enter to dcommit or ctrl-C to quit]')
return SendUpstream(parser, args, 'dcommit')
@subcommand.usage('[upstream branch to apply against]')
def CMDland(parser, args):
"""Commits the current changelist via git."""
if settings.GetIsGitSvn() or get_footer_svn_id():
print('This appears to be an SVN repository.')
print('Are you sure you didn\'t mean \'git cl dcommit\'?')
print('(Ignore if this is the first commit after migrating from svn->git)')
ask_for_data('[Press enter to push or ctrl-C to quit]')
return SendUpstream(parser, args, 'land')
@subcommand.usage('<patch url or issue id>')
def CMDpatch(parser, args):
"""Patches in a code review."""
parser.add_option('-b', dest='newbranch',
help='create a new branch off trunk for the patch')
parser.add_option('-f', '--force', action='store_true',
help='with -b, clobber any existing branch')
parser.add_option('-d', '--directory', action='store', metavar='DIR',
help='Change to the directory DIR immediately, '
'before doing anything else.')
parser.add_option('--reject', action='store_true',
help='failed patches spew .rej files rather than '
'attempting a 3-way merge')
parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit',
help="don't commit after patch applies")
auth.add_auth_options(parser)
(options, args) = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if len(args) != 1:
parser.print_help()
return 1
issue_arg = args[0]
# We don't want uncommitted changes mixed up with the patch.
if git_common.is_dirty_git_tree('patch'):
return 1
# TODO(maruel): Use apply_issue.py
# TODO(ukai): use gerrit-cherry-pick for gerrit repository?
if options.newbranch:
if options.force:
RunGit(['branch', '-D', options.newbranch],
stderr=subprocess2.PIPE, error_ok=True)
RunGit(['checkout', '-b', options.newbranch,
Changelist().GetUpstreamBranch()])
return PatchIssue(issue_arg, options.reject, options.nocommit,
options.directory, auth_config)
def PatchIssue(issue_arg, reject, nocommit, directory, auth_config):
# PatchIssue should never be called with a dirty tree. It is up to the
# caller to check this, but just in case we assert here since the
# consequences of the caller not checking this could be dire.
assert(not git_common.is_dirty_git_tree('apply'))
if type(issue_arg) is int or issue_arg.isdigit():
# Input is an issue id. Figure out the URL.
issue = int(issue_arg)
cl = Changelist(issue=issue, auth_config=auth_config)
patchset = cl.GetMostRecentPatchset()
patch_data = cl.GetPatchSetDiff(issue, patchset)
else:
# Assume it's a URL to the patch. Default to https.
issue_url = gclient_utils.UpgradeToHttps(issue_arg)
match = re.match(r'(.*?)/download/issue(\d+)_(\d+).diff', issue_url)
if not match:
DieWithError('Must pass an issue ID or full URL for '
'\'Download raw patch set\'')
issue = int(match.group(2))
cl = Changelist(issue=issue, auth_config=auth_config)
cl.rietveld_server = match.group(1)
patchset = int(match.group(3))
patch_data = urllib2.urlopen(issue_arg).read()
# Switch up to the top-level directory, if necessary, in preparation for
# applying the patch.
top = settings.GetRelativeRoot()
if top:
os.chdir(top)
# Git patches have a/ at the beginning of source paths. We strip that out
# with a sed script rather than the -p flag to patch so we can feed either
# Git or svn-style patches into the same apply command.
# re.sub() should be used but flags=re.MULTILINE is only in python 2.7.
try:
patch_data = subprocess2.check_output(
['sed', '-e', 's|^--- a/|--- |; s|^+++ b/|+++ |'], stdin=patch_data)
except subprocess2.CalledProcessError:
DieWithError('Git patch mungling failed.')
logging.info(patch_data)
# We use "git apply" to apply the patch instead of "patch" so that we can
# pick up file adds.
# The --index flag means: also insert into the index (so we catch adds).
cmd = ['git', 'apply', '--index', '-p0']
if directory:
cmd.extend(('--directory', directory))
if reject:
cmd.append('--reject')
elif IsGitVersionAtLeast('1.7.12'):
cmd.append('--3way')
try:
subprocess2.check_call(cmd, env=GetNoGitPagerEnv(),
stdin=patch_data, stdout=subprocess2.VOID)
except subprocess2.CalledProcessError:
print 'Failed to apply the patch'
return 1
# If we had an issue, commit the current state and register the issue.
if not nocommit:
RunGit(['commit', '-m', (cl.GetDescription() + '\n\n' +
'patch from issue %(i)s at patchset '
'%(p)s (http://crrev.com/%(i)s#ps%(p)s)'
% {'i': issue, 'p': patchset})])
cl = Changelist(auth_config=auth_config)
cl.SetIssue(issue)
cl.SetPatchset(patchset)
print "Committed patch locally."
else:
print "Patch applied to index."
return 0
def CMDrebase(parser, args):
"""Rebases current branch on top of svn repo."""
# Provide a wrapper for git svn rebase to help avoid accidental
# git svn dcommit.
# It's the only command that doesn't use parser at all since we just defer
# execution to git-svn.
return RunGitWithCode(['svn', 'rebase'] + args)[1]
def GetTreeStatus(url=None):
"""Fetches the tree status and returns either 'open', 'closed',
'unknown' or 'unset'."""
url = url or settings.GetTreeStatusUrl(error_ok=True)
if url:
status = urllib2.urlopen(url).read().lower()
if status.find('closed') != -1 or status == '0':
return 'closed'
elif status.find('open') != -1 or status == '1':
return 'open'
return 'unknown'
return 'unset'
def GetTreeStatusReason():
"""Fetches the tree status from a json url and returns the message
with the reason for the tree to be opened or closed."""
url = settings.GetTreeStatusUrl()
json_url = urlparse.urljoin(url, '/current?format=json')
connection = urllib2.urlopen(json_url)
status = json.loads(connection.read())
connection.close()
return status['message']
def GetBuilderMaster(bot_list):
"""For a given builder, fetch the master from AE if available."""
map_url = 'https://builders-map.appspot.com/'
try:
master_map = json.load(urllib2.urlopen(map_url))
except urllib2.URLError as e:
return None, ('Failed to fetch builder-to-master map from %s. Error: %s.' %
(map_url, e))
except ValueError as e:
return None, ('Invalid json string from %s. Error: %s.' % (map_url, e))
if not master_map:
return None, 'Failed to build master map.'
result_master = ''
for bot in bot_list:
builder = bot.split(':', 1)[0]
master_list = master_map.get(builder, [])
if not master_list:
return None, ('No matching master for builder %s.' % builder)
elif len(master_list) > 1:
return None, ('The builder name %s exists in multiple masters %s.' %
(builder, master_list))
else:
cur_master = master_list[0]
if not result_master:
result_master = cur_master
elif result_master != cur_master:
return None, 'The builders do not belong to the same master.'
return result_master, None
def CMDtree(parser, args):
"""Shows the status of the tree."""
_, args = parser.parse_args(args)
status = GetTreeStatus()
if 'unset' == status:
print 'You must configure your tree status URL by running "git cl config".'
return 2
print "The tree is %s" % status
print
print GetTreeStatusReason()
if status != 'open':
return 1
return 0
def CMDtry(parser, args):
"""Triggers a try job through BuildBucket."""
group = optparse.OptionGroup(parser, "Try job options")
group.add_option(
"-b", "--bot", action="append",
help=("IMPORTANT: specify ONE builder per --bot flag. Use it multiple "
"times to specify multiple builders. ex: "
"'-b win_rel -b win_layout'. See "
"the try server waterfall for the builders name and the tests "
"available."))
group.add_option(
"-m", "--master", default='',
help=("Specify a try master where to run the tries."))
group.add_option(
"-r", "--revision",
help="Revision to use for the try job; default: the "
"revision will be determined by the try server; see "
"its waterfall for more info")
group.add_option(
"-c", "--clobber", action="store_true", default=False,
help="Force a clobber before building; e.g. don't do an "
"incremental build")
group.add_option(
"--project",
help="Override which project to use. Projects are defined "
"server-side to define what default bot set to use")
group.add_option(
"-n", "--name", help="Try job name; default to current branch name")
group.add_option(
"--use-rietveld", action="store_true", default=False,
help="Use Rietveld to trigger try jobs.")
group.add_option(
"--buildbucket-host", default='cr-buildbucket.appspot.com',
help="Host of buildbucket. The default host is %default.")
parser.add_option_group(group)
auth.add_auth_options(parser)
options, args = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error('Unknown arguments: %s' % args)
cl = Changelist(auth_config=auth_config)
if not cl.GetIssue():
parser.error('Need to upload first')
props = cl.GetIssueProperties()
if props.get('closed'):
parser.error('Cannot send tryjobs for a closed CL')
if props.get('private'):
parser.error('Cannot use trybots with private issue')
if not options.name:
options.name = cl.GetBranch()
if options.bot and not options.master:
options.master, err_msg = GetBuilderMaster(options.bot)
if err_msg:
parser.error('Tryserver master cannot be found because: %s\n'
'Please manually specify the tryserver master'
', e.g. "-m tryserver.chromium.linux".' % err_msg)
def GetMasterMap():
# Process --bot.
if not options.bot:
change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
# Get try masters from PRESUBMIT.py files.
masters = presubmit_support.DoGetTryMasters(
change,
change.LocalPaths(),
settings.GetRoot(),
None,
None,
options.verbose,
sys.stdout)
if masters:
return masters
# Fall back to deprecated method: get try slaves from PRESUBMIT.py files.
options.bot = presubmit_support.DoGetTrySlaves(
change,
change.LocalPaths(),
settings.GetRoot(),
None,
None,
options.verbose,
sys.stdout)
if not options.bot:
parser.error('No default try builder to try, use --bot')
builders_and_tests = {}
# TODO(machenbach): The old style command-line options don't support
# multiple try masters yet.
old_style = filter(lambda x: isinstance(x, basestring), options.bot)
new_style = filter(lambda x: isinstance(x, tuple), options.bot)
for bot in old_style:
if ':' in bot:
parser.error('Specifying testfilter is no longer supported')
elif ',' in bot:
parser.error('Specify one bot per --bot flag')
else:
builders_and_tests.setdefault(bot, []).append('defaulttests')
for bot, tests in new_style:
builders_and_tests.setdefault(bot, []).extend(tests)
# Return a master map with one master to be backwards compatible. The
# master name defaults to an empty string, which will cause the master
# not to be set on rietveld (deprecated).
return {options.master: builders_and_tests}
masters = GetMasterMap()
for builders in masters.itervalues():
if any('triggered' in b for b in builders):
print >> sys.stderr, (
'ERROR You are trying to send a job to a triggered bot. This type of'
' bot requires an\ninitial job from a parent (usually a builder). '
'Instead send your job to the parent.\n'
'Bot list: %s' % builders)
return 1
patchset = cl.GetMostRecentPatchset()
if patchset and patchset != cl.GetPatchset():
print(
'\nWARNING Mismatch between local config and server. Did a previous '
'upload fail?\ngit-cl try always uses latest patchset from rietveld. '
'Continuing using\npatchset %s.\n' % patchset)
if not options.use_rietveld:
try:
trigger_try_jobs(auth_config, cl, options, masters, 'git_cl_try')
except BuildbucketResponseException as ex:
print 'ERROR: %s' % ex
return 1
except Exception as e:
stacktrace = (''.join(traceback.format_stack()) + traceback.format_exc())
print 'ERROR: Exception when trying to trigger tryjobs: %s\n%s' % (
e, stacktrace)
return 1
else:
try:
cl.RpcServer().trigger_distributed_try_jobs(
cl.GetIssue(), patchset, options.name, options.clobber,
options.revision, masters)
except urllib2.HTTPError as e:
if e.code == 404:
print('404 from rietveld; '
'did you mean to use "git try" instead of "git cl try"?')
return 1
print('Tried jobs on:')
for (master, builders) in sorted(masters.iteritems()):
if master:
print 'Master: %s' % master
length = max(len(builder) for builder in builders)
for builder in sorted(builders):
print ' %*s: %s' % (length, builder, ','.join(builders[builder]))
return 0
@subcommand.usage('[new upstream branch]')
def CMDupstream(parser, args):
"""Prints or sets the name of the upstream branch, if any."""
_, args = parser.parse_args(args)
if len(args) > 1:
parser.error('Unrecognized args: %s' % ' '.join(args))
cl = Changelist()
if args:
# One arg means set upstream branch.
branch = cl.GetBranch()
RunGit(['branch', '--set-upstream', branch, args[0]])
cl = Changelist()
print "Upstream branch set to " + cl.GetUpstreamBranch()
# Clear configured merge-base, if there is one.
git_common.remove_merge_base(branch)
else:
print cl.GetUpstreamBranch()
return 0
def CMDweb(parser, args):
"""Opens the current CL in the web browser."""
_, args = parser.parse_args(args)
if args:
parser.error('Unrecognized args: %s' % ' '.join(args))
issue_url = Changelist().GetIssueURL()
if not issue_url:
print >> sys.stderr, 'ERROR No issue to open'
return 1
webbrowser.open(issue_url)
return 0
def CMDset_commit(parser, args):
"""Sets the commit bit to trigger the Commit Queue."""
auth.add_auth_options(parser)
options, args = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error('Unrecognized args: %s' % ' '.join(args))
cl = Changelist(auth_config=auth_config)
props = cl.GetIssueProperties()
if props.get('private'):
parser.error('Cannot set commit on private issue')
cl.SetFlag('commit', '1')
return 0
def CMDset_close(parser, args):
"""Closes the issue."""
auth.add_auth_options(parser)
options, args = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error('Unrecognized args: %s' % ' '.join(args))
cl = Changelist(auth_config=auth_config)
# Ensure there actually is an issue to close.
cl.GetDescription()
cl.CloseIssue()
return 0
def CMDdiff(parser, args):
"""Shows differences between local tree and last upload."""
auth.add_auth_options(parser)
options, args = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
if args:
parser.error('Unrecognized args: %s' % ' '.join(args))
# Uncommitted (staged and unstaged) changes will be destroyed by
# "git reset --hard" if there are merging conflicts in PatchIssue().
# Staged changes would be committed along with the patch from last
# upload, hence counted toward the "last upload" side in the final
# diff output, and this is not what we want.
if git_common.is_dirty_git_tree('diff'):
return 1
cl = Changelist(auth_config=auth_config)
issue = cl.GetIssue()
branch = cl.GetBranch()
if not issue:
DieWithError('No issue found for current branch (%s)' % branch)
TMP_BRANCH = 'git-cl-diff'
base_branch = cl.GetCommonAncestorWithUpstream()
# Create a new branch based on the merge-base
RunGit(['checkout', '-q', '-b', TMP_BRANCH, base_branch])
try:
# Patch in the latest changes from rietveld.
rtn = PatchIssue(issue, False, False, None, auth_config)
if rtn != 0:
RunGit(['reset', '--hard'])
return rtn
# Switch back to starting branch and diff against the temporary
# branch containing the latest rietveld patch.
subprocess2.check_call(['git', 'diff', TMP_BRANCH, branch, '--'])
finally:
RunGit(['checkout', '-q', branch])
RunGit(['branch', '-D', TMP_BRANCH])
return 0
def CMDowners(parser, args):
"""Interactively find the owners for reviewing."""
parser.add_option(
'--no-color',
action='store_true',
help='Use this option to disable color output')
auth.add_auth_options(parser)
options, args = parser.parse_args(args)
auth_config = auth.extract_auth_config_from_options(options)
author = RunGit(['config', 'user.email']).strip() or None
cl = Changelist(auth_config=auth_config)
if args:
if len(args) > 1:
parser.error('Unknown args')
base_branch = args[0]
else:
# Default to diffing against the common ancestor of the upstream branch.
base_branch = cl.GetCommonAncestorWithUpstream()
change = cl.GetChange(base_branch, None)
return owners_finder.OwnersFinder(
[f.LocalPath() for f in
cl.GetChange(base_branch, None).AffectedFiles()],
change.RepositoryRoot(), author,
fopen=file, os_path=os.path, glob=glob.glob,
disable_color=options.no_color).run()
def BuildGitDiffCmd(diff_type, upstream_commit, args, extensions):
"""Generates a diff command."""
# Generate diff for the current branch's changes.
diff_cmd = ['diff', '--no-ext-diff', '--no-prefix', diff_type,
upstream_commit, '--' ]
if args:
for arg in args:
if os.path.isdir(arg):
diff_cmd.extend(os.path.join(arg, '*' + ext) for ext in extensions)
elif os.path.isfile(arg):
diff_cmd.append(arg)
else:
DieWithError('Argument "%s" is not a file or a directory' % arg)
else:
diff_cmd.extend('*' + ext for ext in extensions)
return diff_cmd
@subcommand.usage('[files or directories to diff]')
def CMDformat(parser, args):
"""Runs auto-formatting tools (clang-format etc.) on the diff."""
CLANG_EXTS = ['.cc', '.cpp', '.h', '.mm', '.proto', '.java']
parser.add_option('--full', action='store_true',
help='Reformat the full content of all touched files')
parser.add_option('--dry-run', action='store_true',
help='Don\'t modify any file on disk.')
parser.add_option('--python', action='store_true',
help='Format python code with yapf (experimental).')
parser.add_option('--diff', action='store_true',
help='Print diff to stdout rather than modifying files.')
opts, args = parser.parse_args(args)
# git diff generates paths against the root of the repository. Change
# to that directory so clang-format can find files even within subdirs.
rel_base_path = settings.GetRelativeRoot()
if rel_base_path:
os.chdir(rel_base_path)
# Grab the merge-base commit, i.e. the upstream commit of the current
# branch when it was created or the last time it was rebased. This is
# to cover the case where the user may have called "git fetch origin",
# moving the origin branch to a newer commit, but hasn't rebased yet.
upstream_commit = None
cl = Changelist()
upstream_branch = cl.GetUpstreamBranch()
if upstream_branch:
upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch])
upstream_commit = upstream_commit.strip()
if not upstream_commit:
DieWithError('Could not find base commit for this branch. '
'Are you in detached state?')
if opts.full:
# Only list the names of modified files.
diff_type = '--name-only'
else:
# Only generate context-less patches.
diff_type = '-U0'
diff_cmd = BuildGitDiffCmd(diff_type, upstream_commit, args, CLANG_EXTS)
diff_output = RunGit(diff_cmd)
top_dir = os.path.normpath(
RunGit(["rev-parse", "--show-toplevel"]).rstrip('\n'))
# Locate the clang-format binary in the checkout
try:
clang_format_tool = clang_format.FindClangFormatToolInChromiumTree()
except clang_format.NotFoundError, e:
DieWithError(e)
# Set to 2 to signal to CheckPatchFormatted() that this patch isn't
# formatted. This is used to block during the presubmit.
return_value = 0
if opts.full:
# diff_output is a list of files to send to clang-format.
files = diff_output.splitlines()
if files:
cmd = [clang_format_tool]
if not opts.dry_run and not opts.diff:
cmd.append('-i')
stdout = RunCommand(cmd + files, cwd=top_dir)
if opts.diff:
sys.stdout.write(stdout)
else:
env = os.environ.copy()
env['PATH'] = str(os.path.dirname(clang_format_tool))
# diff_output is a patch to send to clang-format-diff.py
try:
script = clang_format.FindClangFormatScriptInChromiumTree(
'clang-format-diff.py')
except clang_format.NotFoundError, e:
DieWithError(e)
cmd = [sys.executable, script, '-p0']
if not opts.dry_run and not opts.diff:
cmd.append('-i')
stdout = RunCommand(cmd, stdin=diff_output, cwd=top_dir, env=env)
if opts.diff:
sys.stdout.write(stdout)
if opts.dry_run and len(stdout) > 0:
return_value = 2
# Similar code to above, but using yapf on .py files rather than clang-format
# on C/C++ files
if opts.python:
diff_cmd = BuildGitDiffCmd(diff_type, upstream_commit, args, ['.py'])
diff_output = RunGit(diff_cmd)
yapf_tool = gclient_utils.FindExecutable('yapf')
if yapf_tool is None:
DieWithError('yapf not found in PATH')
if opts.full:
files = diff_output.splitlines()
if files:
cmd = [yapf_tool]
if not opts.dry_run and not opts.diff:
cmd.append('-i')
stdout = RunCommand(cmd + files, cwd=top_dir)
if opts.diff:
sys.stdout.write(stdout)
else:
# TODO(sbc): yapf --lines mode still has some issues.
# https://github.com/google/yapf/issues/154
DieWithError('--python currently only works with --full')
# Build a diff command that only operates on dart files. dart's formatter
# does not have the nice property of only operating on modified chunks, so
# hard code full.
dart_diff_cmd = BuildGitDiffCmd('--name-only', upstream_commit,
args, ['.dart'])
dart_diff_output = RunGit(dart_diff_cmd)
if dart_diff_output:
try:
command = [dart_format.FindDartFmtToolInChromiumTree()]
if not opts.dry_run and not opts.diff:
command.append('-w')
command.extend(dart_diff_output.splitlines())
stdout = RunCommand(command, cwd=top_dir, env=env)
if opts.dry_run and stdout:
return_value = 2
except dart_format.NotFoundError as e:
print ('Unable to check dart code formatting. Dart SDK is not in ' +
'this checkout.')
return return_value
def CMDlol(parser, args):
# This command is intentionally undocumented.
print zlib.decompress(base64.b64decode(
'eNptkLEOwyAMRHe+wupCIqW57v0Vq84WqWtXyrcXnCBsmgMJ+/SSAxMZgRB6NzE'
'E2ObgCKJooYdu4uAQVffUEoE1sRQLxAcqzd7uK2gmStrll1ucV3uZyaY5sXyDd9'
'JAnN+lAXsOMJ90GANAi43mq5/VeeacylKVgi8o6F1SC63FxnagHfJUTfUYdCR/W'
'Ofe+0dHL7PicpytKP750Fh1q2qnLVof4w8OZWNY'))
return 0
class OptionParser(optparse.OptionParser):
"""Creates the option parse and add --verbose support."""
def __init__(self, *args, **kwargs):
optparse.OptionParser.__init__(
self, *args, prog='git cl', version=__version__, **kwargs)
self.add_option(
'-v', '--verbose', action='count', default=0,
help='Use 2 times for more debugging info')
def parse_args(self, args=None, values=None):
options, args = optparse.OptionParser.parse_args(self, args, values)
levels = [logging.WARNING, logging.INFO, logging.DEBUG]
logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
return options, args
def main(argv):
if sys.hexversion < 0x02060000:
print >> sys.stderr, (
'\nYour python version %s is unsupported, please upgrade.\n' %
sys.version.split(' ', 1)[0])
return 2
# Reload settings.
global settings
settings = Settings()
colorize_CMDstatus_doc()
dispatcher = subcommand.CommandDispatcher(__name__)
try:
return dispatcher.execute(OptionParser(), argv)
except auth.AuthenticationError as e:
DieWithError(str(e))
except urllib2.HTTPError, e:
if e.code != 500:
raise
DieWithError(
('AppEngine is misbehaving and returned HTTP %d, again. Keep faith '
'and retry or visit go/isgaeup.\n%s') % (e.code, str(e)))
return 0
if __name__ == '__main__':
# These affect sys.stdout so do it outside of main() to simplify mocks in
# unit testing.
fix_encoding.fix_encoding()
colorama.init()
try:
sys.exit(main(sys.argv[1:]))
except KeyboardInterrupt:
sys.stderr.write('interrupted\n')
sys.exit(1)
|
kevinkindom/chrome_depto_tools
|
git_cl.py
|
Python
|
bsd-3-clause
| 130,087
|
[
"VisIt"
] |
68c99b1fded3ec8160ff37417be4d1e090d34b72739371868173032d6cf11747
|
# coding: utf-8
# Copyright 2014-2015 Álvaro Justen <https://github.com/turicas/rows/>
#
# 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/>.
from __future__ import unicode_literals
import types
import unittest
from collections import OrderedDict
from rows.utils import ipartition, slug
class UtilsTestCase(unittest.TestCase):
def test_slug(self):
self.assertEqual(slug('Álvaro Justen'), 'alvaro_justen')
self.assertEqual(slug("Moe's Bar"), 'moes_bar')
self.assertEqual(slug("-----te-----st------"), 'te_st')
def test_ipartition(self):
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = ipartition(iterable, 3)
self.assertEqual(type(result), types.GeneratorType)
self.assertEqual(list(result), [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]])
# TODO: test download_file
# TODO: test get_uri_information
# TODO: test import_from_uri (test also args like encoding)
# TODO: test export_to_uri (test also args like encoding)
|
interlegis/rows
|
tests/tests_utils.py
|
Python
|
gpl-3.0
| 1,618
|
[
"MOE"
] |
c73a367f07f3d17678ad76187b8f29aec99308243e3ce5815e2833f099d0b97d
|
"""Names for groups of animals.
---
layout: post
source: Oxford Dictionaries
source_url: http://www.oxforddictionaries.com/words/what-do-you-call-a-group-of
title: Names for groups of animals
date: 2014-06-10 12:31:19
categories: writing
---
Names for groups of animals.
"""
from proselint.tools import memoize, preferred_forms_check
@memoize
def check(text):
"""Check the text."""
err = "oxford.venery_terms"
msg = "The venery term is '{}'."
term_list = [
["alligators", "congregation"],
["antelopes", "herd"],
["baboons", "troop"],
["badgers", "cete"],
["bats", "colony"],
["bears", "sloth"],
["buffalo", "herd"],
["bullfinches", "bellowing"],
["caribou", "herd"],
["cats", "glaring"],
["caterpillars", "army"],
["cockroaches", "intrusion"],
["coyotes", "pack"],
["crows", "murder"],
["dogs", "pack"],
["eagles", "convocation"],
["emus", "mob"],
["flamingos", "stand"],
["frogs", "army"],
["goldfinches", "charm"],
["gorillas", "band"],
["guineafowl", "rasp"],
["hedgehogs", "array"],
["herons", "siege"],
["hogs", "parcel"],
["hyenas", "cackle"],
["ibex", "herd"],
["iguanas", "mess"],
["lions", "pride"],
["locusts", "plague"],
["mackerel", "shoal"],
["mares", "stud"],
["minnows", "shoal"],
["moose", "herd"],
["mosquitoes", "scourge"],
["nightingales", "watch"],
["oysters", "bed"],
["partridges", "covey"],
["pelicans", "pod"],
["raccoons", "gaze"],
["ravens", "unkindness"],
["rhinoceroses", "crash"],
["sea urchins", "sea"],
["starlings", "murmuration"],
["toads", "knot"],
["wombats", "wisdom"],
["woodcocks", "fall"],
["woodpeckers", "descent"],
["wrens", "herd"],
]
generic_terms = [
"group",
"bunch",
]
list = []
for term_pair in term_list:
for generic in generic_terms:
wrong = f"a {generic} of {term_pair[0]}"
right = f"a {term_pair[1]} of {term_pair[0]}"
list += [[right, [wrong]]]
return preferred_forms_check(text, list, err, msg)
|
amperser/proselint
|
proselint/checks/terms/venery.py
|
Python
|
bsd-3-clause
| 2,591
|
[
"MOOSE"
] |
2daf1b6e37e74a0989fcb058a3b844360b7fbf491f56888f9fab45142f3f3d0e
|
#!/usr/bin/env python
#
# GalMap.py
#
# Elisa Antolini
# Jeremy Heyl
# UBC Southern Observatory
#
# This script generates a healpix map from a galaxy catalogue
#
# usage: GalMap.py [-h] [--zcolumn ZCOLUMN] [--num-bootstrap NUM_BOOTSTRAP]
# [--smooth SMOOTH] [--savefigures] [--no-savefigures]
# galaxy-catalogue nside zmin zmax
#
#
# Questions: heyl@phas.ubc.ca
#
# Copyright 2015, Elisa Antolini and Jeremy Heyl
#
# 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/>.
#
from argparse import ArgumentParser
import math as mt
import numpy as np
import healpy as hp
import matplotlib.pyplot as plt
import pyfits
def IndexToDeclRa(NSIDE,index):
theta,phi=hp.pixelfunc.pix2ang(NSIDE,index)
return np.degrees(mt.pi/2.0-theta),np.degrees(phi)
def DeclRaToIndex(decl,RA,NSIDE):
return hp.pixelfunc.ang2pix(NSIDE,np.radians(90.-decl),np.radians(RA))
def isPower(num, base):
if base == 1 and num != 1: return False
if base == 1 and num == 1: return True
if base == 0 and num != 1: return False
power = int (mt.log (num, base) + 0.5)
return base ** power == num
def MakeGalMap(FitsGalCat_name,nvalues,z_min,z_max,showMap,zcolumn=None,
sigma=0.01,numbootstrap=None):
#Check if the nside is a power of two
val = isPower(nvalues,2)
if val == False:
print(" **************** WARNING **************** ")
print("The inserted NSIDE is not a power of two")
y = np.log2(nvalues)
exp = int(y)
if (exp + 0.5) < y :
exp = exp +1
nvalues = int(np.power(2,exp))
print("The nearest NSIDE applicable is "+str(nvalues))
print(" ****************************************** ")
FitsMapCat_name = FitsGalCat_name+"_"+str(z_min)+"_"+str(z_max)
radians_to_deg = 57.2957795
# Lsun = 3.846e26 # Watt
# MagSun = -26.832 # Bolometric
#Load the Galaxy Catalog
hdulist = pyfits.open(FitsGalCat_name)
tabledata = hdulist[1].data
#Get RA and DEC in degrees
Gal_RA = tabledata.field('RA') * radians_to_deg
Gal_DEC = tabledata.field('DEC') * radians_to_deg
# K_mag = tabledata.field('KCORR')
if zcolumn==None:
z = tabledata.field('ZPHOTO')
else:
z = tabledata.field(zcolumn)
# dist = (z*3E05)/72
#Create the pixel map
galpixels_GalMap = np.zeros(hp.nside2npix(nvalues))
pixels = DeclRaToIndex(Gal_DEC,Gal_RA,nvalues)
#LumK = Lsun*np.power(10,(-MagSun-K_mag)/2.5)
#LumK = np.power(10,(-0.4*(-K_mag-5*np.log10(dist)-6.35)))
#galpixels_GalMap[pixels] += (np.log10(LumK))/np.log10(np.amax(LumK))
galpixels_GalMap[pixels[(z>z_min) & (z<z_max)]] += 1
GalMap_smoothed = hp.sphtfunc.smoothing(galpixels_GalMap,sigma = sigma)
if showMap:
hp.mollview(galpixels_GalMap,coord=['C','G'],rot = [0,0.3],
title='Relative Surface Density of Galaxies: %g < z < %g' % (z_min,z_max), unit='prob', xsize=nvalues)
hp.graticule()
plt.savefig(FitsMapCat_name+".png")
plt.show()
hp.mollview(GalMap_smoothed,coord=['C','G'],rot = [0,0.3],
title='Relative Surface Density of Galaxies: %g < z < %g' % (z_min,z_max), unit='prob', xsize=nvalues)
hp.graticule()
plt.savefig(FitsMapCat_name+"_smoothed.png")
plt.show()
hp.write_map(FitsMapCat_name+".fits.gz", galpixels_GalMap,coord='C')
hp.write_map(FitsMapCat_name+"_smoothed.fits.gz", GalMap_smoothed,coord='C')
if (numbootstrap!=None):
for nboot in range(numbootstrap):
iboot=np.intp(np.random.uniform(low=0.0,high=len(pixels),size=len(pixels)))
pixelsboot = pixels[iboot]
zboot = z[iboot]
galpixels_GalMap=0*galpixels_GalMap
galpixels_GalMap[pixelsboot[(zboot>z_min) & (zboot<z_max)]] += 1
GalMap_smoothed = hp.sphtfunc.smoothing(galpixels_GalMap,sigma = sigma)
hp.write_map("%s_%03d.fits.gz" % (FitsMapCat_name,nboot), galpixels_GalMap,coord='C')
hp.write_map("%s_%03d_smoothed.fits.gz" % (FitsMapCat_name,nboot), GalMap_smoothed,coord='C')
def _parse_command_line_arguments():
"""
Parse and return command line arguments
"""
parser = ArgumentParser(
description=(
'Command-line tool to generate a galaxy map from a FITS catalogue'
),
)
parser.add_argument(
'galaxy-catalogue',
type=str,
help=(
'A FITS file containing the galaxy catalogue'
),
)
parser.add_argument(
'nside',
type=int,
help=(
'nside for the output map'
'nside = ceil(sqrt(3/Pi) 60 / s)'
'where s is the length of one side of the square field of view in degrees.'
'It will be rounded to the nearest power of two.'
),
)
parser.add_argument(
'zmin',
type=float,
help='The minimum redshift for a galaxy to appear in the output map'
)
parser.add_argument(
'zmax',
type=float,
help='The maximum redshift for a galaxy to appear in the output map'
)
parser.add_argument(
'--zcolumn',
required=False,
type=str,
help='A name of the column in FITS file that contains the redshift (default ZPHOTO)'
)
parser.add_argument(
'--numbootstrap',
required=False,
type=int,
help='Number of bootstrapped maps to produce'
)
parser.add_argument('--smooth',
type=float,
help='smoothing scale in radians (default 0.01)',
required=False)
parser.set_defaults(smooth=0.01)
parser.add_argument('--savefigures',dest='savefigures',action='store_true',
help='output the healpix data in a png file')
parser.add_argument('--no-savefigures',dest='savefigures',action='store_false',
help='do not output the healpix data in a png file (default)')
parser.set_defaults(savefigures=False)
arguments = vars(parser.parse_args())
return arguments
#------------------------------------------------------------------------------
# main
#
def _main():
"""
This is the main routine.
"""
'''
#### Input Parameters #####
FitsGalCat_name = argv[1]
nvalues = int(argv[2])
z_min = float(argv[3])
z_max = float(argv[4])
showMap = argv[5]
MakeGalMap(FitsGalCat_name,nvalues,z_min,z_max,showMap)
'''
args=_parse_command_line_arguments()
MakeGalMap(args['galaxy-catalogue'],args['nside'],args['zmin'],args['zmax'],
args['savefigures'],zcolumn=args['zcolumn'],
sigma=args['smooth'],numbootstrap=args['numbootstrap'])
#------------------------------------------------------------------------------
# Start program execution.
#
if __name__ == '__main__':
_main()
|
UBC-Astrophysics/ObsPlan
|
GalMap.py
|
Python
|
gpl-3.0
| 7,788
|
[
"Galaxy"
] |
4116df6fd7e55abd73e4130e47599faa758d66dd0bfd38ad9fc93eb5691262d8
|
import pyspeckit
# Read in J000002.09+155254.1 spectrum, a nice emission-line galaxy
sp = pyspeckit.Spectrum('../tests/SIIdoublet.fits')
# Read in rest wavelengths of SII lines. If you didn't know the names already,
# you could do sp.speclines.optical.lines.keys() to see what is available.
SIIa = sp.speclines.optical.lines['SIIa'][0]
SIIb = sp.speclines.optical.lines['SIIb'][0]
# Wavelength difference between doublet lines - use to tie positions together
offset = SIIb - SIIa
# Let's have a look at the spectrum
sp.plotter()
raw_input('Let\'s do a simple continuum subtraction (continue)')
# Plot the baseline fit
sp.baseline(subtract = False)
raw_input('Let\'s zoom in on the SII doublet (continue)')
# Subtract the baseline fit and save
sp.baseline(subtract = True)
sp.plotter.savefig('doublet_example_fullspectrum.png')
# Guess for the redshift - otherwise we'll end up with the Halpha-NII complex
z = 0.02
# Zoom in on SII doublet
sp.plotter(xmin = SIIa * (1 + z) - 75, xmax = SIIb * (1 + z) + 75, ymin = -10, ymax = 60)
# Guess amplitudes to be 100, positions to be rest wavelengths
# times factor (1 + z), and widths to be 5 Angstroms
guesses = [100, SIIa * (1 + z), 5, 100, SIIb * (1 + z), 5]
tied = ['', '', '', '', 'p[1] + %g' % offset, '']
# Do the fit, and plot it
sp.specfit(guesses = guesses, tied = tied, quiet = False)
sp.plotter.savefig('doublet_example_SII.png')
raw_input('Hooray! The doublet has been fit. ')
SIIb_obs = sp.specfit.modelpars[-2]
print 'Our guess for the redshift was z = 0.02.'
print 'The redshift, as derived by the line shift, is z = %g' % ((SIIb_obs / SIIb) - 1)
|
keflavich/pyspeckit-obsolete
|
examples/doublet_example.py
|
Python
|
mit
| 1,645
|
[
"Galaxy"
] |
ef7f6b64fce1a9b3d1dfdd11b4d715fc2f9b22cd72954baa1d88be1e0798a24e
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.