def loadParameters(self):
print("NetworkX version %s running" % nx.__version__)
print("Matplotlib version %s running\n" % mplt.__version__)
nxv = nx.__version__
vOK = checkVersion(nxv, 'NetworkX', 1, 9, 1)
if not vOK:
print("NetworkX 1.9.1 or greater required")
os.sys.exit(1)
mpltv = mplt.__version__
vOK = checkVersion(mpltv, 'Matplotlib', 1, 5, 1)
if not vOK:
print("Matplotlib 1.5.1 or greater required")
os.sys.exit(1)
mySeed = eval(input("random number seed (1 to get it from the clock) "))
if mySeed == 1:
random.seed()
else:
random.seed(mySeed)
self.nAgents = 0
print("No 'bland' agents")
#self.worldXSize= input("X size of the world? ")
self.worldXSize = 1
print("X size of the world not relevant")
#self.worldYSize= input("Y size of the world? ")
self.worldYSize = 50
print("y size of the world not relevant")
# recipes
common.maxLenght = 10
common.maxSector = 6
print(
"recipes: max lenght",
common.maxLenght,
"and max sector number",
common.maxSector)
self.nCycles = eval(input("How many cycles? (0 = exit) "))
v = input("verbose? (y/[n]) ")
if v == "y" or v == "Y":
common.verbose = True # predefined False
python类__version__()的实例源码
def _init_image(self, data, cbnorm, cblinthresh, cmap, extent, aspect):
"""Store output of imshow in image variable"""
if (cbnorm == 'log10'):
norm = matplotlib.colors.LogNorm()
elif (cbnorm == 'linear'):
norm = matplotlib.colors.Normalize()
elif (cbnorm == 'symlog'):
if cblinthresh is None:
cblinthresh = (data.max()-data.min())/10.
norm = matplotlib.colors.SymLogNorm(cblinthresh, vmin=data.min(), vmax=data.max())
extent = [float(e) for e in extent]
# tuple colormaps are from palettable (or brewer2mpl)
if isinstance(cmap, tuple):
cmap = get_brewer_cmap(cmap)
self.image = self.axes.imshow(data.to_ndarray(), origin='lower',
extent=extent, norm=norm, vmin=self.zmin,
aspect=aspect, vmax=self.zmax, cmap=cmap,
interpolation='nearest')
if (cbnorm == 'symlog'):
if LooseVersion(matplotlib.__version__) < LooseVersion("2.0.0"):
formatter_kwargs = {}
else:
formatter_kwargs = dict(linthresh=cblinthresh)
formatter = matplotlib.ticker.LogFormatterMathtext(
**formatter_kwargs)
self.cb = self.figure.colorbar(
self.image, self.cax, format=formatter)
if data.min() >= 0.0:
yticks = [data.min().v] + list(
10**np.arange(np.rint(np.log10(cblinthresh)),
np.ceil(np.log10(data.max())) + 1))
elif data.max() <= 0.0:
yticks = list(
-10**np.arange(
np.floor(np.log10(-data.min())),
np.rint(np.log10(cblinthresh)) - 1, -1)) + \
[data.max().v]
else:
yticks = list(
-10**np.arange(np.floor(np.log10(-data.min())),
np.rint(np.log10(cblinthresh))-1, -1)) + \
[0] + \
list(10**np.arange(np.rint(np.log10(cblinthresh)),
np.ceil(np.log10(data.max()))+1))
self.cb.set_ticks(yticks)
else:
self.cb = self.figure.colorbar(self.image, self.cax)
for which in ['major', 'minor']:
self.cax.tick_params(which=which, axis='y', direction='in')
def streamplot(self, x, y, u, v, *args, **kwargs):
"""
Draws streamlines of a vector flow.
(see matplotlib.pyplot.streamplot documentation).
If ``latlon`` keyword is set to True, x,y are intrepreted as
longitude and latitude in degrees. Data and longitudes are
automatically shifted to match map projection region for cylindrical
and pseudocylindrical projections, and x,y are transformed to map
projection coordinates. If ``latlon`` is False (default), x and y
are assumed to be map projection coordinates.
Extra keyword ``ax`` can be used to override the default axis instance.
Other \*args and \**kwargs passed on to matplotlib.pyplot.streamplot.
"""
if _matplotlib_version < '1.2':
msg = dedent("""
streamplot method requires matplotlib 1.2 or higher,
you have %s""" % _matplotlib_version)
raise NotImplementedError(msg)
ax, plt = self._ax_plt_from_kw(kwargs)
# allow callers to override the hold state by passing hold=True|False
b = ax.ishold()
h = kwargs.pop('hold',None)
if h is not None:
ax.hold(h)
try:
ret = ax.streamplot(x,y,u,v,*args,**kwargs)
except:
ax.hold(b)
raise
ax.hold(b)
if plt is not None and ret.lines.get_array() is not None:
plt.sci(ret.lines)
# clip for round polar plots.
# streamplot arrows not returned in matplotlib 1.1.1, so clip all
# FancyArrow patches attached to axes instance.
if self. round:
ret,c = self._clipcircle(ax,ret)
for p in ax.patches:
if isinstance(p,FancyArrowPatch): p.set_clip_path(c)
# set axes limits to fit map region.
self.set_axes_limits(ax=ax)
return ret
def barbs(self, x, y, u, v, *args, **kwargs):
"""
Make a wind barb plot (u, v) with on the map.
(see matplotlib.pyplot.barbs documentation).
If ``latlon`` keyword is set to True, x,y are intrepreted as
longitude and latitude in degrees. Data and longitudes are
automatically shifted to match map projection region for cylindrical
and pseudocylindrical projections, and x,y are transformed to map
projection coordinates. If ``latlon`` is False (default), x and y
are assumed to be map projection coordinates.
Extra keyword ``ax`` can be used to override the default axis instance.
Other \*args and \**kwargs passed on to matplotlib.pyplot.barbs
Returns two matplotlib.axes.Barbs instances, one for the Northern
Hemisphere and one for the Southern Hemisphere.
"""
if _matplotlib_version < '0.98.3':
msg = dedent("""
barb method requires matplotlib 0.98.3 or higher,
you have %s""" % _matplotlib_version)
raise NotImplementedError(msg)
ax, plt = self._ax_plt_from_kw(kwargs)
# allow callers to override the hold state by passing hold=True|False
b = ax.ishold()
h = kwargs.pop('hold',None)
if h is not None:
ax.hold(h)
lons, lats = self(x, y, inverse=True)
unh = ma.masked_where(lats <= 0, u)
vnh = ma.masked_where(lats <= 0, v)
ush = ma.masked_where(lats > 0, u)
vsh = ma.masked_where(lats > 0, v)
try:
retnh = ax.barbs(x,y,unh,vnh,*args,**kwargs)
kwargs['flip_barb']=True
retsh = ax.barbs(x,y,ush,vsh,*args,**kwargs)
except:
ax.hold(b)
raise
ax.hold(b)
# Because there are two collections returned in general,
# we can't set the current image...
#if plt is not None and ret.get_array() is not None:
# plt.sci(retnh)
# clip for round polar plots.
if self.round:
retnh,c = self._clipcircle(ax,retnh)
retsh,c = self._clipcircle(ax,retsh)
# set axes limits to fit map region.
self.set_axes_limits(ax=ax)
return retnh,retsh
def streamplot(self, x, y, u, v, *args, **kwargs):
"""
Draws streamlines of a vector flow.
(see matplotlib.pyplot.streamplot documentation).
If ``latlon`` keyword is set to True, x,y are intrepreted as
longitude and latitude in degrees. Data and longitudes are
automatically shifted to match map projection region for cylindrical
and pseudocylindrical projections, and x,y are transformed to map
projection coordinates. If ``latlon`` is False (default), x and y
are assumed to be map projection coordinates.
Extra keyword ``ax`` can be used to override the default axis instance.
Other \*args and \**kwargs passed on to matplotlib.pyplot.streamplot.
"""
if _matplotlib_version < '1.2':
msg = dedent("""
streamplot method requires matplotlib 1.2 or higher,
you have %s""" % _matplotlib_version)
raise NotImplementedError(msg)
ax, plt = self._ax_plt_from_kw(kwargs)
# allow callers to override the hold state by passing hold=True|False
b = ax.ishold()
h = kwargs.pop('hold',None)
if h is not None:
ax.hold(h)
try:
ret = ax.streamplot(x,y,u,v,*args,**kwargs)
except:
ax.hold(b)
raise
ax.hold(b)
if plt is not None and ret.lines.get_array() is not None:
plt.sci(ret.lines)
# clip for round polar plots.
# streamplot arrows not returned in matplotlib 1.1.1, so clip all
# FancyArrow patches attached to axes instance.
if self. round:
ret,c = self._clipcircle(ax,ret)
for p in ax.patches:
if isinstance(p,FancyArrowPatch): p.set_clip_path(c)
# set axes limits to fit map region.
self.set_axes_limits(ax=ax)
return ret
def barbs(self, x, y, u, v, *args, **kwargs):
"""
Make a wind barb plot (u, v) with on the map.
(see matplotlib.pyplot.barbs documentation).
If ``latlon`` keyword is set to True, x,y are intrepreted as
longitude and latitude in degrees. Data and longitudes are
automatically shifted to match map projection region for cylindrical
and pseudocylindrical projections, and x,y are transformed to map
projection coordinates. If ``latlon`` is False (default), x and y
are assumed to be map projection coordinates.
Extra keyword ``ax`` can be used to override the default axis instance.
Other \*args and \**kwargs passed on to matplotlib.pyplot.barbs
Returns two matplotlib.axes.Barbs instances, one for the Northern
Hemisphere and one for the Southern Hemisphere.
"""
if _matplotlib_version < '0.98.3':
msg = dedent("""
barb method requires matplotlib 0.98.3 or higher,
you have %s""" % _matplotlib_version)
raise NotImplementedError(msg)
ax, plt = self._ax_plt_from_kw(kwargs)
# allow callers to override the hold state by passing hold=True|False
b = ax.ishold()
h = kwargs.pop('hold',None)
if h is not None:
ax.hold(h)
lons, lats = self(x, y, inverse=True)
unh = ma.masked_where(lats <= 0, u)
vnh = ma.masked_where(lats <= 0, v)
ush = ma.masked_where(lats > 0, u)
vsh = ma.masked_where(lats > 0, v)
try:
retnh = ax.barbs(x,y,unh,vnh,*args,**kwargs)
kwargs['flip_barb']=True
retsh = ax.barbs(x,y,ush,vsh,*args,**kwargs)
except:
ax.hold(b)
raise
ax.hold(b)
# Because there are two collections returned in general,
# we can't set the current image...
#if plt is not None and ret.get_array() is not None:
# plt.sci(retnh)
# clip for round polar plots.
if self.round:
retnh,c = self._clipcircle(ax,retnh)
retsh,c = self._clipcircle(ax,retsh)
# set axes limits to fit map region.
self.set_axes_limits(ax=ax)
return retnh,retsh
testing.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def package_check(pkg_name, version=None, app='pandas', checker=LooseVersion,
exc_failed_import=ImportError,
exc_failed_check=RuntimeError):
"""Check that the minimal version of the required package is installed.
Parameters
----------
pkg_name : string
Name of the required package.
version : string, optional
Minimal version number for required package.
app : string, optional
Application that is performing the check. For instance, the
name of the tutorial being executed that depends on specific
packages.
checker : object, optional
The class that will perform the version checking. Default is
distutils.version.LooseVersion.
exc_failed_import : Exception, optional
Class of the exception to be thrown if import failed.
exc_failed_check : Exception, optional
Class of the exception to be thrown if version check failed.
Examples
--------
package_check('numpy', '1.3')
package_check('networkx', '1.0', 'tutorial1')
"""
if app:
msg = '%s requires %s' % (app, pkg_name)
else:
msg = 'module requires %s' % pkg_name
if version:
msg += ' with version >= %s' % (version,)
try:
mod = __import__(pkg_name)
except ImportError:
raise exc_failed_import(msg)
if not version:
return
try:
have_version = mod.__version__
except AttributeError:
raise exc_failed_check('Cannot find version for %s' % pkg_name)
if checker(have_version) < checker(version):
raise exc_failed_check(msg)
def init_log(args, mdtrajectory):
"""
DESCRIPTION
initialyse the logfile with some information
----
Args:
args (dict): dictionnary of all arguments (argparse)
"""
topo = args["top"]
traj = args["traj"]
selection_string = args["select_traj"]
select_align = args["select_alignement"]
select_rmsd = args["select_rmsd"]
logname = os.path.splitext(args["logfile"])[0]
LOGFILE.write("========================================================\n")
LOGFILE.write("==================== TTCLUST {} ===================\n"\
.format(__version__))
LOGFILE.write("========================================================\n")
LOGFILE.write("\n")
LOGFILE.write("************ General information ************\n")
LOGFILE.write("software version : {}\n".format(__version__))
LOGFILE.write("Created on : {}\n".format(datetime.datetime.now()))
write_command_line()
LOGFILE.write("DESTINATION FOLDER : {}\n".format(os.getcwd()+"/"+logname))
LOGFILE.write("ARGUMENTS : \n")
LOGFILE.write(" Selection string :\n")
LOGFILE.write(" Atoms selected in trajectory = {} \n".format(
selection_string))
LOGFILE.write(" Atoms selected for alignement = {} \n".format(
select_align))
LOGFILE.write(" Atoms selected for RMSD = {} \n".format(select_rmsd))
LOGFILE.write(" trajectory file : {} \n".format(traj))
LOGFILE.write(" Number of frames : {} \n".format(mdtrajectory.n_frames))
LOGFILE.write(" Number of atoms : {} \n".format(mdtrajectory.n_atoms))
LOGFILE.write(" topology file : {} \n".format(topo))
LOGFILE.write(" method used of clusterring : {}".format(args["method"]))
LOGFILE.write("\n\n")
if args["ngroup"]:
LOGFILE.write(" Number of cluster asked: {}\n".format(args["ngroup"]))
if args["cutoff"]:
LOGFILE.write(" cutoff for dendrogram clustering: {}\n".format("cutoff"))
def plot_hist(clusters_list, logname,colors_list):
"""
DESCRIPTION
This function is used to plot a histogram with the cluster size.
Args:
cluster_number_list (list) : list of cluster label in order or appearance
output (str) : output logname
Returns:
None
"""
if mpl.__version__[0] == "2":
STYLE = "classic"
if STYLE in plt.style.available:
plt.style.use(STYLE)
values = []
labels = []
for cl in clusters_list:
#occurence.append((cl.id, cl.size))
values.append(cl.size)
labels.append(cl.id)
#Sorting occurence dict by cluster size
#### Configuration plot
width = 0.7 # bars size
index = np.arange(len(values)) # the x locations for the groups
fig, ax = plt.subplots()
bp = ax.bar(index, values, width, color=colors_list, label="Cluster size")
#add value on top of bars, adapted from matplotlib doc
for rect in bp:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.0*height,
'%d' % int(height),
ha='center', va='bottom')
plt.xlabel("Clusters")
plt.ylabel("Number of members")
plt.title("Distribution within clusters")
plt.xticks(index+(width/2), labels)
plt.tight_layout()
plt.savefig("{0}/{0}-hist.png".format(logname), dpi=DPI,transparent=True)
plt.close()
def plot_dendro(linkage, logname, cutoff, color_list,clusters_list):
"""
DESCRIPTION
This function will create the dendrogram graph with the corresponding
cluster color.
Args:
linkage (numpy array) : linkage matrix
output (str) : output logfile name
cutoff (float) : cutoff used for clustering
color_list (list) : HEX code color for each cluster
cluster_list (list) : list of all cluster (Cluster object)
Returns:
None
"""
if mpl.__version__[0] == "2":
STYLE = "classic"
if STYLE in plt.style.available:
plt.style.use(STYLE)
fig = plt.figure()
#Convert RGB color to HEX color
color_hex = [mpl.colors.rgb2hex(x) for x in color_list]
sch.set_link_color_palette(color_hex)
#clusters_list
color_member = {}
for cl in clusters_list:
for frm in cl.frames:
color_member[frm] = mpl.colors.rgb2hex(color_list[cl.id-1])
#Attribute the correct color for each branch.
#adapte from Ulrich Stern code in StackOverflow http://stackoverflow.com/a/38208611
link_cols = {}
for i, i12 in enumerate(linkage[:,:2].astype(int)):
c1, c2 = (link_cols[x] if x > len(linkage) else color_member[x] for x in i12)
link_cols[i+1+len(linkage)] = c1 if c1 == c2 else "#808080"
#Dendrogram creation
# Override the default linewidth.
den = sch.dendrogram(linkage, color_threshold=float(cutoff), above_threshold_color="#808080", link_color_func=lambda x: link_cols[x])
#Graph parameters
plt.title("Clustering Dendrogram")
ax = plt.axes()
ax.set_xticklabels([])
plt.axhline(y=float(cutoff), color = "grey") # cutoff value vertical line
ax.set_ylabel("Distance (AU)")
ax.set_xlabel("Frames")
plt.savefig("{0}/{0}-den.png".format(logname), format="png", dpi=DPI, transparent=True)
plt.close()
def __init__(self, font_path=None, only_persian=False, width=400, height=200, margin=2,
ranks_only=None, prefer_horizontal=.9, mask=None, scale=1,
color_func=None, max_words=200, min_font_size=4,
stopwords=None, random_state=None, background_color='black',
max_font_size=None, font_step=1, mode="RGB",
relative_scaling=.5, regexp=None, collocations=True,
colormap=None, normalize_plurals=True):
super(PersianWordCloud, self).__init__(font_path, width, height, margin,
ranks_only, prefer_horizontal, mask, scale,
color_func, max_words, min_font_size,
stopwords, random_state, background_color,
max_font_size, font_step, mode,
relative_scaling, regexp, collocations,
colormap, normalize_plurals)
if font_path is None:
font_path = FONT_PATH
if color_func is None and colormap is None:
# we need a color map
import matplotlib
version = matplotlib.__version__
if version[0] < "2" and version[2] < "5":
colormap = "hsv"
else:
colormap = "viridis"
self.only_persian = only_persian
self.colormap = colormap
self.collocations = collocations
self.font_path = font_path
self.width = width
self.height = height
self.margin = margin
self.prefer_horizontal = prefer_horizontal
self.mask = mask
self.scale = scale
self.color_func = color_func or colormap_color_func(colormap)
self.max_words = max_words
self.stopwords = stopwords if stopwords is not None else STOPWORDS
self.min_font_size = min_font_size
self.font_step = font_step
self.regexp = regexp
if isinstance(random_state, int):
random_state = Random(random_state)
self.random_state = random_state
self.background_color = background_color
self.max_font_size = max_font_size
self.mode = mode
if relative_scaling < 0 or relative_scaling > 1:
raise ValueError("relative_scaling needs to be "
"between 0 and 1, got %f." % relative_scaling)
self.relative_scaling = relative_scaling
if ranks_only is not None:
warnings.warn("ranks_only is deprecated and will be removed as"
" it had no effect. Look into relative_scaling.",
DeprecationWarning)
self.normalize_plurals = normalize_plurals