本文整理汇总了Python中matplotlib.colors.LinearSegmentedColormap.set_bad方法的典型用法代码示例。如果您正苦于以下问题:Python LinearSegmentedColormap.set_bad方法的具体用法?Python LinearSegmentedColormap.set_bad怎么用?Python LinearSegmentedColormap.set_bad使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.colors.LinearSegmentedColormap
的用法示例。
在下文中一共展示了LinearSegmentedColormap.set_bad方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_colorMap_heat
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def get_colorMap_heat():
""" according to the colorweel heat"""
color1 = np.array([0.0,14.,161.])/255.
color2 = np.array([0., 125., 11.])/255.
color3 = np.array([255.,255.,255.])/255.
color4 = np.array([255., 172., 0.])/255.
# color5 = np.array([ 184., 0.,18.])/255.
color5 = np.array([ 163., 0.,119.])/255.
cdict = {'red': ((0.0, color1[0], color1[0]),
(0.25,color2[0] ,color2[0]),
(0.5,color3[0] ,color3[0]),
(0.75,color4[0] ,color4[0]),
(1.00,color5[0] ,color5[0])),
'green': ((0.0, color1[1], color1[1]),
(0.25,color2[1] , color2[1]),
(0.5,color3[1] ,color3[1]),
(0.75,color4[1] ,color4[1]),
(1.0,color5[1] ,color5[1])),
'blue': ((0.0, color1[2], color1[2]),
(0.25, color2[2], color2[2]),
(0.5, color3[2] ,color3[2]),
(0.75,color4[2] ,color4[2]),
(1.0,color5[2] ,color5[2]))
}
hag_cmap = LinearSegmentedColormap('hag_cmap',cdict)
hag_cmap.set_bad('black')
return hag_cmap
示例2: get_colorMap_intensity_r
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def get_colorMap_intensity_r():
""" according to the colorweel intensity II"""
color5 = [0.0,4./255,76./255]
color4 = [49./255., 130./255., 0.0]
color3 = [1.,197./255.,98./255.]
color2 = [245./255., 179./255., 223./255.]
color1 = [ 216./255., 1.0,1.0]
cdict = {'red': ((0.0, color1[0], color1[0]),
(0.25,color2[0] ,color2[0]),
(0.5,color3[0] ,color3[0]),
(0.75,color4[0] ,color4[0]),
(1.00,color5[0] ,color5[0])),
'green': ((0.0, color1[1], color1[1]),
(0.25,color2[1] , color2[1]),
(0.5,color3[1] ,color3[1]),
(0.75,color4[1] ,color4[1]),
(1.0,color5[1] ,color5[1])),
'blue': ((0.0, color1[2], color1[2]),
(0.25, color2[2], color2[2]),
(0.5, color3[2] ,color3[2]),
(0.75,color4[2] ,color4[2]),
(1.0,color5[2] ,color5[2]))
}
hag_cmap = LinearSegmentedColormap('hag_cmap',cdict)
hag_cmap.set_bad('black')
return hag_cmap
示例3: get_colorMap_water
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def get_colorMap_water():
"""elevation map according to a tundra climate """
colors = []
# color.append(np.array([0.,0.,0.])/255.) #white for ice
# blue = np.array([ 0., 0., 50])/255.
blue = np.array([161., 190., 255.]) / 255.
colors.append(blue)
colors.append(blue)
# colors.append(np.array([39., 62., 44.])/255.)
# colors.append(np.array([77.,102.,70.])/255.)
# colors.append(np.array([126., 129., 110.])/255.)
# colors.append(np.array([ 95., 93.,94.])/255.)
# colors.append(np.array([1.,1.,1.])) #white for ice
steps = np.linspace(0,1,len(colors))
# print(len(colors))
# print(steps)
red = []
green = []
blue = []
for e,c in enumerate(colors):
red.append((steps[e],c[0],c[0]))
green.append((steps[e],c[1],c[1]))
blue.append((steps[e],c[2],c[2]))
cdict = {'red': red,
'green': green,
'blue': blue
}
hag_cmap = LinearSegmentedColormap('svalbard',cdict)
hag_cmap.set_bad(np.array([ 0., 0.,0.,0]))
return hag_cmap
示例4: cmap_powerlaw_adjust
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def cmap_powerlaw_adjust(cmap, a):
'''
returns a new colormap based on the one given
but adjusted via power-law:
newcmap = oldcmap**a
'''
if a < 0.:
return cmap
cdict = copy(cmap._segmentdata)
def fn(x):
return (x[0]**a, x[1], x[2])
for key in ('red','green','blue'):
try:
cdict[key] = map(fn, cdict[key])
cdict[key].sort()
assert (cdict[key][0]<0 or cdict[key][-1]>1), \
"Resulting indices extend out of the [0, 1] segment."
except TypeError:
def fngen(f):
def fn(x):
return f(x)**a
return fn
cdict[key] = fngen(cdict[key])
newcmap = LinearSegmentedColormap('colormap',cdict,1024)
newcmap.set_bad(cmap(np.nan))
return newcmap
示例5: _create_overlay_map
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def _create_overlay_map():
#transparent colormap
global _over_red
r, g, b = plotParams['mask']['color']
cdict = {'red': ((0.0, r, r),
(1.0, r, r)),
'green': ((0.0, g, g),
(1.0, g, g)),
'blue': ((0.0, b, b),
(1.0, b, b))
}
_over_red = LinearSegmentedColormap('MaskOver', cdict)
_over_red.set_bad(alpha=0)
示例6: get_color_map
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def get_color_map(color):
'''Generate a LinearSegmentedColormap with a single color and varying
transparency. Bad values and values below the lower limit are set to be
completely transparent.
Parameters
----------
color: string or array-like with shape (3,)
The color to use when overlaying the survey footprint. Either a
string that can be input to colorConverter.to_rgb() or rgb triplet.
Returns
-------
colormap1: LinearSegmentedColormap
A color map that is a single color but varies its opacity
from 0.5 to 1. Bad values and values below the minimum are completely
transparent.
'''
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.colors import colorConverter
# if the type is a string it is assumed to be an input to allow us
# to get an rgb value. If it is not a string and length is 3, it is
# assumed to be an actual rgb value
if isinstance(color, str):
rgb = colorConverter.to_rgb(color)
elif len(color) == 3:
rgb = color
else:
raise ValueError('Bad color input')
cdict = {'red': [(0, rgb[0], rgb[0]),
(1, rgb[0], rgb[0])],
'green': [(0, rgb[1], rgb[1]),
(1, rgb[1], rgb[1])],
'blue': [(0, rgb[2], rgb[2]),
(1, rgb[2], rgb[2])],
'alpha': [(0, 0.5, 0.5),
(1, 1, 1)]}
colormap1 = LinearSegmentedColormap('FootprintCM', cdict)
colormap1.set_bad(alpha=0.0)
colormap1.set_under(alpha=0.0)
return colormap1
示例7: _shiftedColorMap
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def _shiftedColorMap(self, cmap, start=0, midpoint=0.5, stop=1.0,
name='shiftedcmap'):
'''
Taken from
https://github.com/olgabot/prettyplotlib/blob/master/prettyplotlib/colors.py
which makes beautiful plots by the way
Function to offset the "center" of a colormap. Useful for
data with a negative min and positive max and you want the
middle of the colormap's dynamic range to be at zero
Input
-----
cmap : The matplotlib colormap to be altered
start : Offset from lowest point in the colormap's range.
Defaults to 0.0 (no lower ofset). Should be between
0.0 and `midpoint`.
midpoint : The new center of the colormap. Defaults to
0.5 (no shift). Should be between 0.0 and 1.0. In
general, this should be 1 - vmax/(vmax + abs(vmin))
For example if your data range from -15.0 to +5.0 and
you want the center of the colormap at 0.0, `midpoint`
should be set to 1 - 5/(5 + 15)) or 0.75
stop : Offset from highets point in the colormap's range.
Defaults to 1.0 (no upper ofset). Should be between
`midpoint` and 1.0.
'''
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
cdict = {
'red': [],
'green': [],
'blue': [],
'alpha': []
}
# regular index to compute the colors
reg_index = np.linspace(start, stop, 257)
# shifted index to match the data
shift_index = np.hstack([
np.linspace(0.0, midpoint, 128, endpoint=False),
np.linspace(midpoint, 1.0, 129, endpoint=True)
])
for ri, si in zip(reg_index, shift_index):
r, g, b, a = cmap(ri)
cdict['red'].append((si, r, r))
cdict['green'].append((si, g, g))
cdict['blue'].append((si, b, b))
cdict['alpha'].append((si, a, a))
newcmap = LinearSegmentedColormap(name, cdict)
# add some overunders
newcmap.set_bad(color='g', alpha=0.75)
newcmap.set_over(color='m', alpha=0.75)
newcmap.set_under(color='c', alpha=0.75)
plt.register_cmap(cmap=newcmap)
return newcmap
示例8: LinearSegmentedColormap
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
(0.96078431372549,0.757171875,0.757171875),
(0.964705882352941,0.76896484375,0.76896484375),
(0.968627450980392,0.78075390625,0.78075390625),
(0.972549019607843,0.79254296875,0.79254296875),
(0.976470588235294,0.80433203125,0.80433203125),
(0.980392156862745,0.81612109375,0.81612109375),
(0.984313725490196,0.82791015625,0.82791015625),
(0.988235294117647,0.839703125,0.839703125),
(0.992156862745098,0.8514921875,0.8514921875),
(0.996078431372549,0.86328125,0.86328125),
(1,0,0)),
}
califa = LinearSegmentedColormap('CALIFA', cdict)
califa.set_bad(color='navy')
califa.set_under(color='navy')
califa.set_over(color='navy')
register_cmap(cmap=califa)
#plt.xkcd()
hdus = fits.open('NGC4047.p_e.rad_SFR_lum_Mass.fits.gz')
img = hdus[0].data
fig=plt.figure()
ax1 = fig.add_subplot(111)
#img_mask= np.power(10, img)
img_masked= img
where_are_NaNs = np.isnan(img_masked)
示例9: draw_map
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def draw_map(data, genome_seq, cumcs, savefig, show, one=False, clim=None,
cmap='jet', decay=False, perc=10, name=None, cistrans=None,
decay_resolution=10000, normalized=False, max_diff=None):
_ = plt.figure(figsize=(15.,12.5))
if not max_diff:
max_diff = len(data)
ax1 = plt.axes([0.34, 0.08, 0.6, 0.7205])
ax2 = plt.axes([0.07, 0.65, 0.21, 0.15])
if decay:
ax3 = plt.axes([0.07, 0.42, 0.21, 0.15])
plot_distance_vs_interactions(data, genome_seq=genome_seq, axe=ax3,
resolution=decay_resolution,
max_diff=max_diff, normalized=normalized)
ax4 = plt.axes([0.34, 0.805, 0.6, 0.04], sharex=ax1)
ax5 = plt.axes([0.34, 0.845, 0.6, 0.04], sharex=ax1)
ax6 = plt.axes([0.34, 0.885, 0.6, 0.04], sharex=ax1)
try:
minoridata = np.nanmin(data)
maxoridata = np.nanmax(data)
except AttributeError:
vals = [i for d in data for i in d if not np.isnan(i)]
minoridata = np.min(vals)
maxoridata = np.max(vals)
totaloridata = np.nansum([data[i][j] for i in xrange(len(data))
for j in xrange(i, len(data[i]))]) # may not be square
data = nozero_log(data, np.log2)
vals = np.array([i for d in data for i in d])
vals = vals[np.isfinite(vals)]
mindata = np.nanmin(vals)
maxdata = np.nanmax(vals)
diff = maxdata - mindata
posI = 0.01 if not clim else (float(clim[0]) / diff) if clim[0] != None else 0.01
posF = 1.0 if not clim else (float(clim[1]) / diff) if clim[1] != None else 1.0
if cmap == 'tadbit':
cuts = perc
cdict = {'red' : [(0.0, 0.0, 0.0)],
'green': [(0.0, 0.0, 0.0)],
'blue' : [(0.0, 0.5, 0.5)]}
prev_pos = 0
median = (np.median(vals) - mindata) / diff
for prc in np.linspace(posI, median, cuts / 2, endpoint=False):
try:
pos = (np.percentile(vals, prc * 100.) - mindata) / diff
prc = ((prc - posI) / (median - posI)) + 1. / cuts
except ValueError:
pos = prc = 0
if prev_pos >= pos:
continue
cdict['red' ].append([pos, prc, prc])
cdict['green'].append([pos, prc, prc])
cdict['blue' ].append([pos, 1, 1])
prev_pos = pos
for prc in np.linspace(median + 1. / cuts, posF, cuts / 2, endpoint=False):
try:
pos = (np.percentile(vals, prc * 100.) - mindata) / diff
prc = ((prc - median) / (posF - median))
except ValueError:
pos = prc = 0
if prev_pos >= pos:
continue
cdict['red' ].append([pos, 1.0, 1.0])
cdict['green'].append([pos, 1 - prc, 1 - prc])
cdict['blue' ].append([pos, 1 - prc, 1 - prc])
prev_pos = pos
pos = (np.percentile(vals ,97.) - mindata) / diff
cdict['red' ].append([pos, 0.1, 0.1])
cdict['green'].append([pos, 0, 0])
cdict['blue' ].append([pos, 0, 0])
cdict['red' ].append([1.0, 1, 1])
cdict['green'].append([1.0, 1, 1])
cdict['blue' ].append([1.0, 0, 0])
cmap = LinearSegmentedColormap(cmap, cdict)
clim = None
else:
cmap = plt.get_cmap(cmap)
cmap.set_bad('darkgrey', 1)
ax1.imshow(data, interpolation='none',
cmap=cmap, vmin=clim[0] if clim else None, vmax=clim[1] if clim else None)
size1 = len(data)
size2 = len(data[0])
if size1 == size2:
for i in xrange(size1):
for j in xrange(i, size2):
if np.isnan(data[i][j]):
data[i][j] = 0
data[j][i] = 0
else:
for i in xrange(size1):
for j in xrange(size2):
if np.isnan(data[i][j]):
data[i][j] = 0
#data[j][i] = data[i][j]
try:
evals, evect = eigh(data)
sort_perm = evals.argsort()
evect = evect[sort_perm]
except:
#.........这里部分代码省略.........
示例10: test_problem_16
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def test_problem_16(self):
"""
Schittkowski problem #16
"""
cost = Problem16_Cost ()
problem = roboptim.core.PyProblem (cost)
problem.startingPoint = numpy.array([-2, 1., ])
problem.argumentBounds = numpy.array([[-2., 0.5],
[-float("inf"), 1.]])
g1 = Problem16_G1 ()
problem.addConstraint (g1, [0., float("inf"),])
g2 = Problem16_G2 ()
problem.addConstraint (g2, [0., float("inf"),])
# Check starting value
numpy.testing.assert_almost_equal (cost (problem.startingPoint)[0], 909.)
# Initialize callback
callback = IterCallback (problem)
# Let the test fail if the solver does not exist.
try:
# Create solver
log_dir = "/tmp/roboptim-core-python/problem_16"
solver = roboptim.core.PySolver ("ipopt", problem, log_dir = log_dir)
# Add callback
solver.addIterationCallback(callback)
print (solver)
solver.solve ()
r = solver.minimum ()
print (r)
# Plot results
plotter = Plotter2D([-2.1,0.6],[0,1.1])
plotter.x_res = 100
plotter.y_res = 100
plotter.plot(cost, plot_style = PlotStyle2D.PColorMesh, vmax=10,
norm=LogNorm())
# Set up a colormap:
cdict = {'red': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'green': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'alpha': ((0.0, 0.0, 0.0),
(1.0, 1.0, 1.0))
}
cstr_cmap = LinearSegmentedColormap('Mask', cdict)
cstr_cmap.set_under('r', alpha=0)
cstr_cmap.set_over('w', alpha=0)
cstr_cmap.set_bad('g', alpha=0)
plotter.plot(g1, plot_style=PlotStyle2D.Contourf,
linewidth=10, alpha=None,
cmap=cstr_cmap, vmax=0, fontsize=20)
plotter.plot(g1, plot_style=PlotStyle2D.Contour,
linewidth=10, alpha=None, levels=[0],
vmax=0, fontsize=20, colors="k")
plotter.plot(g2, plot_style=PlotStyle2D.Contourf,
linewidth=10, alpha=None,
cmap=cstr_cmap, vmax=0)
# Print iterations
X = zip(*callback.x)[0]
Y = zip(*callback.x)[1]
# Show evolution
plotter.add_marker(X, Y,
color="white", marker=".", markersize=5)
# First point
plotter.add_marker(X[0], Y[0],
color="white", marker="o", markersize=10, markeredgewidth=2)
# Final result
plotter.add_marker(X[-1], Y[-1],
color="white", marker="s", markersize=10, markeredgewidth=2)
# Print actual global minimum
plotter.add_marker(0.5, 0.25,
color="black", marker="x", markersize=14, markeredgewidth=6)
plotter.add_marker(0.5, 0.25,
color="white", marker="x", markersize=10, markeredgewidth=3)
plotter.show()
except Exception as e:
print ("Error: %s" % e)
示例11: generate_cmap_flame
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
(0,1,1),
(0,1,0.3),
(1,1,0),
(1,0.5,0),
(1,0,0),
(0.5,0,0)
]
flame = LinearSegmentedColormap.from_list('flame', clrs)
#flame.set_bad(flame(0)) # set nan's and inf's to white
flame.set_bad('0.75') # set nan's and inf's to light gray
return flame
flame = generate_cmap_flame()
cubehelix = LinearSegmentedColormap('cubehelix',cm.revcmap(_cm.cubehelix(1,0,1,2.5)))
cubehelix.set_bad(cubehelix(0))
def cmap_powerlaw_adjust(cmap, a):
'''
returns a new colormap based on the one given
but adjusted via power-law:
newcmap = oldcmap**a
'''
if a < 0.:
return cmap
cdict = copy(cmap._segmentdata)
def fn(x):
return (x[0]**a, x[1], x[2])
for key in ('red','green','blue'):
try:
示例12: draw_map
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def draw_map(
data,
genome_seq,
cumcs,
savefig,
show,
one=False,
clim=None,
cmap="jet",
decay=False,
perc=10,
name=None,
cistrans=None,
decay_resolution=10000,
normalized=False,
max_diff=None,
):
_ = plt.figure(figsize=(15.0, 12.5))
if not max_diff:
max_diff = len(data)
ax1 = plt.axes([0.34, 0.08, 0.6, 0.7205])
ax2 = plt.axes([0.07, 0.65, 0.21, 0.15])
if decay:
ax3 = plt.axes([0.07, 0.42, 0.21, 0.15])
plot_distance_vs_interactions(
data, genome_seq=genome_seq, axe=ax3, resolution=decay_resolution, max_diff=max_diff, normalized=normalized
)
ax4 = plt.axes([0.34, 0.805, 0.6, 0.04], sharex=ax1)
ax5 = plt.axes([0.34, 0.845, 0.6, 0.04], sharex=ax1)
ax6 = plt.axes([0.34, 0.885, 0.6, 0.04], sharex=ax1)
try:
minoridata = np.nanmin(data)
maxoridata = np.nanmax(data)
except AttributeError:
vals = [i for d in data for i in d if not np.isnan(i)]
minoridata = np.min(vals)
maxoridata = np.max(vals)
totaloridata = np.nansum([data[i][j] for i in xrange(len(data)) for j in xrange(i, len(data))])
data = nozero_log(data, np.log2)
vals = np.array([i for d in data for i in d])
vals = vals[np.isfinite(vals)]
mindata = np.nanmin(vals)
maxdata = np.nanmax(vals)
diff = maxdata - mindata
posI = 0.01 if not clim else (float(clim[0]) / diff) if clim[0] != None else 0.01
posF = 1.0 if not clim else (float(clim[1]) / diff) if clim[1] != None else 1.0
if cmap == "tadbit":
cuts = perc
cdict = {"red": [(0.0, 0.0, 0.0)], "green": [(0.0, 0.0, 0.0)], "blue": [(0.0, 0.5, 0.5)]}
prev_pos = 0
median = (np.median(vals) - mindata) / diff
for prc in np.linspace(posI, median, cuts / 2, endpoint=False):
try:
pos = (np.percentile(vals, prc * 100.0) - mindata) / diff
prc = ((prc - posI) / (median - posI)) + 1.0 / cuts
except ValueError:
pos = prc = 0
if prev_pos >= pos:
continue
cdict["red"].append([pos, prc, prc])
cdict["green"].append([pos, prc, prc])
cdict["blue"].append([pos, 1, 1])
prev_pos = pos
for prc in np.linspace(median + 1.0 / cuts, posF, cuts / 2, endpoint=False):
try:
pos = (np.percentile(vals, prc * 100.0) - mindata) / diff
prc = (prc - median) / (posF - median)
except ValueError:
pos = prc = 0
if prev_pos >= pos:
continue
cdict["red"].append([pos, 1.0, 1.0])
cdict["green"].append([pos, 1 - prc, 1 - prc])
cdict["blue"].append([pos, 1 - prc, 1 - prc])
prev_pos = pos
pos = (np.percentile(vals, 97.0) - mindata) / diff
cdict["red"].append([pos, 0.1, 0.1])
cdict["green"].append([pos, 0, 0])
cdict["blue"].append([pos, 0, 0])
cdict["red"].append([1.0, 1, 1])
cdict["green"].append([1.0, 1, 1])
cdict["blue"].append([1.0, 0, 0])
cmap = LinearSegmentedColormap(cmap, cdict)
clim = None
else:
cmap = plt.get_cmap(cmap)
cmap.set_bad("darkgrey", 1)
ax1.imshow(data, interpolation="none", cmap=cmap, vmin=clim[0] if clim else None, vmax=clim[1] if clim else None)
size = len(data)
for i in xrange(size):
for j in xrange(i, size):
if np.isnan(data[i][j]):
data[i][j] = 0
data[j][i] = 0
# data[j][i] = data[i][j]
evals, evect = eigh(data)
sort_perm = evals.argsort()
#.........这里部分代码省略.........
示例13: mds
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def mds(MATRIX_FILE, DIMENSIONS, N_ITERATIONS, IMAGES_EVERY, STATION_BLOCK_SIZE, N_NEARBY_STATIONS, DEBUG_OUTPUT, STATUS_FUNCTION, GRAPH_FUNCTION) :
print 'Loading matrix...'
npz = np.load(MATRIX_FILE)
station_coords = npz['station_coords']
grid_dim = npz['grid_dim']
matrix = npz['matrix'].astype(np.int32)
# EVERYTHING SHOULD BE IN FLOAT32 for ease of debugging. even times.
# Matrix and others should be textures, arrays, or in constant memory, to do cacheing.
# As it is, I'm doing explicit cacheing.
# force OD matrix symmetry for test
# THIS was responsible for the coordinate drift!!!
# need to symmetrize it before copy to device
matrix = (matrix + matrix.T) / 2
station_coords_int = station_coords.round().astype(np.int32)
# to be removed when textures are working
station_coords_gpu = gpuarray.to_gpu(station_coords_int)
matrix_gpu = gpuarray.to_gpu(matrix)
max_x, max_y = grid_dim
n_gridpoints = int(max_x * max_y)
n_stations = len(station_coords)
cuda_grid_shape = ( int( math.ceil( float(max_x)/CUDA_BLOCK_SHAPE[0] ) ), int( math.ceil( float(max_y)/CUDA_BLOCK_SHAPE[1] ) ) )
print "\n----PARAMETERS----"
print "Input file: ", MATRIX_FILE
print "Number of stations: ", n_stations
print "OD matrix shape: ", matrix.shape
print "Station coords shape: ", station_coords_int.shape
print "Station cache size: ", N_NEARBY_STATIONS
print "Map dimensions: ", grid_dim
print "Number of map points: ", n_gridpoints
print "Target space dimensionality: ", DIMENSIONS
print "CUDA block dimensions: ", CUDA_BLOCK_SHAPE
print "CUDA grid dimensions: ", cuda_grid_shape
assert station_coords.shape == (n_stations, 2)
assert N_NEARBY_STATIONS <= n_stations
#sys.exit()
# Make and register custom color map for pylab graphs
cdict = {'red': ((0.0, 0.0, 0.0),
(0.2, 0.0, 0.0),
(0.4, 0.9, 0.9),
(1.0, 0.0, 0.0)),
'green': ((0.0, 0.0, 0.1),
(0.05, 0.9, 0.9),
(0.1, 0.0, 0.0),
(0.4, 0.9, 0.9),
(0.6, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(0.05, 0.0, 0.0),
(0.2, 0.9, 0.9),
(0.3, 0.0, 0.0),
(1.0, 0.0, 0.0))}
mymap = LinearSegmentedColormap('mymap', cdict)
mymap.set_over( (1.0, 0.0, 1.0) )
mymap.set_bad ( (0.0, 0.0, 0.0) )
pl.plt.register_cmap(cmap=mymap)
# set up arrays for calculations
coords_gpu = gpuarray.to_gpu(np.random.random( (max_x, max_y, DIMENSIONS) ).astype(np.float32)) # initialize coordinates to random values in range 0...1
forces_gpu = gpuarray.zeros( (int(max_x), int(max_y), DIMENSIONS), dtype=np.float32 ) # 3D float32 accumulate forces over one timestep
weights_gpu = gpuarray.zeros( (int(max_x), int(max_y)), dtype=np.float32 ) # 2D float32 cell error accumulation
errors_gpu = gpuarray.zeros( (int(max_x), int(max_y)), dtype=np.float32 ) # 2D float32 cell error accumulation
near_stations_gpu = gpuarray.zeros( (cuda_grid_shape[0], cuda_grid_shape[1], N_NEARBY_STATIONS), dtype=np.int32)
debug_gpu = gpuarray.zeros( n_gridpoints, dtype = np.int32 )
debug_img_gpu = gpuarray.zeros_like( errors_gpu )
print "\n----COMPILATION----"
# times could be merged into forces kernel, if done by pixel not station.
# integrate kernel could be GPUArray operation; also helps clean up code by using GPUArrays.
# DIM should be replaced by python script, so as not to define twice.
src = open("unified_mds.cu").read()
src = src.replace( 'N_NEARBY_STATIONS_PYTHON', str(N_NEARBY_STATIONS) )
src = src.replace( 'N_STATIONS_PYTHON', str(n_stations) )
src = src.replace( 'DIMENSIONS_PYTHON', str(DIMENSIONS) )
mod = SourceModule(src, options=["--ptxas-options=-v"])
stations_kernel = mod.get_function("stations" )
forces_kernel = mod.get_function("forces" )
integrate_kernel = mod.get_function("integrate")
matrix_texref = mod.get_texref('tex_matrix')
station_coords_texref = mod.get_texref('tex_station_coords')
near_stations_texref = mod.get_texref('tex_near_stations')
#ts_coords_texref = mod.get_texref('tex_ts_coords') could be a 4-channel 2 dim texture, or 3 dim texture. or just 1D.
#.........这里部分代码省略.........
示例14: run
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import set_bad [as 别名]
def run (self) :
cuda.init()
self.cuda_dev = cuda.Device(0)
self.cuda_context = self.cuda_dev.make_context()
# print 'Loading matrix...'
# npz = np.load(self.MATRIX_FILE)
# station_coords = npz['station_coords']
# grid_dim = npz['grid_dim']
# matrix = npz['matrix']
station_coords = self.station_coords
grid_dim = self.grid_dim
matrix = self.matrix
nearby_stations = self.nearby_stations
# EVERYTHING SHOULD BE IN FLOAT32 for ease of debugging. even times.
# Matrix and others should be textures, arrays, or in constant memory, to do cacheing.
# make matrix symmetric before converting to int32. this avoids halving the pseudo-infinity value.
matrix = (matrix + matrix.T) / 2
#print np.where(matrix == np.inf)
matrix[matrix == np.inf] = 99999999
# nan == nan is False because any operation involving nan is False !
# must use specific isnan function. however, inf works like a normal number.
matrix[np.isnan(matrix)] = 99999999
#matrix[matrix >= 60 * 60 * 3] = 0
matrix = matrix.astype(np.int32)
#matrix += 60 * 5
#matrix = np.nan_to_num(matrix)
print matrix
# force OD matrix symmetry for test
# THIS was responsible for the coordinate drift!!!
# need to symmetrize it before copy to device
# matrix = (matrix + matrix.T) / 2
# print matrix
#print np.any(matrix == np.nan)
#print np.any(matrix == np.inf)
station_coords_int = station_coords.round().astype(np.int32)
# to be removed when textures are working
station_coords_gpu = gpuarray.to_gpu(station_coords_int)
matrix_gpu = gpuarray.to_gpu(matrix)
max_x, max_y = grid_dim
n_gridpoints = int(max_x * max_y)
n_stations = len(station_coords)
cuda_grid_shape = ( int( math.ceil( float(max_x)/CUDA_BLOCK_SHAPE[0] ) ), int( math.ceil( float(max_y)/CUDA_BLOCK_SHAPE[1] ) ) )
print "\n----PARAMETERS----"
print "Input file: ", self.MATRIX_FILE
print "Number of stations: ", n_stations
print "OD matrix shape: ", matrix.shape
print "Station coords shape: ", station_coords_int.shape
print "Station cache size: ", self.N_NEARBY_STATIONS
print "Map dimensions: ", grid_dim
print "Number of map points: ", n_gridpoints
print "Target space dimensionality: ", self.DIMENSIONS
print "CUDA block dimensions: ", CUDA_BLOCK_SHAPE
print "CUDA grid dimensions: ", cuda_grid_shape
assert station_coords.shape == (n_stations, 2)
assert self.N_NEARBY_STATIONS <= n_stations
#sys.exit()
# Make and register custom color map for pylab graphs
cdict = {'red': ((0.0, 0.0, 0.0),
(0.2, 0.0, 0.0),
(0.4, 0.9, 0.9),
(1.0, 0.0, 0.0)),
'green': ((0.0, 0.0, 0.1),
(0.05, 0.9, 0.9),
(0.1, 0.0, 0.0),
(0.4, 0.9, 0.9),
(0.6, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(0.05, 0.0, 0.0),
(0.2, 0.9, 0.9),
(0.3, 0.0, 0.0),
(1.0, 0.0, 0.0))}
mymap = LinearSegmentedColormap('mymap', cdict)
mymap.set_over( (1.0, 0.0, 1.0) )
mymap.set_bad ( (0.0, 0.0, 0.0) )
#pl.plt.register_cmap(cmap=mymap)
# set up arrays for calculations
coords_gpu = gpuarray.to_gpu(np.random.random( (max_x, max_y, self.DIMENSIONS) ).astype(np.float32)) # initialize coordinates to random values in range 0...1
forces_gpu = gpuarray.zeros( (int(max_x), int(max_y), self.DIMENSIONS), dtype=np.float32 ) # 3D float32 accumulate forces over one timestep
weights_gpu = gpuarray.zeros( (int(max_x), int(max_y)), dtype=np.float32 ) # 2D float32 cell error accumulation
errors_gpu = gpuarray.zeros( (int(max_x), int(max_y)), dtype=np.float32 ) # 2D float32 cell error accumulation
#.........这里部分代码省略.........