def helixmap(): # Construct our own cubehelix color map. from matplotlib._cm import cubehelix ch_data=cubehelix(1.0, 0.5, -1.5, 0.0) ch_data=cm.revcmap(ch_data) helix_map=colors.LinearSegmentedColormap('helix', ch_data, 256) return helix_map
def calculate_em(self, wlen='171', dz=100, model=False): """ Calculate an approximation of the coronal EmissionMeasure using a given TemperatureMap object and a particular AIA channel. Parameters ---------- tmap : CoronaTemps.temperature.TemperatureMap A TemperatureMap instance containing coronal temperature data wlen : {'94' | '131' | '171' | '193' | '211' | '335'} AIA wavelength used to approximate the emission measure. '171', '193' and '211' are most likely to provide reliable results. Use of other channels is not recommended. """ # Load the appropriate temperature response function tresp = read('/imaps/holly/home/ajl7/CoronaTemps/aia_tresp') resp = tresp['resp{}'.format(wlen)] # Get some information from the TemperatureMap and set up filenames, etc tempdata = self.data.copy() tempdata[np.isnan(tempdata)] = 0.0 date = sunpy.time.parse_time(self.date) if not model: data_dir = self.data_dir fits_dir = path.join(data_dir, '{:%Y/%m/%d}/{}'.format(date, wlen)) filename = path.join(fits_dir, '*{0:%Y?%m?%d}?{0:%H?%M}*fits'.format(date)) if wlen == '94': filename = filename.replace('94', '094') # Load and appropriately process AIA data filelist = glob.glob(filename) if filelist == []: print 'AIA data not found :(' return aiamap = Map(filename) aiamap.data /= aiamap.exposure_time aiamap = aiaprep(aiamap) aiamap = aiamap.submap(self.xrange, self.yrange) else: fname = '/imaps/holly/home/ajl7/CoronaTemps/data/synthetic/{}/model.fits'.format(wlen) if wlen == '94': fname = fname.replace('94', '094') aiamap = Map(fname) # Create new Map and put EM values in it emmap = Map(self.data.copy(), self.meta.copy()) indices = np.round((tempdata - 4.0) / 0.05).astype(int) indices[indices < 0] = 0 indices[indices > 100] = 100 #print emmap.shape, indices.shape, tempdata.shape, aiamap.shape, resp.shape emmap.data = np.log10(aiamap.data / resp[indices]) #emmap.data = aiamap.data / resp[indices] emmapcubehelix = _cm.cubehelix(s=2.8, r=-0.7, h=1.4, gamma=1.0) cm.register_cmap(name='emhelix', data=emmapcubehelix) emmap.cmap = cm.get_cmap('emhelix') return emmap
def get_linecolors_from_cubehelix(N, gamma=0.8, hue=3.0, rot=1.8, start=-0.30): """Return N colors from the cubehelix for plots """ rgb_dict = cubehelix(h=hue, r=rot, gamma=gamma, s=start) brightness = np.linspace(0.0, 1.0, num=N, endpoint=False) rgb_list = [(rgb_dict['red'](b), rgb_dict['green'](b), rgb_dict['blue'](b)) for b in brightness] ret = [(_norm(a), _norm(b), _norm(c)) for a, b, c in rgb_list] return ret
from matplotlib.colors import LinearSegmentedColormap def generate_cmap_flame(): clrs = [(1, 1, 1), (0, 0.3, 1), (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):
import sunpy from sunpy.map import Map import numpy as np from matplotlib import cm, _cm, rc, patches rc('savefig', bbox='tight', pad_inches=0.5) import matplotlib.pyplot as plt import sys from os.path import join, expanduser sys.path.append(expanduser('~/CoronaTemps/')) from temperature import TemperatureMap as TMap from astropy import units as u from scipy.interpolate import RegularGridInterpolator as rgi from itertools import product emmapcubehelix = _cm.cubehelix(s=2.8, r=-0.7, h=1.4, gamma=1.0) cm.register_cmap(name='emhelix', data=emmapcubehelix) emcm = cm.get_cmap('emhelix') # Load a temperature map and get the EM data out of it tmap = TMap('2011-02-15', maps_dir=expanduser('~/coronal-backprojection/'), n_params=3) EMmap = Map(10.0**tmap.emission_measure, tmap.meta.copy()) EMlog = Map(tmap.emission_measure, tmap.meta.copy()) print np.nanmin(EMlog.data), np.nanmax(EMlog.data) fig = plt.figure(figsize=(32, 24)) EMlog.plot(cmap=emcm) plt.colorbar() plt.savefig('input-em') plt.close()
import sunpy from sunpy.map import Map import numpy as np from matplotlib import cm, _cm, rc, patches rc('savefig', bbox='tight', pad_inches=0.5) import matplotlib.pyplot as plt import sys from os.path import join, expanduser sys.path.append(expanduser('~/CoronaTemps/')) from temperature import TemperatureMap as TMap from astropy import units as u from scipy.interpolate import RegularGridInterpolator as rgi from itertools import product emmapcubehelix = _cm.cubehelix(s=2.8, r=-0.7, h=1.4, gamma=1.0) cm.register_cmap(name='emhelix', data=emmapcubehelix) emcm = cm.get_cmap('emhelix') # Load a temperature map and get the EM data out of it tmap = TMap('2011-02-15', maps_dir=expanduser('~/coronal-backprojection/'), n_params=3) EMmap = Map(10.0**tmap.emission_measure, tmap.meta.copy()) EMlog = Map(tmap.emission_measure, tmap.meta.copy()) print np.nanmin(EMlog.data), np.nanmax(EMlog.data) fig = plt.figure(figsize=(32, 24)) EMlog.plot(cmap=emcm) plt.colorbar() plt.savefig('input-em') plt.close() # Define ranges of reconstruction space
(0,0.3,1), (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'):
def __init__(self, date=None, n_params=1, data_dir=None, maps_dir=None, fname=None, infofile=None, submap=None, verbose=False, force_temp_scan=False): if (not fname and not date) or (fname and date): print """You must specify either a date and time for which to create temperatures or the name of a file containing a valid TemperatureMap object.""" return if date: date = sunpy.time.parse_time(date) if data_dir is None: data_dir = '/media/huw/SDO_data/' if maps_dir is None: maps_dir='/media/huw/temperature_maps/{}pars/'.format(n_params) fname = path.join(maps_dir, '{:%Y-%m-%dT%H_%M_%S}.fits'.format(date)) if infofile: data_dir = None maps_dir = open(infofile).readline()[:-1] fname = path.join(maps_dir, '{:%Y-%m-%dT%H:%M:%S}.fits'.format(date)) fname.replace('/images/', '/data/') if n_params != 1: fname = fname.replace('.fits', '_full.fits') if fname and not date: data_dir = path.dirname(fname) if verbose: print fname, data_dir try: newmap = Map(fname) GenericMap.__init__(self, newmap.data[..., 0], newmap.meta) self.goodness_of_fit = newmap.data[..., -1] if newmap.data.shape[2] != 2: self.dem_width = newmap.data[..., 1] self.emission_measure = newmap.data[..., 2] except ValueError: cmdargs = ["python", path.join(cortemps, 'create_tempmap.py'), date, n_params, data_dir, infofile, submap, verbose, force_temp_scan] if n_params != 1: cmdargs = ["mpiexec", "-n", 16] + cmdargs cmdargs = [str(cmd) for cmd in cmdargs] status = subp.call(cmdargs) newmap = Map(path.join(cortemps, 'temporary.fits')) subp.call(["rm", path.join(cortemps, 'temporary.fits')]) data, meta = newmap.data, newmap.meta if verbose: print data.shape GenericMap.__init__(self, data[..., 0], meta) if data.shape[2] != 2: data[data == 0] = np.nan self.dem_width = data[..., 1] self.emission_measure = data[..., 2] self.goodness_of_fit = data[..., -1] if verbose: print self.shape print self.goodness_of_fit.shape if n_params != 1: print self.dem_width.shape print self.emission_measure.shape lowx, highx = (self.xrange[0] / self.scale['x'], self.xrange[1] / self.scale['x']) lowy, highy = (self.yrange[0] / self.scale['y'], self.yrange[1] / self.scale['y']) x_grid, y_grid = np.mgrid[lowx:highx-1, lowy:highy-1] r_grid = np.sqrt((x_grid ** 2.0) + (y_grid ** 2.0)) outer_rad = (self.rsun_arcseconds * 1.5) / self.scale['x'] self.data[r_grid > outer_rad] = None self.meta['date-obs'] = str(date) tmapcubehelix = _cm.cubehelix(s=2.8, r=0.7, h=2.0, gamma=1.0) cm.register_cmap(name='temphelix', data=tmapcubehelix) self.cmap = cm.get_cmap('temphelix') self.data_dir = data_dir self.maps_dir = maps_dir self.temperature_scale = 'log' self.region = None self.region_coordinate = {'x': 0.0, 'y': 0.0} if n_params == 3: self.n_params = 3 else: self.n_params = 1 return
After importing, these color maps can be used in exactly the same way as matplotlib's internal color maps. Each new color map is a variant on the cubhelix color map with no rotation in color space, each one passing thorugh a different color. The _l versions have more color variation for smaller values than larger values. Usage: from densityplot import * from pylab import * new_colormap = cm.cubehelix_purple new_colormap_reverse = cm.cubehelix_purple_r """ from matplotlib import _cm as c c.datad['cubehelix_light'] = c.cubehelix(gamma=0.6) c.datad['cubehelix_purple'] = c.cubehelix(gamma=0.6, s=0.5, r=0.0, h=1.0) c.datad['cubehelix_red'] = c.cubehelix(gamma=0.6, s=1.0, r=0.0, h=1.0) c.datad['cubehelix_yellow'] = c.cubehelix(gamma=0.6, s=1.5, r=0.0, h=1.0) c.datad['cubehelix_green'] = c.cubehelix(gamma=0.6, s=2.0, r=0.0, h=1.0) c.datad['cubehelix_teal'] = c.cubehelix(gamma=0.6, s=2.5, r=0.0, h=1.0) c.datad['cubehelix_blue'] = c.cubehelix(gamma=0.6, s=3.0, r=0.0, h=1.0) c.datad['cubehelix_purple_l'] = c.cubehelix(gamma=0.4, s=0.5, r=0.0, h=1.5) c.datad['cubehelix_red_l'] = c.cubehelix(gamma=0.4, s=1.0, r=0.0, h=1.5) c.datad['cubehelix_yellow_l'] = c.cubehelix(gamma=0.4, s=1.5, r=0.0, h=1.5) c.datad['cubehelix_green_l'] = c.cubehelix(gamma=0.4, s=2.0, r=0.0, h=1.5) c.datad['cubehelix_teal_l'] = c.cubehelix(gamma=0.4, s=2.5, r=0.0, h=1.5) c.datad['cubehelix_blue_l'] = c.cubehelix(gamma=0.4, s=3.0, r=0.0, h=1.5)