def draw_contour_plot(self, valuations, nafrica): """ Note that this is not useful for the web. Also it is not useful for calling over ssh because it pops up a picture. @param valuations: valuations conformant to the spanning tree points @param nafrica: the number of points on the continent boundary """ # y axis is flipped in matplotlib relative to cairo x = self.x_final y = [self.t_height - y for y in self.y_final] # get the relevant points mst_x = x[nafrica:] mst_y = y[nafrica:] # do a grid interpolation xvalues = np.arange(min(mst_x), max(mst_x), 1.0) yvalues = np.arange(min(mst_y), max(mst_y), 1.0) xi, yi = np.meshgrid(xvalues, yvalues) tri = Triangulation(mst_x, mst_y) interp = tri.nn_interpolator(valuations) zi = interp(xi, yi) # define the africa clip path # http://matplotlib.sourceforge.net/examples/api/compound_path.html continent_poly = np.array(zip(x[:nafrica], y[:nafrica]) + [(0, 0)]) continent_codes = ([matplotlib.path.Path.MOVETO] + [matplotlib.path.Path.LINETO] * (nafrica - 1) + [matplotlib.path.Path.CLOSEPOLY]) continent_path = matplotlib.path.Path(continent_poly, continent_codes) # draw the plot plt.figure() cs = plt.contour(xi, yi, zi, clip_path=continent_path) plt.fill(x[:nafrica], y[:nafrica], fill=False) plt.axes().set_aspect('equal') plt.show()
def __init__(self, xrange=(0.0, 1.0), yrange=(0.0, 1.0), nrange=101, npoints=250): self.xrange = xrange self.yrange = yrange self.nrange = nrange self.npoints = npoints rng = np.random.RandomState(1234567890) self.x = rng.uniform(xrange[0], xrange[1], size=npoints) self.y = rng.uniform(yrange[0], yrange[1], size=npoints) self.tri = Triangulation(self.x, self.y)
class LinearTester(object): name = 'Linear' def __init__(self, xrange=(0.0, 1.0), yrange=(0.0, 1.0), nrange=101, npoints=250): self.xrange = xrange self.yrange = yrange self.nrange = nrange self.npoints = npoints rng = np.random.RandomState(1234567890) self.x = rng.uniform(xrange[0], xrange[1], size=npoints) self.y = rng.uniform(yrange[0], yrange[1], size=npoints) self.tri = Triangulation(self.x, self.y) def replace_data(self, dataset): self.x = dataset.x self.y = dataset.y self.tri = Triangulation(self.x, self.y) def interpolator(self, func): z = func(self.x, self.y) return self.tri.linear_extrapolator(z, bbox=self.xrange+self.yrange) def plot(self, func, interp=True, plotter='imshow'): if interp: lpi = self.interpolator(func) z = lpi[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] else: y, x = np.mgrid[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] z = func(x, y) z = np.where(np.isinf(z), 0.0, z) extent = (self.xrange[0], self.xrange[1], self.yrange[0], self.yrange[1]) fig = plt.figure() plt.hot() # Some like it hot if plotter == 'imshow': plt.imshow(np.nan_to_num(z), interpolation='nearest', extent=extent, origin='lower') elif plotter == 'contour': Y, X = np.ogrid[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] plt.contour(np.ravel(X), np.ravel(Y), z, 20) x = self.x y = self.y lc = mpl.collections.LineCollection(np.array([((x[i], y[i]), (x[j], y[j])) for i, j in self.tri.edge_db]), colors=[(0,0,0,0.2)]) ax = plt.gca() ax.add_collection(lc) if interp: title = '%s Interpolant' % self.name else: title = 'Reference' if hasattr(func, 'title'): plt.title('%s: %s' % (func.title, title)) else: plt.title(title)
class LinearTester(object): name = 'Linear' def __init__(self, xrange=(0.0, 1.0), yrange=(0.0, 1.0), nrange=101, npoints=250): self.xrange = xrange self.yrange = yrange self.nrange = nrange self.npoints = npoints rng = np.random.RandomState(1234567890) self.x = rng.uniform(xrange[0], xrange[1], size=npoints) self.y = rng.uniform(yrange[0], yrange[1], size=npoints) self.tri = Triangulation(self.x, self.y) def replace_data(self, dataset): self.x = dataset.x self.y = dataset.y self.tri = Triangulation(self.x, self.y) def interpolator(self, func): z = func(self.x, self.y) return self.tri.linear_extrapolator(z, bbox=self.xrange+self.yrange) def plot(self, func, interp=True, plotter='imshow'): if interp: lpi = self.interpolator(func) z = lpi[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] else: y, x = np.mgrid[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] z = func(x, y) z = np.where(np.isinf(z), 0.0, z) extent = (self.xrange[0], self.xrange[1], self.yrange[0], self.yrange[1]) fig = plt.figure() plt.hot() # Some like it hot if plotter == 'imshow': plt.imshow(np.nan_to_num(z), interpolation='nearest', extent=extent, origin='lower') elif plotter == 'contour': Y, X = np.ogrid[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] plt.contour(np.ravel(X), np.ravel(Y), z, 20) x = self.x y = self.y lc = mpl.collections.LineCollection(np.array([((x[i], y[i]), (x[j], y[j])) for i, j in self.tri.edge_db]), colors=[(0,0,0,0.2)]) ax = plt.gca() ax.add_collection(lc) if interp: title = '%s Interpolant' % self.name else: title = 'Reference' if hasattr(func, 'title'): plt.title('%s: %s' % (func.title, title)) else: plt.title(title)
def __init__(self, xrange=(0.0, 1.0), yrange=(0.0, 1.0), nrange=101, npoints=250): self.xrange = xrange self.yrange = yrange self.nrange = nrange self.npoints = npoints rng = np.random.RandomState(1234567890) self.x = rng.uniform(xrange[0], xrange[1], size=npoints) self.y = rng.uniform(yrange[0], yrange[1], size=npoints) self.tri = Triangulation(self.x, self.y)
def get_response_content(fs): # use a fixed seed if requested if fs.seed: random.seed(fs.seed) # define the max number of rejection iterations limit = fs.npoints * 100 # validate input if fs.axis < 0: raise ValueError('the mds axis must be nonnegative') # get points defining the boundary of africa nafrica = len(g_africa_poly) africa_edges = [(i, (i + 1) % nafrica) for i in range(nafrica)] # get some points and edges inside africa points = sample_with_rejection(fs.npoints, g_africa_poly, limit) x_list, y_list = zip(*points) tri = Triangulation(x_list, y_list) tri_edges = [(i + nafrica, j + nafrica) for i, j in tri.edge_db.tolist()] # get the whole list of points allpoints = g_africa_poly + points # refine the list of edges tri_edges = list(gen_noncrossing_edges(tri_edges, africa_edges, allpoints)) tri_edges = get_mst(tri_edges, allpoints) alledges = africa_edges + tri_edges # make the graph laplacian A = np.zeros((len(points), len(points))) for ia, ib in tri_edges: xa, ya = allpoints[ia] xb, yb = allpoints[ib] d = math.hypot(xb - xa, yb - ya) A[ia - nafrica, ib - nafrica] = 1 / d A[ib - nafrica, ia - nafrica] = 1 / d L = Euclid.adjacency_to_laplacian(A) ws, vs = EigUtil.eigh(np.linalg.pinv(L)) if fs.axis >= len(ws): raise ValueError('choose a smaller mds axis') v = vs[fs.axis] # get the color and sizes for the points v /= max(np.abs(v)) colors = [(0, 0, 0)] * nafrica + [get_color(x) for x in v] radii = [2] * nafrica + [5 for p in points] # get the width and height of the drawable area of the image width = fs.total_width - 2 * fs.border height = fs.total_height - 2 * fs.border if width < 1 or height < 1: msg = 'the image dimensions do not allow for enough drawable area' raise HandlingError(msg) # draw the image ext = Form.g_imageformat_to_ext[fs.imageformat] try: helper = ImgHelper(allpoints, alledges, fs.total_width, fs.total_height, fs.border) return helper.get_image_string(colors, radii, ext) except CairoUtil.CairoUtilError as e: raise HandlingError(e)
def mesh(xs, ys, npoints): # randomly choose some points rng = random.RandomState(1234567890) rx = rng.uniform(xs[0], xs[1], size=npoints) ry = rng.uniform(ys[0], ys[1], size=npoints) # only take points in domain nx, ny = [], [] for x,y in zip(rx,ry): if in_domain(x,y): nx.append(x) ny.append(y) # Delaunay triangulation tri = Triangulation(array(nx), array(ny)) return tri
def draw_contour_plot(self, valuations, nafrica): """ Note that this is not useful for the web. Also it is not useful for calling over ssh because it pops up a picture. @param valuations: valuations conformant to the spanning tree points @param nafrica: the number of points on the continent boundary """ # y axis is flipped in matplotlib relative to cairo x = self.x_final y = [self.t_height - y for y in self.y_final] # get the relevant points mst_x = x[nafrica:] mst_y = y[nafrica:] # do a grid interpolation xvalues = np.arange(min(mst_x), max(mst_x), 1.0) yvalues = np.arange(min(mst_y), max(mst_y), 1.0) xi, yi = np.meshgrid(xvalues, yvalues) tri = Triangulation(mst_x, mst_y) interp = tri.nn_interpolator(valuations) zi = interp(xi, yi) # define the africa clip path # http://matplotlib.sourceforge.net/examples/api/compound_path.html continent_poly = np.array(zip(x[:nafrica], y[:nafrica]) + [(0, 0)]) continent_codes = ( [matplotlib.path.Path.MOVETO] + [matplotlib.path.Path.LINETO] * (nafrica - 1) + [matplotlib.path.Path.CLOSEPOLY] ) continent_path = matplotlib.path.Path(continent_poly, continent_codes) # draw the plot plt.figure() cs = plt.contour(xi, yi, zi, clip_path=continent_path) plt.fill(x[:nafrica], y[:nafrica], fill=False) plt.axes().set_aspect("equal") plt.show()
def main(fs): # use a fixed seed if requested if fs.seed: random.seed(fs.seed) # define the max number of rejection iterations limit = fs.npoints * 100 # validate input if fs.axis < 0: raise ValueError('the mds axis must be nonnegative') # get points defining the boundary of africa nafrica = len(g_africa_poly) africa_edges = [(i, (i + 1) % nafrica) for i in range(nafrica)] # get some points and edges inside africa points = sample_with_rejection(fs.npoints, g_africa_poly, limit) x_list, y_list = zip(*points) tri = Triangulation(x_list, y_list) tri_edges = [(i + nafrica, j + nafrica) for i, j in tri.edge_db.tolist()] # get the whole list of points allpoints = g_africa_poly + points # refine the list of edges tri_edges = list(gen_noncrossing_edges(tri_edges, africa_edges, allpoints)) tri_edges = get_mst(tri_edges, allpoints) alledges = africa_edges + tri_edges # make the graph laplacian A = np.zeros((len(points), len(points))) for ia, ib in tri_edges: xa, ya = allpoints[ia] xb, yb = allpoints[ib] d = math.hypot(xb - xa, yb - ya) A[ia - nafrica, ib - nafrica] = 1 / d A[ib - nafrica, ia - nafrica] = 1 / d L = Euclid.adjacency_to_laplacian(A) ws, vs = EigUtil.eigh(np.linalg.pinv(L)) if fs.axis >= len(ws): raise ValueError('choose a smaller mds axis') v = vs[fs.axis] # get the color and sizes for the points v /= max(np.abs(v)) # draw the picture helper = ImgHelper(allpoints, alledges, fs.total_width, fs.total_height, fs.border) helper.draw_contour_plot(v, nafrica)
def get_response_content(fs): # start writing the response out = StringIO() # define the points; each is a numpy array of length 2 G = [] P = [] for i in range(fs.disc_npoints): P.append(sample_point_on_disc(fs.disc_sigma)) G.append(0) for i in range(fs.ann_npoints): P.append(sample_point_on_annulus(fs.ann_radius, fs.ann_sigma)) G.append(1) # use delaunay triangulation to force planarity x_list, y_list = zip(*[p.tolist() for p in P]) tri = Triangulation(x_list, y_list) edges = set(tuple(sorted(edge)) for edge in tri.edge_db) # define edge distances e_to_d = dict(((i, j), np.linalg.norm(P[j] - P[i])) for i, j in edges) # get the edges joining the disc and annulus groups joining_edges = set((i, j) for i, j in edges if G[i] != G[j]) dae_pairs = [(e_to_d[e], e) for e in joining_edges] sorted_dae_pairs = list(sorted(dae_pairs)) sorted_joining_edges = zip(*sorted_dae_pairs)[1] short_joining_edges = set(sorted_joining_edges[:fs.conn_sparse]) # get edges which are longer than the connection radius overlong_edges = set(e for e in edges if e_to_d[e] > fs.conn_radius) # define the final set of edges edges = (edges - overlong_edges - joining_edges) | short_joining_edges # write some extra info # write the points print >> out, 'POINTS' for i, p in enumerate(P): print >> out, '\t'.join(str(x) for x in [i, p[0], p[1]]) # write the edges print >> out, 'EDGES' for i, j in edges: print >> out, '\t'.join(str(x) for x in [i, j]) # return the response return out.getvalue()
chunks_lit = chunks_sa.value uchunks_lit = chunks_sa.value chunks_attrmap = AttributeMap(mapnumeric=True) chunks = chunks_attrmap.to_numeric(chunks_lit) uchunks = chunks_attrmap.to_numeric(uchunks_lit) from matplotlib.delaunay.triangulate import Triangulation from matplotlib.patches import Polygon # Lets figure out convex halls for each chunk/label pair for target in utargets: t_mask = targets == target for chunk in uchunks: tc_mask = np.logical_and(t_mask, chunk == chunks) tc_samples = dataset.samples[tc_mask] tr = Triangulation(tc_samples[:, 0], tc_samples[:, 1]) poly = pl.fill(tc_samples[tr.hull, 0], tc_samples[tr.hull, 1], closed=True, facecolor=targets_colors[target], #fill=False, alpha=0.01, edgecolor='gray', linestyle='dotted', linewidth=0.5, ) pl.legend(scatterpoints=1) if clf and not estimates_were_enabled: clf.ca.disable('estimates') Pion()
def replace_data(self, dataset): self.x = dataset.x self.y = dataset.y self.tri = Triangulation(self.x, self.y)
def __init__(self, xNode, yNode): super(DelaunayTessellation, self).__init__() self.xNode = xNode self.yNode = yNode self._triangulation = Triangulation(self.xNode, self.yNode) self._mem_table = None
def replace_data(self, dataset): self.x = dataset.x self.y = dataset.y self.tri = Triangulation(self.x, self.y)
def plot_decision_boundary_2d(dataset, clf=None, targets=None, regions=None, maps=None, maps_res=50, vals=[-1, 0, 1], data_callback=None): """Plot a scatter of a classifier's decision boundary and data points Assumes data is 2d (no way to visualize otherwise!!) Parameters ---------- dataset : `Dataset` Data points to visualize (might be the data `clf` was train on, or any novel data). clf : `Classifier`, optional Trained classifier targets : string, optional What samples attributes to use for targets. If None and clf is provided, then `clf.params.targets_attr` is used. regions : string, optional Plot regions (polygons) around groups of samples with the same attribute (and target attribute) values. E.g. chunks. maps : string in {'targets', 'estimates'}, optional Either plot underlying colored maps, such as clf predictions within the spanned regions, or estimates from the classifier (might not work for some). maps_res : int, optional Number of points in each direction to evaluate. Points are between axis limits, which are set automatically by matplotlib. Higher number will yield smoother decision lines but come at the cost of O^2 classifying time/memory. vals : array of floats, optional Where to draw the contour lines if maps='estimates' data_callback : callable, optional Callable object to preprocess the new data points. Classified points of the form samples = data_callback(xysamples). I.e. this can be a function to normalize them, or cache them before they are classified. """ if False: ## from mvpa2.misc.data_generators import * ## from mvpa2.clfs.svm import * ## from mvpa2.clfs.knn import * ## ds = dumb_feature_binary_dataset() dataset = normal_feature_dataset(nfeatures=2, nchunks=5, snr=10, nlabels=4, means=[[0, 1], [1, 0], [1, 1], [0, 0]]) dataset.samples += dataset.sa.chunks[:, None] * 0.1 # slight shifts for chunks ;) #dataset = normal_feature_dataset(nfeatures=2, nlabels=3, means=[ [0,1], [1,0], [1,1] ]) #dataset = normal_feature_dataset(nfeatures=2, nlabels=2, means=[ [0,1], [1,0] ]) #clf = LinearCSVMC(C=-1) clf = kNN(4) #LinearCSVMC(C=-1) clf.train(dataset) #clf = None #plot_decision_boundary_2d(ds, clf) targets = 'targets' regions = 'chunks' #maps = 'estimates' maps = 'targets' #maps = None #'targets' res = 50 vals = [-1, 0, 1] data_callback = None pl.clf() if dataset.nfeatures != 2: raise ValueError('Can only plot a decision boundary in 2D') Pioff() a = pl.gca() # f.add_subplot(1,1,1) attrmap = None if clf: estimates_were_enabled = clf.ca.is_enabled('estimates') clf.ca.enable('estimates') if targets is None: targets = clf.get_space() # Lets reuse classifiers attrmap if it is good enough attrmap = clf._attrmap predictions = clf.predict(dataset) targets_sa_name = targets # bad Yarik -- will rebind targets to actual values targets_lit = dataset.sa[targets_sa_name].value utargets_lit = dataset.sa[targets_sa_name].unique if not (attrmap is not None and len(attrmap) and set(clf._attrmap.keys()).issuperset(utargets_lit)): # create our own attrmap = AttributeMap(mapnumeric=True) targets = attrmap.to_numeric(targets_lit) utargets = attrmap.to_numeric(utargets_lit) vmin = min(utargets) vmax = max(utargets) cmap = pl.cm.RdYlGn # argument # Scatter points if clf: all_hits = predictions == targets_lit else: all_hits = np.ones((len(targets), ), dtype=bool) targets_colors = {} for l in utargets: targets_mask = targets == l s = dataset[targets_mask] targets_colors[l] = c \ = cmap((l-vmin)/float(vmax-vmin)) # We want to plot hits and misses with different symbols hits = all_hits[targets_mask] misses = np.logical_not(hits) scatter_kwargs = dict(c=[c], zorder=10 + (l - vmin)) if sum(hits): a.scatter(s.samples[hits, 0], s.samples[hits, 1], marker='o', label='%s [%d]' % (attrmap.to_literal(l), sum(hits)), **scatter_kwargs) if sum(misses): a.scatter(s.samples[misses, 0], s.samples[misses, 1], marker='x', label='%s [%d] (miss)' % (attrmap.to_literal(l), sum(misses)), edgecolor=[c], **scatter_kwargs) (xmin, xmax) = a.get_xlim() (ymin, ymax) = a.get_ylim() extent = (xmin, xmax, ymin, ymax) # Create grid to evaluate, predict it (x, y) = np.mgrid[xmin:xmax:np.complex(0, maps_res), ymin:ymax:np.complex(0, maps_res)] news = np.vstack((x.ravel(), y.ravel())).T try: news = data_callback(news) except TypeError: # Not a callable object pass imshow_kwargs = dict(origin='lower', zorder=1, aspect='auto', interpolation='bilinear', alpha=0.9, cmap=cmap, vmin=vmin, vmax=vmax, extent=extent) if maps is not None: if clf is None: raise ValueError, \ "Please provide classifier for plotting maps of %s" % maps predictions_new = clf.predict(news) if maps == 'estimates': # Contour and show predictions trained_targets = attrmap.to_numeric(clf.ca.trained_targets) if len(trained_targets) == 2: linestyles = [] for v in vals: if v == 0: linestyles.append('solid') else: linestyles.append('dashed') vmin, vmax = -3, 3 # Gives a nice tonal range ;) map_ = 'estimates' # should actually depend on estimates else: vals = (trained_targets[:-1] + trained_targets[1:]) / 2. linestyles = ['solid'] * len(vals) map_ = 'targets' try: clf.ca.estimates.reshape(x.shape) a.imshow(map_values.T, **imshow_kwargs) CS = a.contour(x, y, map_values, vals, zorder=6, linestyles=linestyles, extent=extent, colors='k') except ValueError as e: print "Sorry - plotting of estimates isn't full supported for %s. " \ "Got exception %s" % (clf, e) elif maps == 'targets': map_values = attrmap.to_numeric(predictions_new).reshape(x.shape) a.imshow(map_values.T, **imshow_kwargs) #CS = a.contour(x, y, map_values, vals, zorder=6, # linestyles=linestyles, extent=extent, colors='k') # Plot regions belonging to the same pair of attribute given # (e.g. chunks) and targets attribute if regions: chunks_sa = dataset.sa[regions] chunks_lit = chunks_sa.value uchunks_lit = chunks_sa.value chunks_attrmap = AttributeMap(mapnumeric=True) chunks = chunks_attrmap.to_numeric(chunks_lit) uchunks = chunks_attrmap.to_numeric(uchunks_lit) from matplotlib.delaunay.triangulate import Triangulation from matplotlib.patches import Polygon # Lets figure out convex halls for each chunk/label pair for target in utargets: t_mask = targets == target for chunk in uchunks: tc_mask = np.logical_and(t_mask, chunk == chunks) tc_samples = dataset.samples[tc_mask] tr = Triangulation(tc_samples[:, 0], tc_samples[:, 1]) poly = pl.fill( tc_samples[tr.hull, 0], tc_samples[tr.hull, 1], closed=True, facecolor=targets_colors[target], #fill=False, alpha=0.01, edgecolor='gray', linestyle='dotted', linewidth=0.5, ) pl.legend(scatterpoints=1) if clf and not estimates_were_enabled: clf.ca.disable('estimates') Pion() pl.axis('tight')
tester = reference_test tester.__name__ = str('test_%s' % func.__name__) return tester nnt = NNTester(npoints=1000) lpt = LinearTester(npoints=1000) for func in allfuncs: globals()['test_%s' % func.__name__] = make_test(func) make_all_2d_testfuncs() # 1d and 0d grid tests ref_interpolator = Triangulation( [0, 10, 10, 0], [0, 0, 10, 10]).linear_interpolator([1, 10, 5, 2.0]) def test_1d_grid(): res = ref_interpolator[3:6:2j, 1:1:1j] assert np.allclose(res, [[1.6], [1.9]], rtol=0) def test_0d_grid(): res = ref_interpolator[3:3:1j, 1:1:1j] assert np.allclose(res, [[1.6]], rtol=0) @image_comparison(baseline_images=['delaunay-1d-interp'], extensions=['png']) def test_1d_plots(): x_range = slice(0.25, 9.75, 20j)
def sutherland(self, wvl): '''Calculates the free-free continuum using the free-free gaunt factor calculations of Sutherland, 1998, MNRAS, 300, 321. the wavelengths (wvl) will be sorted, first thing''' # wvl = np.array(wvl, 'float64') nWvl = wvl.size # factor = 5.44436e-39 try: temperature = self.Temperature except: errorMessage = ' temperature undefined in continuum.sutherland' print(errorMessage) return {'errorMessage':errorMessage} # read in the gaunt factors, if necessary and get interpolator try: gffInterpolator = self.GffInterpolator except: self.Gff = util.gffRead() gff = self.Gff iu=(np.log10(gff['u1d']) + 4.)*10. ig=(np.log10(gff['g21d']) + 4.)*5. gaunt = gff['gff'] #tr=Triangulation(iu.flatten(),ig.flatten()) tr=Triangulation(iu,ig) self.GffInterpolator = tr.nn_interpolator(gaunt.flatten()) gffInterpolator = self.GffInterpolator # gga = np.array((float(self.Z)**2*const.ryd2erg/const.boltzmann)*(1./temperature),'float64') nonValidGg1 = np.log10(gga) < -4. nonValidGg2 = np.log10(gga) > 4. nonValidGg = np.logical_or(nonValidGg1, nonValidGg2) ggOut = np.ma.array(gga, mask = nonValidGg, fill_value=True) iGg = np.ma.array((np.log10(gga) + 4.)*5., mask=nonValidGg, fill_value=0.) # if nonValidGg.sum(): errorMessage = 'no valid temperatures in continuum.sutherland' print(errorMessage) return {'errorMessage':errorMessage} else: #iUu = np.ma.array((np.log10(uu) + 4.)*10., mask=nonValidUu, fill_value=0.) #iGg = (np.log10(gg) + 4.)*5. #print ' iGg.shape = ',iGg, iGg.shape # nWvl = wvl.size nTemp = temperature.size # if (nTemp > 1) and (nWvl > 1): ff = np.ma.zeros((nWvl, nTemp), 'float64') gffOut1 = np.ma.zeros((nWvl, nTemp), 'float64') gffOutMask = np.zeros((nWvl, nTemp), 'Bool') uuOut = np.zeros((nWvl, nTemp), 'float64') for iwvl in range(nWvl): uu = ((const.planck*const.light*1.e+8/const.boltzmann)/(wvl[iwvl]*temperature)) #.flatten() nonValidUu1 = np.log10(uu) < -4. nonValidUu2 = np.log10(uu) > 4. nonValidUu = np.logical_or(nonValidUu1, nonValidUu2) gffOutMask[iwvl] = nonValidUu uuOut[iwvl] = np.ma.array(uu, mask=nonValidUu, fill_value=True) iUu = np.ma.array((np.log10(uu) + 4.)*10., mask=nonValidUu, fill_value=0.) gffOut1[iwvl] = gffInterpolator(iUu, iGg) wvlt = 1./(wvl[iwvl]**2*np.sqrt(temperature)) # was sortedTemperature ff[iwvl] = (np.exp(-uuOut[iwvl])*gffOut1[iwvl]*wvlt) gffOut1.mask = gffOutMask gffOut1.set_fill_value(0.) gffOut = gffOut1.transpose() ff.mask = gffOutMask ff.set_fill_value(0.) return {'suthFf':ff.transpose(), 'suthGff':gffOut} # if (nTemp == 1) and (nWvl > 1): uu = ((const.planck*const.light*1.e+8/const.boltzmann)/(wvl*temperature)) # .flatten() nonValidUu1 = np.log10(uu) < -4. nonValidUu2 = np.log10(uu) > 4. nonValidUu = np.logical_or(nonValidUu1, nonValidUu2) gffOutMask = nonValidUu iUu = (np.log10(uu) + 4.)*10. gffOut1 = gffInterpolator(iUu, iGg.repeat(nWvl)) wvlt = 1./(wvl**2*np.sqrt(temperature)) ff = np.ma.array(np.exp(-uu)*gffOut1*wvlt) ff.mask=gffOutMask ff.set_fill_value(0.) gffOut = np.ma.array(gffOut1, mask=gffOutMask, fill_value=0.) return {'suthFf':ff, 'suthGff':gffOut, 'iUu':iUu, 'gffOut1':gffOut1, 'wvlt':wvlt, 'iGg':iGg.repeat(nWvl), 'gffInterpolator':gffInterpolator} #elif (nTemp > 1) and (nWvl == 1): else: #print ' igg.shape = ',iGg.shape #gffOut1 = np.ma.zeros((nTemp), 'float64') #gffOutMask = np.zeros((nTemp), 'Bool') #uuOut = np.zeros((nTemp), 'float64') # uu = (const.planck*const.light*1.e+8/const.boltzmann) /(wvl*temperature).flatten() nonValidUu1 = np.log10(uu) < -4. nonValidUu2 = np.log10(uu) > 4. nonValidUu = np.logical_or(nonValidUu1, nonValidUu2) gffOutMask = nonValidUu uuOut = np.ma.array(uu, mask=nonValidUu, fill_value=True) #iUu = np.ma.array((np.log10(uu) + 4.)*10., mask=nonValidUu, fill_value=0.) iUu = (np.log10(uu) + 4.)*10. #print ' iUu.shape = ',iUu.shape gffOut1 = gffInterpolator(iUu, iGg.flatten()) # wvlt = 1./(wvl**2*np.sqrt(temperature)) ff1 = np.exp(-uuOut)*gffOut1*wvlt ff = np.ma.array(ff1, mask=gffOutMask, fill_value=0.) gffOut = np.ma.array(gffOut1, mask=gffOutMask, fill_value=0.) return {'suthFf':ff, 'suthGff':gffOut}