########################################################
# Started Logging At: 2023-02-24 09:15:55
########################################################
########################################################
# # Started Logging At: 2023-02-24 09:15:55
########################################################
import uvcombine
########################################################
# Started Logging At: 2023-02-24 09:17:39
########################################################
########################################################
# # Started Logging At: 2023-02-24 09:17:39
########################################################
import uvcombine
get_ipython().run_line_magic('pinfo', 'uvcombine.feather_simple')
simplefeather = uvcombine.feather_simple('/orange/adamginsburg/ACES/mosaics/12m_continuum_commonbeam_circular_mosaic.fits',
                                         '/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
import uvcombine
simplefeather = uvcombine.feather_simple('/orange/adamginsburg/ACES/mosaics/12m_continuum_commonbeam_circular_mosaic.fits',
                                         '/orange/adamginsburg/ACES/mosaics/7m_continuum_commonbeam_circular_mosaic.fits')
simplefeather
#[Out]# array([[-9.42226990e-18+7.79694167e-18j, -7.15003224e-18+3.17568444e-18j,
#[Out]#         -2.72404579e-18+7.01357638e-18j, ...,
#[Out]#         -1.09078595e-18+1.07617680e-17j, -4.10212116e-18+9.72975028e-18j,
#[Out]#         -5.88594091e-18+2.92217550e-18j],
#[Out]#        [ 1.64332021e-18+1.21191160e-18j,  4.12883323e-18-3.41377946e-18j,
#[Out]#          8.73277865e-18+5.28836856e-19j, ...,
#[Out]#          9.72693112e-18+4.21321297e-18j,  6.69180595e-18+3.24975487e-18j,
#[Out]#          5.26337708e-18-3.66604311e-18j],
#[Out]#        [-1.65537692e-18+4.79801466e-18j,  7.98292162e-19+2.99230404e-19j,
#[Out]#          5.26573144e-18+4.49694259e-18j, ...,
#[Out]#          6.96544283e-18+7.24423517e-18j,  3.64102722e-18+6.54321434e-18j,
#[Out]#          2.32671330e-18-2.88073105e-19j],
#[Out]#        ...,
#[Out]#        [ 7.99985753e-18+7.82380283e-18j,  1.01450641e-17+3.29816782e-18j,
#[Out]#          1.44399503e-17+6.94286075e-18j, ...,
#[Out]#          1.58057120e-17+1.06543636e-17j,  1.32957759e-17+9.45123374e-18j,
#[Out]#          1.09775596e-17+2.93817307e-18j],
#[Out]#        [-6.56325325e-18+1.64161252e-19j, -4.43859907e-18-4.53222678e-18j,
#[Out]#         -1.26625142e-19-9.52997336e-19j, ...,
#[Out]#          1.50278543e-18+3.49993585e-18j, -1.20784343e-18+2.18123605e-18j,
#[Out]#         -3.37891345e-18-4.59714476e-18j],
#[Out]#        [-4.50001245e-18+5.43325814e-18j, -2.36195793e-18+8.52446908e-19j,
#[Out]#          1.94779680e-18+4.62768952e-18j, ...,
#[Out]#          3.86781785e-18+8.37343913e-18j,  9.56721398e-19+7.25739961e-18j,
#[Out]#         -1.09374771e-18+5.43896753e-19j]])
pl.imshow(simplefeather)
get_ipython().run_line_magic('matplotlib', 'inline')
import pylab as pl
pl.rcParams['image.origin'] = 'lower'
pl.imshow(simplefeather.real)
#[Out]# <matplotlib.image.AxesImage at 0x2b325f5839a0>
get_ipython().run_line_magic('matplotlib', 'inline')
import pylab as pl
pl.rcParams['image.origin'] = 'lower'
from astropy.visualization import simple_norm
pl.imshow(simplefeather.real, norm=simple_norm(simplefeather.real, min_percent=1, max_percent=99, stretch='asinh'))
#[Out]# <matplotlib.image.AxesImage at 0x2b32e6a17940>
pl.imshow(simplefeather.real, norm=simple_norm(simplefeather.real, min_percent=1, max_percent=99.95, stretch='asinh'))
#[Out]# <matplotlib.image.AxesImage at 0x2b336e400070>
pl.figure(figsize=(20,10), dpi=200)
pl.imshow(simplefeather.real, norm=simple_norm(simplefeather.real, min_percent=1, max_percent=99.95, stretch='asinh'))
#[Out]# <matplotlib.image.AxesImage at 0x2b336e4606a0>
pl.figure(figsize=(20,10), dpi=200)
pl.imshow(simplefeather.real,
          norm=simple_norm(simplefeather.real,
                           min_cut=-0.025,
                           max_cut=0.2, stretch='asinh'),
         cmap='gray')
#[Out]# <matplotlib.image.AxesImage at 0x2b336e4c1730>
########################################################
# Started Logging At: 2023-02-24 15:26:25
########################################################
########################################################
# # Started Logging At: 2023-02-24 15:26:26
########################################################
pl.figure(figsize=(20,10), dpi=200)
pl.imshow(simplefeather.real,
          norm=simple_norm(simplefeather.real,
                           min_cut=-0.025,
                           max_cut=0.2, stretch='asinh'),
         cmap='gray_r')
#[Out]# <matplotlib.image.AxesImage at 0x2b336e527730>
get_ipython().run_line_magic('pwd', '')
#[Out]# '/orange/adamginsburg/cmz/DataSetVisualizations'
get_ipython().run_line_magic('matplotlib', 'inline')
import pylab as pl
import numpy as np
import os
from astropy.utils.data import download_file
from astropy.io import fits
from spectral_cube import SpectralCube
from astropy.visualization import simple_norm
import shutil
import reproject
from reproject import reproject_from_healpix, reproject_to_healpix

from astropy.wcs import WCS
import matplotlib.pyplot as plt
from astropy.visualization.wcsaxes.frame import EllipticalFrame

from matplotlib.colors import rgb_to_hsv, hsv_to_rgb 

from astropy.convolution import convolve_fft, Gaussian2DKernel, Gaussian1DKernel
import healpy
def h_rot(rgb, rot):
    hsv = rgb_to_hsv(rgb)
    hsv[:,:,0] += rot  # 0.25 = 90/360
    hsv[:,:,0] = hsv[:,:,0] % 1 
    rgb_scaled = hsv_to_rgb(hsv)
    return rgb_scaled

def make_rgb(rgb, basename, hsv_rotation=0, layernames='RGB',
             do_layers=True,
             axlims=None, frame_class=EllipticalFrame):
    plt.figure(figsize=(10,5), dpi=200)
    ax = plt.subplot(1,1,1, projection=WCS(target_header),
                     frame_class=frame_class)
    #ax.coords.grid(color='white')
    ax.coords['glat'].set_ticklabel(visible=False)
    ax.coords['glon'].set_ticklabel(visible=False)
    ax.coords['glat'].set_ticks_visible(False)
    ax.coords['glon'].set_ticks_visible(False)
    if do_layers:
        for ind, color in zip((0, 1, 2), (layernames)):
            rgbc = np.zeros_like(rgb)
            rgbc[:, :, ind] = rgb[:, :, ind]
            if hsv_rotation != 0:
                rgbc = h_rot(rgbc, hsv_rotation)
            ax.imshow(rgbc)
            pl.savefig(f'{basename}_{color}.png', bbox_inches='tight', transparent=True)
    if hsv_rotation != 0:
        rgb = h_rot(rgb, hsv_rotation)
    ax.imshow(rgb)
    if axlims is not None:
        ax.axis(axlims)
    pl.savefig(f'{basename}_RGB.png', bbox_inches='tight', transparent=True)
    return ax
target_header_medres = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                  960
NAXIS2  =                  480
CTYPE1  = 'GLON-MOL'
CRPIX1  =                480.5
CRVAL1  =                  0.0
CDELT1  =              -0.3375
CUNIT1  = 'deg     '
CTYPE2  = 'GLAT-MOL'
CRPIX2  =                240.5
CRVAL2  =                  0.0
CDELT2  =               0.3375
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
target_header = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 1920
NAXIS2  =                  960
CTYPE1  = 'GLON-MOL'
CRPIX1  =                960.5
CRVAL1  =                  0.0
CDELT1  =             -0.16875
CUNIT1  = 'deg     '
CTYPE2  = 'GLAT-MOL'
CRPIX2  =                480.5
CRVAL2  =                  0.0
CDELT2  =              0.16875
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
def fix_nans(img):
    kernel = Gaussian2DKernel(2)
    sm = convolve_fft(img, kernel)
    img[np.isnan(img)] = sm[np.isnan(img)]
    return img

def fix_rosat_nans(tb):
    #kernel = Gaussian1DKernel(3)
    kernel = Gaussian2DKernel(1) # convolving in 2D convolves adjacent scans
    # tb is a 2D array, but we want to convolve in 1D
    #sm = convolve_fft(tb, kernel.array[None, :])
    sm = convolve_fft(tb, kernel)
    tb[np.isnan(tb)] = sm[np.isnan(tb)]
    return tb
get_ipython().run_line_magic('pwd', '')
#[Out]# '/orange/adamginsburg/cmz/DataSetVisualizations'
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
if os.path.exists('meerkat_projectedto_aces.fits'):
    img_meerkat_ACES = fits.getdata('meerkat_projectedto_aces.fits')
else:
    img_meerkat_ACES,_ = reproject.reproject_interp((meerkat[0].data.squeeze(), WCS(meerkat[0].header).celestial),
                                                  aces12mwcs.celestial, shape_out=aces12m[0].data.shape)
    fits.PrimaryHDU(data=img_meerkat_ACES, header=aces12m[0].header).writeto('meerkat_projectedto_aces.fits')
if os.path.exists('glimpsei4_projectedto_aces.fits'):
    img_glimpsei4_ACES = fits.getdata('glimpsei4_projectedto_aces.fits')
else:
    img_glimpsei4_ACES,_ = reproject.reproject_interp(glimpsei4, aces12mwcs.celestial, shape_out=aces12m[0].data.shape)
    fits.PrimaryHDU(data=img_glimpsei4_ACES, header=aces12m[0].header).writeto('glimpsei4_projectedto_aces.fits')
fn_meerkat = 'MeerKAT_Galactic_Centre_1284MHz-StokesI.fits'
if not os.path.exists(fn_meerkat):
    meerkat = download_file(f"https://archive-gw-1.kat.ac.za/public/repository/10.48479/fyst-hj47/data/{fn_meerkat}")
    shutil.move(meerkat, fn_meerkat)
meerkat = fits.open(fn_meerkat)
glimpsei4 = fits.open('/orange/adamginsburg/cmz/glimpse_data/GLM_00000+0000_mosaic_I4.fits')
fn_meerkat = 'MeerKAT_Galactic_Centre_1284MHz-StokesI.fits'
if not os.path.exists(fn_meerkat):
    meerkat = download_file(f"https://archive-gw-1.kat.ac.za/public/repository/10.48479/fyst-hj47/data/{fn_meerkat}")
    shutil.move(meerkat, fn_meerkat)
meerkat = fits.open(fn_meerkat)
glimpsei4 = fits.open('/orange/adamginsburg/cmz/glimpse_data/GLM_00000+0000_mosaic_I4.fits')
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(meerkat[0].data.squeeze(),
          norm=simple_norm(meerkat[0].data, min_percent=0.1, max_percent=99.9, stretch='log'),
          transform=ax.get_transform(WCS(meerkat[0].header).celestial),
          cmap='gray')
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
if os.path.exists('meerkat_projectedto_aces.fits'):
    img_meerkat_ACES = fits.getdata('meerkat_projectedto_aces.fits')
else:
    img_meerkat_ACES,_ = reproject.reproject_interp((meerkat[0].data.squeeze(), WCS(meerkat[0].header).celestial),
                                                  aces12mwcs.celestial, shape_out=aces12m[0].data.shape)
    fits.PrimaryHDU(data=img_meerkat_ACES, header=aces12m[0].header).writeto('meerkat_projectedto_aces.fits')
if os.path.exists('glimpsei4_projectedto_aces.fits'):
    img_glimpsei4_ACES = fits.getdata('glimpsei4_projectedto_aces.fits')
else:
    img_glimpsei4_ACES,_ = reproject.reproject_interp(glimpsei4, aces12mwcs.celestial, shape_out=aces12m[0].data.shape)
    fits.PrimaryHDU(data=img_glimpsei4_ACES, header=aces12m[0].header).writeto('glimpsei4_projectedto_aces.fits')
fn7m = '/orange/adamginsburg/ACES/mosaics/7m_continuum_commonbeam_circular_mosaic.fits'
pl.figure(figsize=(20,10), dpi=200)
pl.imshow(fits.getdata(fn7m),
          norm=simple_norm(fits.getdata(fn7m),
                           min_cut=-0.025,
                           max_cut=0.2, stretch='asinh'),
         cmap='gray_r')
import uvcombine
from astropy.io import fits
pl.figure(figsize=(20,10), dpi=200)
pl.imshow(fits.getdata(fn7m),
          norm=simple_norm(fits.getdata(fn7m),
                           min_cut=-0.025,
                           max_cut=0.2, stretch='asinh'),
         cmap='gray_r')
#[Out]# <matplotlib.image.AxesImage at 0x2b336e5ac160>
simplefeather_retry = uvcombine.feather_simple('/orange/adamginsburg/ACES/mosaics/12m_continuum_commonbeam_circular_mosaic.fits',
                                               '/orange/adamginsburg/ACES/mosaics/7m_continuum_commonbeam_circular_mosaic.fits',
                                               highresscalefactor=1000,
                                              )
rgb = np.array([simple_norm(img_meerkat_ACES,   min_percent=25, max_percent=99.99, log_a=4e1, stretch='linear')(np.nan_to_num(img_meerkat_ACES)),
                simple_norm(aces12m[0].data.squeeze(),   min_percent=5, max_percent=99.99, log_a=4e1, stretch='asinh')(np.nan_to_num(aces12m[0].data.squeeze())),
                simple_norm(img_glimpse_ACES, min_percent=1, max_percent=99.99, log_a=4e1, stretch='log')(np.nan_to_num(img_glimpse_ACES))]).T.swapaxes(0,1)
pl.imshow(rgb)
rgb = np.array([simple_norm(img_meerkat_ACES,   min_percent=25, max_percent=99.99, log_a=4e1, stretch='linear')(np.nan_to_num(img_meerkat_ACES)),
                simple_norm(aces12m[0].data.squeeze(),   min_percent=5, max_percent=99.99, log_a=4e1, stretch='asinh')(np.nan_to_num(aces12m[0].data.squeeze())),
                simple_norm(img_glimpsei4_ACES, min_percent=1, max_percent=99.99, log_a=4e1, stretch='log')(np.nan_to_num(img_glimpsei4_ACES))]).T.swapaxes(0,1)
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b408cc78070>
rgb = np.array([simple_norm(img_meerkat_ACES,   min_percent=1, max_percent=99.99, log_a=2e1, stretch='log')(np.nan_to_num(img_meerkat_ACES)),
                simple_norm(aces12m[0].data.squeeze(),   min_percent=1, max_percent=99.99, log_a=2e1, stretch='log')(np.nan_to_num(aces12m[0].data.squeeze())),
                simple_norm(img_glimpsei4_ACES, min_percent=1, max_percent=99.99, log_a=2e1, stretch='log')(np.nan_to_num(img_glimpsei4_ACES))]).T.swapaxes(0,1)
pl.imshow(rgb, origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b408d36b280>
pl.figure(figsize=(20,10), dpi=200)
pl.imshow(simplefeather_retry.real,
          norm=simple_norm(simplefeather_retry.real,
                           min_cut=-0.025,
                           max_cut=0.2, stretch='asinh'),
         cmap='gray_r')
#[Out]# <matplotlib.image.AxesImage at 0x2b336e618400>
rgb = np.array([simple_norm(img_meerkat_ACES,   min_percent=1, max_percent=99.99, log_a=2e1, stretch='log')(np.nan_to_num(img_meerkat_ACES)),
                simple_norm(aces12m[0].data.squeeze(),   min_percent=1, max_percent=99.99, log_a=4e1, stretch='log')(np.nan_to_num(aces12m[0].data.squeeze())),
                simple_norm(img_glimpsei4_ACES, min_percent=1, max_percent=99.99, log_a=2e1, stretch='log')(np.nan_to_num(img_glimpsei4_ACES))]).T.swapaxes(0,1)
pl.imshow(rgb[4000:6000,12000:14000,:], origin='lower')
simplefeather_retry = uvcombine.feather_simple('/orange/adamginsburg/ACES/mosaics/12m_continuum_commonbeam_circular_mosaic.fits',
                                               '/orange/adamginsburg/ACES/mosaics/7m_continuum_commonbeam_circular_mosaic.fits',
                                               highresscalefactor=10,
                                              )
#[Out]# <matplotlib.image.AxesImage at 0x2b408d3cfd30>
rgb = np.array([simple_norm(img_meerkat_ACES,   min_percent=1, max_percent=99.99, log_a=3e1, stretch='log')(np.nan_to_num(img_meerkat_ACES)),
                simple_norm(aces12m[0].data.squeeze(),   min_percent=1, max_percent=99.99, log_a=5e1, stretch='log')(np.nan_to_num(aces12m[0].data.squeeze())),
                simple_norm(img_glimpsei4_ACES, min_percent=1, max_percent=99.99, log_a=3e1, stretch='log')(np.nan_to_num(img_glimpsei4_ACES))]).T.swapaxes(0,1)
pl.imshow(rgb[4000:6000,12000:14000,:], origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b408d43cf40>
rgb = np.array([simple_norm(img_meerkat_ACES,   min_percent=1, max_percent=99.99, log_a=4e1, stretch='log')(np.nan_to_num(img_meerkat_ACES)),
                simple_norm(aces12m[0].data.squeeze(),   min_percent=1, max_percent=99.99, log_a=6e1, stretch='log')(np.nan_to_num(aces12m[0].data.squeeze())),
                simple_norm(img_glimpsei4_ACES, min_percent=1, max_percent=99.99, log_a=4e1, stretch='log')(np.nan_to_num(img_glimpsei4_ACES))]).T.swapaxes(0,1)
pl.imshow(rgb[4000:6000,12000:14000,:], origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b408d4b4220>
pl.imshow(rgb, origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b408d5186a0>
rgb = np.array([simple_norm(img_meerkat_ACES,   min_percent=1, max_percent=99.95, log_a=4e1, stretch='log')(np.nan_to_num(img_meerkat_ACES)),
                simple_norm(aces12m[0].data.squeeze(),   min_percent=1, max_percent=99.9, log_a=6e1, stretch='log')(np.nan_to_num(aces12m[0].data.squeeze())),
                simple_norm(img_glimpsei4_ACES, min_percent=1, max_percent=99.9, log_a=4e1, stretch='log')(np.nan_to_num(img_glimpsei4_ACES))]).T.swapaxes(0,1)
pl.imshow(rgb[4000:6000,12000:14000,:], origin='lower')
pl.figure(figsize=(20,10), dpi=200)
pl.imshow(simplefeather_retry.real,
          norm=simple_norm(simplefeather_retry.real,
                           min_cut=-0.025,
                           max_cut=0.2, stretch='asinh'),
         cmap='gray_r')
#[Out]# <matplotlib.image.AxesImage at 0x2b336e67c550>
#[Out]# <matplotlib.image.AxesImage at 0x2b408d5804f0>
pl.imshow(rgb, origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b408d5e5970>
rgb = np.array([simple_norm(img_meerkat_ACES,   min_percent=1, max_percent=99.95, log_a=4e1, stretch='log')(np.nan_to_num(img_meerkat_ACES)),
                simple_norm(aces12m[0].data.squeeze(),   min_percent=1, max_percent=99.95, log_a=6e1, stretch='log')(np.nan_to_num(aces12m[0].data.squeeze())),
                simple_norm(img_glimpsei4_ACES, min_percent=1, max_percent=99.9, log_a=4e1, stretch='log')(np.nan_to_num(img_glimpsei4_ACES))]).T.swapaxes(0,1)
pl.imshow(rgb[4000:6000,12000:14000,:], origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b408d64b7c0>
pl.imshow(rgb, origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b408d6b3c70>
orange_transparent
from matplotlib.colors import ListedColormap
cmap = pl.cm.gray
gray_transparent = cmap(np.arange(cmap.N))
gray_transparent[:,-1] = np.linspace(0, 1, cmap.N)
gray_transparent = ListedColormap(gray_transparent)
cmap = pl.cm.Oranges
orange_transparent = cmap(np.arange(cmap.N))
orange_transparent[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent = ListedColormap(orange_transparent)

cmap = pl.cm.Oranges_r
orange_transparent_r = cmap(np.arange(cmap.N))
orange_transparent_r[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent_r = ListedColormap(orange_transparent_r)

orange_transparent2 = cmap(np.arange(cmap.N))
orange_transparent2[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent2 = ListedColormap(orange_transparent2)
orange_transparent
#[Out]# <matplotlib.colors.ListedColormap at 0x2b408d6ea520>
orange_transparent(180)
#[Out]# (0.8841983852364476,
#[Out]#  0.32802768166089974,
#[Out]#  0.028835063437139624,
#[Out]#  0.7058823529411764)
from matplotlib.colors import ListedColormap
cmap = pl.cm.gray
gray_transparent = cmap(np.arange(cmap.N))
gray_transparent[:,-1] = np.linspace(0, 1, cmap.N)
gray_transparent = ListedColormap(gray_transparent)
cmap = pl.cm.Oranges
orange_transparent = cmap(np.arange(cmap.N))
orange_transparent[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent = ListedColormap(orange_transparent)

cmap = pl.cm.Oranges_r
orange_transparent_r = cmap(np.arange(cmap.N))
orange_transparent_r[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent_r = ListedColormap(orange_transparent_r)

orange_transparent2 = cmap(np.arange(cmap.N))
orange_transparent2[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent2[:,:-1] = [0.88, 0.32, 0.03]
orange_transparent2 = ListedColormap(orange_transparent2)
orange_transparent2
#[Out]# <matplotlib.colors.ListedColormap at 0x2b408e4d1160>
from matplotlib.colors import ListedColormap
cmap = pl.cm.gray
gray_transparent = cmap(np.arange(cmap.N))
gray_transparent[:,-1] = np.linspace(0, 1, cmap.N)
gray_transparent = ListedColormap(gray_transparent)
cmap = pl.cm.Oranges
orange_transparent = cmap(np.arange(cmap.N))
orange_transparent[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent = ListedColormap(orange_transparent)

cmap = pl.cm.Oranges_r
orange_transparent_r = cmap(np.arange(cmap.N))
orange_transparent_r[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent_r = ListedColormap(orange_transparent_r)

orange_transparent2 = cmap(np.arange(cmap.N))
orange_transparent2[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent2[:,:-1] = [0.98, 0.42, 0.03]
orange_transparent2 = ListedColormap(orange_transparent2)
orange_transparent2
#[Out]# <matplotlib.colors.ListedColormap at 0x2b408e4d1f40>
from matplotlib.colors import ListedColormap
cmap = pl.cm.gray
gray_transparent = cmap(np.arange(cmap.N))
gray_transparent[:,-1] = np.linspace(0, 1, cmap.N)
gray_transparent = ListedColormap(gray_transparent)
cmap = pl.cm.Oranges
orange_transparent = cmap(np.arange(cmap.N))
orange_transparent[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent = ListedColormap(orange_transparent)

cmap = pl.cm.Oranges_r
orange_transparent_r = cmap(np.arange(cmap.N))
orange_transparent_r[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent_r = ListedColormap(orange_transparent_r)

orange_transparent2 = cmap(np.arange(cmap.N))
orange_transparent2[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent2[:,:-1] = [0.98, 0.32, 0.03]
orange_transparent2 = ListedColormap(orange_transparent2)
from matplotlib.colors import ListedColormap
cmap = pl.cm.gray
gray_transparent = cmap(np.arange(cmap.N))
gray_transparent[:,-1] = np.linspace(0, 1, cmap.N)
gray_transparent = ListedColormap(gray_transparent)
cmap = pl.cm.Oranges
orange_transparent = cmap(np.arange(cmap.N))
orange_transparent[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent = ListedColormap(orange_transparent)

cmap = pl.cm.Oranges_r
orange_transparent_r = cmap(np.arange(cmap.N))
orange_transparent_r[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent_r = ListedColormap(orange_transparent_r)

orange_transparent2 = cmap(np.arange(cmap.N))
orange_transparent2[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent2[:,:-1] = [0.98, 0.32, 0.03]
orange_transparent2 = ListedColormap(orange_transparent2)
orange_transparent2
#[Out]# <matplotlib.colors.ListedColormap at 0x2b408e4d13a0>
from matplotlib.colors import ListedColormap
cmap = pl.cm.gray
gray_transparent = cmap(np.arange(cmap.N))
gray_transparent[:,-1] = np.linspace(0, 1, cmap.N)
gray_transparent = ListedColormap(gray_transparent)
cmap = pl.cm.Oranges
orange_transparent = cmap(np.arange(cmap.N))
orange_transparent[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent = ListedColormap(orange_transparent)

cmap = pl.cm.Oranges_r
orange_transparent_r = cmap(np.arange(cmap.N))
orange_transparent_r[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent_r = ListedColormap(orange_transparent_r)

orange_transparent2 = cmap(np.arange(cmap.N))
orange_transparent2[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent2[:,:-1] = [0.98, 0.35, 0.03]
orange_transparent2 = ListedColormap(orange_transparent2)
orange_transparent2
#[Out]# <matplotlib.colors.ListedColormap at 0x2b408e4d10d0>
from matplotlib.colors import ListedColormap
cmap = pl.cm.gray
gray_transparent = cmap(np.arange(cmap.N))
gray_transparent[:,-1] = np.linspace(0, 1, cmap.N)
gray_transparent = ListedColormap(gray_transparent)
cmap = pl.cm.Oranges
orange_transparent = cmap(np.arange(cmap.N))
orange_transparent[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent = ListedColormap(orange_transparent)

cmap = pl.cm.Oranges_r
orange_transparent_r = cmap(np.arange(cmap.N))
orange_transparent_r[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent_r = ListedColormap(orange_transparent_r)

orange_transparent2 = cmap(np.arange(cmap.N))
orange_transparent2[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent2[:,:-1] = [0.95, 0.35, 0.03]
orange_transparent2 = ListedColormap(orange_transparent2)
orange_transparent2
#[Out]# <matplotlib.colors.ListedColormap at 0x2b408e4d1040>
rgb = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
ww = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

fig = plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=ww)
ax.imshow(rgb)
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

aces7m = fits.open('/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
aces7mwcs = WCS(aces7m[0].header)
aces7mrepr,_ = reproject.reproject_interp(aces7m, ww, shape_out=rgb.shape[:2])
aces7mrepr[aces7mrepr < 0] = np.nan
ax.imshow(aces7mrepr, 
          norm=simple_norm(aces7mrepr, stretch='log', max_percent=99.96, min_percent=1),
          cmap=orange_transparent2)

pl.savefig("gc_fullres_6_small_withACES7m.png", bbox_inches='tight', pad_inches=0)
import PIL
import pyavm
rgb = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
ww = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

fig = plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=ww)
ax.imshow(rgb)
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

aces7m = fits.open('/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
aces7mwcs = WCS(aces7m[0].header)
aces7mrepr,_ = reproject.reproject_interp(aces7m, ww, shape_out=rgb.shape[:2])
aces7mrepr[aces7mrepr < 0] = np.nan
ax.imshow(aces7mrepr, 
          norm=simple_norm(aces7mrepr, stretch='log', max_percent=99.96, min_percent=1),
          cmap=orange_transparent2)

pl.savefig("gc_fullres_6_small_withACES7m.png", bbox_inches='tight', pad_inches=0)
rgb = np.array([simple_norm(img_meerkat_ACES,   min_percent=1, max_percent=99.95, log_a=4e1, stretch='log')(np.nan_to_num(img_meerkat_ACES)),
                simple_norm(aces12m[0].data.squeeze(),   min_percent=1, max_percent=99.95, log_a=5e1, stretch='log')(np.nan_to_num(aces12m[0].data.squeeze())),
                simple_norm(img_glimpsei4_ACES, min_percent=1, max_percent=99.9, log_a=4e1, stretch='log')(np.nan_to_num(img_glimpsei4_ACES))]).T.swapaxes(0,1)
pl.imshow(rgb[4000:6000,12000:14000,:], origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b408e72b4c0>
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=aces12mwcs)

ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )

ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=15*u.arcsec)
sgrb2b = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=15*u.arcsec)

psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)

pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')
point_sgrb2m.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=aces12mwcs)

ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )

ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=15*u.arcsec)
sgrb2b = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=15*u.arcsec)

psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)

pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')
point_sgrb2m.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=aces12mwcs)

ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )

ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=15*u.arcsec)
sgrb2b = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=15*u.arcsec)

psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)

pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')
point_sgrb2m.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')
import regions
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=aces12mwcs)

ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )

ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=15*u.arcsec)
sgrb2b = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=15*u.arcsec)

psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)

pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')
point_sgrb2m.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')
import regions
from astropy import coordinates
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=aces12mwcs)

ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )

ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=15*u.arcsec)
sgrb2b = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=15*u.arcsec)

psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)

pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')
point_sgrb2m.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=15*u.arcsec)
sgrb2b = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=15*u.arcsec)

psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)

ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )

pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')
point_sgrb2m.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=15*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=15*u.arcsec)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )

psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')
point_sgrb2m.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes
import regions
from astropy import coordinates
from astropy import units as u, constants
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=15*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=15*u.arcsec)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)
psgrb2m.bounding_box

axins = zoomed_inset_axes(ax, 5, loc='upper left', bbox_to_anchor=[-0.1, 0], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')
point_sgrb2m.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=15*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=15*u.arcsec)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m = msgrb2m

axins = zoomed_inset_axes(ax, 5, loc='upper left', bbox_to_anchor=[-0.1, 0], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2m]))
axins.imshow(aces12m[0].data[slcs_sgrb2m],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray'
            )
point_sgrb2m = psgrb2m.plot(ax=axins)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')
point_sgrb2m.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=15*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=15*u.arcsec)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data)

axins = zoomed_inset_axes(ax, 5, loc='upper left', bbox_to_anchor=[-0.1, 0], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2m]))
axins.imshow(aces12m[0].data[slcs_sgrb2m],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray'
            )
point_sgrb2m = psgrb2m.plot(ax=axins)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')
point_sgrb2m.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=15*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=15*u.arcsec)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

axins = zoomed_inset_axes(ax, 5, loc='upper left', bbox_to_anchor=[-0.1, 0], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2m]))
axins.imshow(aces12m[0].data[slcs_sgrb2m],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray'
            )
point_sgrb2m_in = psgrb2m.plot(ax=axins)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')
point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins = zoomed_inset_axes(ax, 5, loc='upper left', bbox_to_anchor=[-0.1, 0], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray'
            )
point_sgrb2n_in = psgrb2n.plot(ax=axins)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')

point_sgrb2m.set_visible(True)
point_sgrb2m_in.set_visible(True)
pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

axins = zoomed_inset_axes(ax, 5, loc='upper left', bbox_to_anchor=[0, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2m]))
axins.imshow(aces12m[0].data[slcs_sgrb2m],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
point_sgrb2m_in = psgrb2m.plot(ax=axins)
axins.coords['glat'].set_ticklabel(visible=False)
axins.coords['glon'].set_ticklabel(visible=False)
axins.coords['glat'].set_ticks_visible(False)
axins.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 5, loc='upper left', bbox_to_anchor=[0, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
point_sgrb2n_in = psgrb2n.plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')

point_sgrb2m.set_visible(True)
point_sgrb2m_in.set_visible(True)
pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

axins = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=[0, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2m]))
axins.imshow(aces12m[0].data[slcs_sgrb2m],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
point_sgrb2m_in = psgrb2m.plot(ax=axins)
axins.coords['glat'].set_ticklabel(visible=False)
axins.coords['glon'].set_ticklabel(visible=False)
axins.coords['glat'].set_ticks_visible(False)
axins.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=[0, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
point_sgrb2n_in = psgrb2n.plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=[0, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_merge]))
axins3.imshow(aces12m[0].data[slcs_merge],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
point_sgrb2n_in = psgrb2n.plot(ax=axins3)
point_sgrb2m_in = psgrb2m.plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
psgrb2m.visual['edgecolor'] = 'r'
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2m]))
axins1.imshow(aces12m[0].data[slcs_sgrb2m],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark1 = mark_inset(ax, axins11, loc=(1,3))
point_sgrb2m_in = psgrb2m.plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
mark1.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark2 = mark_inset(ax, axins2, loc=(1,3))
point_sgrb2n_in = psgrb2n.plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
mark2.set_visible(False)
axins2.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_merge]))
axins3.imshow(aces12m[0].data[slcs_merge],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
point_sgrb2n_in = psgrb2n.plot(ax=axins3)
point_sgrb2m_in = psgrb2m.plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight')
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2m]))
axins1.imshow(aces12m[0].data[slcs_sgrb2m],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark1 = mark_inset(ax, axins11, loc=(1,3))
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
mark1.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark2 = mark_inset(ax, axins2, loc=(1,3))
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
mark2.set_visible(False)
axins2.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_merge]))
axins3.imshow(aces12m[0].data[slcs_merge],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2m]))
axins1.imshow(aces12m[0].data[slcs_sgrb2m],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark1 = mark_inset(ax, axins1, loc=(1,3))
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
mark1.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark2 = mark_inset(ax, axins2, loc=(1,3))
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
mark2.set_visible(False)
axins2.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_merge]))
axins3.imshow(aces12m[0].data[slcs_merge],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2m]))
axins1.imshow(aces12m[0].data[slcs_sgrb2m],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3)
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
mark1.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3)
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
mark2.set_visible(False)
axins2.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_merge]))
axins3.imshow(aces12m[0].data[slcs_merge],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3)
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight')
import os
from astropy.utils.data import download_file
from astropy.io import fits
from spectral_cube import SpectralCube
from astropy.visualization import simple_norm
import shutil
import reproject
from reproject import reproject_from_healpix, reproject_to_healpix

from astropy.wcs import WCS
import matplotlib.pyplot as plt
from astropy.visualization.wcsaxes.frame import EllipticalFrame
import astropy.visualization.wcsaxes

from matplotlib.colors import rgb_to_hsv, hsv_to_rgb 

from astropy import coordinates
from astropy.coordinates import SkyCoord
from astropy import units as u, constants
from astropy.convolution import convolve_fft, Gaussian2DKernel, Gaussian1DKernel
import healpy
import PIL
import pyavm
import regions
def h_rot(rgb, rot):
    hsv = rgb_to_hsv(rgb)
    hsv[:,:,0] += rot  # 0.25 = 90/360
    hsv[:,:,0] = hsv[:,:,0] % 1 
    rgb_scaled = hsv_to_rgb(hsv)
    return rgb_scaled

def make_rgb(rgb, basename, hsv_rotation=0, layernames='RGB',
             do_layers=True,
             axlims=None, frame_class=EllipticalFrame):
    plt.figure(figsize=(10,5), dpi=200)
    ax = plt.subplot(1,1,1, projection=WCS(target_header),
                     frame_class=frame_class)
    #ax.coords.grid(color='white')
    ax.coords['glat'].set_ticklabel(visible=False)
    ax.coords['glon'].set_ticklabel(visible=False)
    ax.coords['glat'].set_ticks_visible(False)
    ax.coords['glon'].set_ticks_visible(False)
    if do_layers:
        for ind, color in zip((0, 1, 2), (layernames)):
            rgbc = np.zeros_like(rgb)
            rgbc[:, :, ind] = rgb[:, :, ind]
            if hsv_rotation != 0:
                rgbc = h_rot(rgbc, hsv_rotation)
            ax.imshow(rgbc)
            pl.savefig(f'{basename}_{color}.png', bbox_inches='tight', transparent=True)
    if hsv_rotation != 0:
        rgb = h_rot(rgb, hsv_rotation)
    ax.imshow(rgb)
    if axlims is not None:
        ax.axis(axlims)
    pl.savefig(f'{basename}_RGB.png', bbox_inches='tight', transparent=True)
    return ax
target_header_medres = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                  960
NAXIS2  =                  480
CTYPE1  = 'GLON-MOL'
CRPIX1  =                480.5
CRVAL1  =                  0.0
CDELT1  =              -0.3375
CUNIT1  = 'deg     '
CTYPE2  = 'GLAT-MOL'
CRPIX2  =                240.5
CRVAL2  =                  0.0
CDELT2  =               0.3375
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
target_header = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 1920
NAXIS2  =                  960
CTYPE1  = 'GLON-MOL'
CRPIX1  =                960.5
CRVAL1  =                  0.0
CDELT1  =             -0.16875
CUNIT1  = 'deg     '
CTYPE2  = 'GLAT-MOL'
CRPIX2  =                480.5
CRVAL2  =                  0.0
CDELT2  =              0.16875
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
def fix_nans(img):
    kernel = Gaussian2DKernel(2)
    sm = convolve_fft(img, kernel)
    img[np.isnan(img)] = sm[np.isnan(img)]
    return img

def fix_rosat_nans(tb):
    #kernel = Gaussian1DKernel(3)
    kernel = Gaussian2DKernel(1) # convolving in 2D convolves adjacent scans
    # tb is a 2D array, but we want to convolve in 1D
    #sm = convolve_fft(tb, kernel.array[None, :])
    sm = convolve_fft(tb, kernel)
    tb[np.isnan(tb)] = sm[np.isnan(tb)]
    return tb
get_ipython().run_line_magic('pwd', '')
#[Out]# '/orange/adamginsburg/cmz/DataSetVisualizations'
fn_rosat5 = "RASS_SXRB_R5.fits"
if not os.path.exists(fn_rosat5):
    rosat5 = download_file(f"https://www.jb.man.ac.uk/research/cosmos/rosat/{fn_rosat5}")
    shutil.move(rosat5, fn_rosat5)
rosat5 = fits.open(fn_rosat5)
data_rosat5 = rosat5[1].data['COUNT_RATE']
data_rosat5 = fix_rosat_nans(np.where(data_rosat5==0, np.nan, data_rosat5))
pl.hist(data_rosat5.ravel(), bins=np.logspace(-14, 5), log=True)
pl.loglog();
#img_rosat5, footprint = reproject_from_healpix(fn_rosat5, target_header)
data_rosat5 = rosat5[1].data['COUNT_RATE']
data_rosat5 = fix_rosat_nans(np.where(data_rosat5<=1e-8, np.nan, data_rosat5))
img_rosat5, footprint = reproject_from_healpix((data_rosat5.ravel(),
                                                rosat5[1].header["COORDSYS"]),
                                               target_header,
                                               nested=rosat5[1].header["ORDERING"].lower() == "nested"
                                              )
img_rosat5 = fix_nans(np.where(img_rosat5<=1e-9, np.nan, img_rosat5))
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame,
                )
ax.imshow(img_rosat5, norm=simple_norm(img_rosat5, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_halpha = "Halpha_map.fits"
if not os.path.exists(fn_halpha):
    halpha = download_file(f"https://lambda.gsfc.nasa.gov/data/foregrounds/fink_halpha/{fn_halpha}")
    shutil.move(halpha, fn_halpha)
halpha = fits.open(fn_halpha)
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
if os.path.exists('meerkat_projectedto_aces.fits'):
    img_meerkat_ACES = fits.getdata('meerkat_projectedto_aces.fits')
else:
    img_meerkat_ACES,_ = reproject.reproject_interp((meerkat[0].data.squeeze(), WCS(meerkat[0].header).celestial),
                                                  aces12mwcs.celestial, shape_out=aces12m[0].data.shape)
    fits.PrimaryHDU(data=img_meerkat_ACES, header=aces12m[0].header).writeto('meerkat_projectedto_aces.fits')
if os.path.exists('glimpsei4_projectedto_aces.fits'):
    img_glimpsei4_ACES = fits.getdata('glimpsei4_projectedto_aces.fits')
else:
    img_glimpsei4_ACES,_ = reproject.reproject_interp(glimpsei4, aces12mwcs.celestial, shape_out=aces12m[0].data.shape)
    fits.PrimaryHDU(data=img_glimpsei4_ACES, header=aces12m[0].header).writeto('glimpsei4_projectedto_aces.fits')
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2m]))
axins1.imshow(aces12m[0].data[slcs_sgrb2m],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3)
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
mark1.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3)
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
mark2.set_visible(False)
axins2.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_merge]))
axins3.imshow(aces12m[0].data[slcs_merge],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3)
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2m]))
axins1.imshow(aces12m[0].data[slcs_sgrb2m],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3)
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3)
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_merge]))
axins3.imshow(aces12m[0].data[slcs_merge],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3)
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight')
#img_rosat5, footprint = reproject_from_healpix(fn_rosat5, target_header)
data_rosat5 = rosat5[1].data['COUNT_RATE']
data_rosat5 = fix_rosat_nans(np.where(data_rosat5<=1e-8, np.nan, data_rosat5))
img_rosat5, footprint = reproject_from_healpix((data_rosat5.ravel(),
                                                rosat5[1].header["COORDSYS"]),
                                               target_header,
                                               nested=rosat5[1].header["ORDERING"].lower() == "nested"
                                              )
img_rosat5 = fix_nans(np.where(img_rosat5<=1e-9, np.nan, img_rosat5))
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame,
                )
ax.imshow(img_rosat5, norm=simple_norm(img_rosat5, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
merge_mask.bbox
#[Out]# RegionBoundingBox(ixmin=4051, ixmax=4484, iymin=4839, iymax=5223)
merge_mask.bbox.extent
#[Out]# (4050.5, 4483.5, 4838.5, 5222.5)
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins1.imshow(aces12m[0].data,
              extent=msgrb2m.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, color='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight')

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
              extent=msgrb2n.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight')

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
              extent=merge_mask.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight')
########################################################
# Started Logging At: 2023-02-24 18:45:59
########################################################
########################################################
# # Started Logging At: 2023-02-24 18:45:59
########################################################
get_ipython().run_line_magic('pwd', '')
#[Out]# '/orange/adamginsburg/cmz/DataSetVisualizations'
get_ipython().run_line_magic('matplotlib', 'inline')
import pylab as pl
import numpy as np
import os
from astropy.utils.data import download_file
from astropy.io import fits
from spectral_cube import SpectralCube
from astropy.visualization import simple_norm
import shutil
import reproject
from reproject import reproject_from_healpix, reproject_to_healpix

from astropy.wcs import WCS
import matplotlib.pyplot as plt
from astropy.visualization.wcsaxes.frame import EllipticalFrame
import astropy.visualization.wcsaxes

from matplotlib.colors import rgb_to_hsv, hsv_to_rgb 

from astropy import coordinates
from astropy.coordinates import SkyCoord
from astropy import units as u, constants
from astropy.convolution import convolve_fft, Gaussian2DKernel, Gaussian1DKernel
import healpy
import PIL
import pyavm
import regions
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins1.imshow(aces12m[0].data,
              extent=msgrb2m.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, color='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
              extent=msgrb2n.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
              extent=merge_mask.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
#aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                          #axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          #axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
              extent=msgrb2m.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)
raise

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
              extent=msgrb2n.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
              extent=merge_mask.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
#aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
              extent=msgrb2m.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)
raise

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
              extent=msgrb2n.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
              extent=merge_mask.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
get_ipython().run_line_magic('matplotlib', 'inline')
import pylab as pl
import numpy as np
pl.rcParams['image.interpolation'] = 'nearest'
msgrb2m.bbox.extent
#[Out]# (4232.5, 4483.5, 4838.5, 5089.5)
pl.imshow(aces12m[0].data,
              extent=msgrb2m.bbox.extent,)
#[Out]# <matplotlib.image.AxesImage at 0x2b76d43ae4c0>
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
#aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2m.bbox.extent)
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)
raise

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 15, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
              extent=msgrb2n.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
              extent=merge_mask.bbox.extent,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.axis('off')

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.1, 0, 0.2, 0.9]

axins1 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2m.bbox.extent)
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)
raise

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins2.axis(msgrb2n.bbox.extent)
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)


axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins3.extent(merge_mask.bbox.extent)
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.axis('off')

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.05, 0, 0.2, 0.95]

axins1 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2m.bbox.extent)
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)
raise

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins2.axis(msgrb2n.bbox.extent)
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)


axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins3.extent(merge_mask.bbox.extent)
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.axis('off')

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.0, 0, 0.2, 2]

axins1 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2m.bbox.extent)
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)
raise

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins2.axis(msgrb2n.bbox.extent)
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)


axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins3.extent(merge_mask.bbox.extent)
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.axis('off')

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.0, 0, 0.2, 1]

axins1 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2m.bbox.extent)
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)
raise

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins2.axis(msgrb2n.bbox.extent)
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)


axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins3.extent(merge_mask.bbox.extent)
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.axis('off')

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.05, 0, 0.2, 1.05]

axins1 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2m.bbox.extent)
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)
raise

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins2.axis(msgrb2n.bbox.extent)
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)


axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins3.extent(merge_mask.bbox.extent)
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.axis('off')

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.03, 0, 0.2, 1.05]

axins1 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2m.bbox.extent)
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins2.axis(msgrb2n.bbox.extent)
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)


axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins3.extent(merge_mask.bbox.extent)
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
merge_mask.bbox
#[Out]# RegionBoundingBox(ixmin=4051, ixmax=4484, iymin=4839, iymax=5223)
merge_mask.bbox.extent
#[Out]# (4050.5, 4483.5, 4838.5, 5222.5)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35', -0.35, layernames=('HI', 'CO', 'Dust'), do_layers=False)
prect = rect.to_pixel(ax.wcs)
prect.visual['edgecolor'] = 'w'
innergalplot = prect.plot(ax=ax)

pl.savefig("HI-CO-Dust_m0.35_RGB_innergal_zoombox.png", bbox_inches='tight')

innergaltext = ax.text(0, 25, "Galactic Plane", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

cmzrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(0*u.deg, 0*u.deg, frame='galactic'),
    width=12*u.deg,
    height=4.8*u.deg,
)
pcmzrect = cmzrect.to_pixel(ax.wcs)
pcmzrect.visual['edgecolor'] = 'w'
cmzplot = pcmzrect.plot(ax=ax)

cmztext = ax.text(0, 5, "Central Molecular Zone", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(209, -15, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_zones.png", bbox_inches='tight')

innergalplot.set_visible(False)
cmzplot.set_visible(False)
innergaltext.set_visible(False)
cmztext.set_visible(False)

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_orion.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.axis('off')

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.03, 0, 0.2, 1.05]

axins1 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2m.bbox.extent)
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

axins2 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs[slcs_sgrb2n]))
axins2.imshow(aces12m[0].data[slcs_sgrb2n],
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins2.axis(msgrb2n.bbox.extent)
mark2 = mark_inset(ax, axins2, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins2.wcs).plot(ax=axins2)
axins2.coords['glat'].set_ticklabel(visible=False)
axins2.coords['glon'].set_ticklabel(visible=False)
axins2.coords['glat'].set_ticks_visible(False)
axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins2.set_visible(False)


axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.1, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins3.axis(merge_mask.bbox.extent)
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, color='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
img_HI4PI_cmz, footprint = reproject_from_healpix(fn_HI4PI, target_header_cmz, field=5)
img_ThermalDust_cmz, footprint = reproject_from_healpix(fn_ThermalDust, target_header_cmz)
img_CO21_cmz, footprint = reproject_from_healpix(fn_CO21, target_header_cmz)
get_ipython().run_line_magic('pwd', '')
#[Out]# '/orange/adamginsburg/cmz/DataSetVisualizations'
get_ipython().run_line_magic('matplotlib', 'inline')
import pylab as pl
import numpy as np
pl.rcParams['image.interpolation'] = 'nearest'
import os
from astropy.utils.data import download_file
from astropy.io import fits
from spectral_cube import SpectralCube
from astropy.visualization import simple_norm
import shutil
import reproject
from reproject import reproject_from_healpix, reproject_to_healpix

from astropy.wcs import WCS
import matplotlib.pyplot as plt
from astropy.visualization.wcsaxes.frame import EllipticalFrame
import astropy.visualization.wcsaxes

from matplotlib.colors import rgb_to_hsv, hsv_to_rgb 

from astropy import coordinates
from astropy.coordinates import SkyCoord
from astropy import units as u, constants
from astropy.convolution import convolve_fft, Gaussian2DKernel, Gaussian1DKernel
import healpy
import PIL
import pyavm
import regions
def h_rot(rgb, rot):
    hsv = rgb_to_hsv(rgb)
    hsv[:,:,0] += rot  # 0.25 = 90/360
    hsv[:,:,0] = hsv[:,:,0] % 1 
    rgb_scaled = hsv_to_rgb(hsv)
    return rgb_scaled

def make_rgb(rgb, basename, hsv_rotation=0, layernames='RGB',
             do_layers=True,
             axlims=None, frame_class=EllipticalFrame):
    plt.figure(figsize=(10,5), dpi=200)
    ax = plt.subplot(1,1,1, projection=WCS(target_header),
                     frame_class=frame_class)
    #ax.coords.grid(color='white')
    ax.coords['glat'].set_ticklabel(visible=False)
    ax.coords['glon'].set_ticklabel(visible=False)
    ax.coords['glat'].set_ticks_visible(False)
    ax.coords['glon'].set_ticks_visible(False)
    if do_layers:
        for ind, color in zip((0, 1, 2), (layernames)):
            rgbc = np.zeros_like(rgb)
            rgbc[:, :, ind] = rgb[:, :, ind]
            if hsv_rotation != 0:
                rgbc = h_rot(rgbc, hsv_rotation)
            ax.imshow(rgbc)
            pl.savefig(f'{basename}_{color}.png', bbox_inches='tight', transparent=True)
    if hsv_rotation != 0:
        rgb = h_rot(rgb, hsv_rotation)
    ax.imshow(rgb)
    if axlims is not None:
        ax.axis(axlims)
    pl.savefig(f'{basename}_RGB.png', bbox_inches='tight', transparent=True)
    return ax
target_header_medres = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                  960
NAXIS2  =                  480
CTYPE1  = 'GLON-MOL'
CRPIX1  =                480.5
CRVAL1  =                  0.0
CDELT1  =              -0.3375
CUNIT1  = 'deg     '
CTYPE2  = 'GLAT-MOL'
CRPIX2  =                240.5
CRVAL2  =                  0.0
CDELT2  =               0.3375
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
target_header = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 1920
NAXIS2  =                  960
CTYPE1  = 'GLON-MOL'
CRPIX1  =                960.5
CRVAL1  =                  0.0
CDELT1  =             -0.16875
CUNIT1  = 'deg     '
CTYPE2  = 'GLAT-MOL'
CRPIX2  =                480.5
CRVAL2  =                  0.0
CDELT2  =              0.16875
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
def fix_nans(img):
    kernel = Gaussian2DKernel(2)
    sm = convolve_fft(img, kernel)
    img[np.isnan(img)] = sm[np.isnan(img)]
    return img

def fix_rosat_nans(tb):
    #kernel = Gaussian1DKernel(3)
    kernel = Gaussian2DKernel(1) # convolving in 2D convolves adjacent scans
    # tb is a 2D array, but we want to convolve in 1D
    #sm = convolve_fft(tb, kernel.array[None, :])
    sm = convolve_fft(tb, kernel)
    tb[np.isnan(tb)] = sm[np.isnan(tb)]
    return tb
get_ipython().run_line_magic('pwd', '')
#[Out]# '/orange/adamginsburg/cmz/DataSetVisualizations'
fn_rosat5 = "RASS_SXRB_R5.fits"
if not os.path.exists(fn_rosat5):
    rosat5 = download_file(f"https://www.jb.man.ac.uk/research/cosmos/rosat/{fn_rosat5}")
    shutil.move(rosat5, fn_rosat5)
rosat5 = fits.open(fn_rosat5)
data_rosat5 = rosat5[1].data['COUNT_RATE']
data_rosat5 = fix_rosat_nans(np.where(data_rosat5==0, np.nan, data_rosat5))
pl.hist(data_rosat5.ravel(), bins=np.logspace(-14, 5), log=True)
pl.loglog();
#img_rosat5, footprint = reproject_from_healpix(fn_rosat5, target_header)
data_rosat5 = rosat5[1].data['COUNT_RATE']
data_rosat5 = fix_rosat_nans(np.where(data_rosat5<=1e-8, np.nan, data_rosat5))
img_rosat5, footprint = reproject_from_healpix((data_rosat5.ravel(),
                                                rosat5[1].header["COORDSYS"]),
                                               target_header,
                                               nested=rosat5[1].header["ORDERING"].lower() == "nested"
                                              )
img_rosat5 = fix_nans(np.where(img_rosat5<=1e-9, np.nan, img_rosat5))
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame,
                )
ax.imshow(img_rosat5, norm=simple_norm(img_rosat5, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_halpha = "Halpha_map.fits"
if not os.path.exists(fn_halpha):
    halpha = download_file(f"https://lambda.gsfc.nasa.gov/data/foregrounds/fink_halpha/{fn_halpha}")
    shutil.move(halpha, fn_halpha)
halpha = fits.open(fn_halpha)
# img_halpha = halpha[0].data
# header = halpha[0].header
img_halpha, footprint = reproject.reproject_interp(fn_halpha, target_header)
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame,
                )
ax.imshow(img_halpha, norm=simple_norm(img_halpha, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_akari65 = "akari_mollweide_65_1_4096.fits"
if not os.path.exists(fn_akari65):
    akari65 = download_file(f"https://lambda.gsfc.nasa.gov/data/foregrounds/akari/images/{fn_akari65}")
    shutil.move(akari65, fn_akari65)
akari65 = fits.open(fn_akari65)
#img_akari65, footprint = reproject_from_healpix(fn_akari65, target_header)
img_akari65 = fix_nans(np.where(akari65[1].data == 0, np.nan, akari65[1].data))
header = akari65[1].header
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(header),
                 #frame_class=EllipticalFrame,
                )
ax.imshow(img_akari65, norm=simple_norm(img_akari65, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_akari90 = "akari_mollweide_WideS_1_4096.fits"
if not os.path.exists(fn_akari90):
    akari90 = download_file(f"https://lambda.gsfc.nasa.gov/data/foregrounds/akari/images/{fn_akari90}")
    shutil.move(akari90, fn_akari90)
akari90 = fits.open(fn_akari90)
#img_akari90, footprint = reproject_from_healpix(fn_akari90, target_header)
img_akari90 = fix_nans(np.where(akari90[1].data == 0, np.nan, akari90[1].data))
header = akari90[1].header
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(header),
                 #frame_class=EllipticalFrame,
                )
ax.imshow(img_akari90, norm=simple_norm(img_akari90, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_akari140 = "akari_mollweide_WideL_1_4096.fits"
if not os.path.exists(fn_akari140):
    akari140 = download_file(f"https://lambda.gsfc.nasa.gov/data/foregrounds/akari/images/{fn_akari140}")
    shutil.move(akari140, fn_akari140)
akari140 = fits.open(fn_akari140)
#img_akari140, footprint = reproject_from_healpix(fn_akari140, target_header)
img_akari140 = fix_nans(np.where(akari140[1].data == 0, np.nan, akari140[1].data))
header = akari140[1].header
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(header),
                 #frame_class=EllipticalFrame,
                )
ax.imshow(img_akari140, norm=simple_norm(img_akari140, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_akari160 = "akari_mollweide_160_1_4096.fits"
if not os.path.exists(fn_akari160):
    akari160 = download_file(f"https://lambda.gsfc.nasa.gov/data/foregrounds/akari/images/{fn_akari160}")
    shutil.move(akari160, fn_akari160)
akari160 = fits.open(fn_akari160)
#img_akari160, footprint = reproject_from_healpix(fn_akari160, target_header)
img_akari160 = fix_nans(np.where(akari160[1].data == 0, np.nan, akari160[1].data))
header = akari160[1].header
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(header),
                 #frame_class=EllipticalFrame,
                )
ax.imshow(img_akari160, norm=simple_norm(img_akari160, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
#fn_chipass = "lambda_chipass_HPX_r10.fits"
fn_chipass = "lambda_chipass_mollweide.fits"
if not os.path.exists(fn_chipass):
    chipass = download_file(f"https://lambda.gsfc.nasa.gov/data/foregrounds/chipass/{fn_chipass}")
    shutil.move(chipass, fn_chipass)
chipass = fits.open(fn_chipass)
#img_chipass, footprint = reproject_from_healpix(fn_chipass, target_header)
img_chipass = chipass[1].data
img_chipass[img_chipass <= 0] = chipass[2].data[img_chipass <= 0]
img_chipass[img_chipass <= 0] = np.nan
header = chipass[1].header
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(header),
                 #frame_class=EllipticalFrame,
                )
ax.imshow(img_chipass, norm=simple_norm(img_chipass, min_percent=1, max_percent=99.99, stretch='asinh'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_sve1420 = "STOCKERT+VILLA-ELISA_1420MHz_1_256.fits"
if not os.path.exists(fn_sve1420):
    sve1420 = download_file(f"https://lambda.gsfc.nasa.gov/data/foregrounds/reich_reich/{fn_sve1420}")
    shutil.move(sve1420, fn_sve1420)
sve1420 = fits.open(fn_sve1420)
img_sve1420, footprint = reproject_from_healpix(fn_sve1420, target_header)
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame)
ax.imshow(img_sve1420, norm=simple_norm(img_sve1420, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_lfi30 = 'LFI_SkyMap_030_1024_R2.01_full.fits'
if not os.path.exists(fn_lfi30):
    lfi30 = download_file(f"https://irsa.ipac.caltech.edu/data/Planck/release_2/all-sky-maps/maps/{fn_lfi30}")
    shutil.move(lfi30, fn_lfi30)
lfi30 = fits.open(fn_lfi30)
# don't use this any more
m30 = healpy.read_map(lfi30)
healpy.mollview(m30, norm=simple_norm(m30, stretch='log'), cbar=False, title='')
img_lfi30, footprint = reproject_from_healpix(fn_lfi30, target_header)
badinds = np.where(np.isnan(img_lfi30))
img_lfi30 = fix_nans(img_lfi30)
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame)
ax.imshow(img_lfi30, norm=simple_norm(img_lfi30, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_hfi143 = "HFI_SkyMap_143_2048_R2.02_full.fits"
if not os.path.exists(fn_hfi143):
    hfi143 = download_file(f"https://irsa.ipac.caltech.edu/data/Planck/release_2/all-sky-maps/maps/{fn_hfi143}")
    shutil.move(hfi143, fn_hfi143)
hfi143 = fits.open(fn_hfi143)
img_hfi143, footprint = reproject_from_healpix(fn_hfi143, target_header)
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame)
ax.imshow(img_hfi143, norm=simple_norm(img_hfi143, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_hfi857 = "HFI_SkyMap_857_2048_R2.02_full.fits"
if not os.path.exists(fn_hfi857):
    hfi857 = download_file(f"https://irsa.ipac.caltech.edu/data/Planck/release_2/all-sky-maps/maps/{fn_hfi857}")
    shutil.move(hfi857, fn_hfi857)
hfi857 = fits.open(fn_hfi857)
img_hfi857, footprint = reproject_from_healpix(fn_hfi857, target_header)
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame)
ax.imshow(img_hfi857, norm=simple_norm(img_hfi857, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
rgb = np.array([simple_norm(img_lfi30,  min_percent=0.01, max_percent=99.90, log_a=5e1, stretch='log')(img_lfi30),
                simple_norm(img_hfi143, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_hfi143),
                simple_norm(img_hfi857, min_percent=0.01, max_percent=99.90, log_a=5e1, stretch='log')(img_hfi857)]).T.swapaxes(0,1)

make_rgb(rgb, 'Planck_RGB_30-143-857')
#[Out]# <WCSAxesSubplot:>
fn_synchrotron = "COM_CompMap_Synchrotron-commander_0256_R2.00.fits"
if not os.path.exists(fn_synchrotron):
    planck_synchrotron = download_file(f"https://irsa.ipac.caltech.edu/data/Planck/release_2/all-sky-maps/maps/component-maps/foregrounds/{fn_synchrotron}")
    shutil.move(planck_synchrotron, fn_synchrotron)
planck_synchrotron = fits.open(fn_synchrotron)
img_synchrotron, footprint = reproject_from_healpix(fn_synchrotron, target_header)
img_synchrotron = fix_nans(np.where(img_synchrotron<=0, np.nan, img_synchrotron))
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame)
ax.imshow(img_synchrotron, norm=simple_norm(img_synchrotron, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_freefree = "COM_CompMap_freefree-commander_0256_R2.00.fits"
if not os.path.exists(fn_freefree):
    planck_freefree = download_file(f"https://irsa.ipac.caltech.edu/data/Planck/release_2/all-sky-maps/maps/component-maps/foregrounds/{fn_freefree}")
    shutil.move(planck_freefree, fn_freefree)
planck_freefree = fits.open(fn_freefree)
img_freefree, footprint = reproject_from_healpix(fn_freefree, target_header)
img_freefree = fix_nans(img_freefree)
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame)
ax.imshow(img_freefree, norm=simple_norm(img_freefree, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_CO21 = "COM_CompMap_CO21-commander_2048_R2.00.fits"
if not os.path.exists(fn_CO21):
    planck_CO21 = download_file(f"https://irsa.ipac.caltech.edu/data/Planck/release_2/all-sky-maps/maps/component-maps/foregrounds/{fn_CO21}")
    shutil.move(planck_CO21, fn_CO21)
planck_CO21 = fits.open(fn_CO21)
img_CO21, footprint = reproject_from_healpix(fn_CO21, target_header)
img_CO21 = fix_nans(img_CO21)
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame)
ax.imshow(img_CO21, norm=simple_norm(img_CO21, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_ThermalDust = "COM_CompMap_ThermalDust-commander_2048_R2.00.fits"
if not os.path.exists(fn_ThermalDust):
    planck_ThermalDust = download_file(f"https://irsa.ipac.caltech.edu/data/Planck/release_2/all-sky-maps/maps/component-maps/foregrounds/{fn_ThermalDust}")
    shutil.move(planck_ThermalDust, fn_ThermalDust)
planck_ThermalDust = fits.open(fn_ThermalDust)
img_ThermalDust, footprint = reproject_from_healpix(fn_ThermalDust, target_header)
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame)
ax.imshow(img_ThermalDust, norm=simple_norm(img_ThermalDust, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
fn_LAB_HI = 'LAB_fullvel.fits'
if not os.path.exists(fn_LAB_HI):
    LAB_HI = download_file(f"https://lambda.gsfc.nasa.gov/data/foregrounds/HI/{fn_LAB_HI}")
    shutil.move(LAB_HI, fn_LAB_HI)
LAB_HI = fits.open(fn_LAB_HI)
img_LAB_HI, footprint = reproject_from_healpix(fn_LAB_HI, target_header, field=5)
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame)
ax.imshow(img_LAB_HI, norm=simple_norm(img_LAB_HI, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.axis('off')

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.01, 0, 0.2, 1.05]

axins1 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2m.bbox.extent)
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

#axins2 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
#                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
#                          axes_kwargs=dict(wcs=ax.wcs))
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2n.bbox.extent)
mark2 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins1.wcs).plot(ax=axins1)
#axins2.coords['glat'].set_ticklabel(visible=False)
#axins2.coords['glon'].set_ticklabel(visible=False)
#axins2.coords['glat'].set_ticks_visible(False)
#axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins1.set_visible(False)


axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.05, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins3.axis(merge_mask.bbox.extent)
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, edgecolor='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
fn_HI4PI = 'NHI_HPX.fits'
if not os.path.exists(fn_HI4PI):
    HI4PI = download_file(f"https://lambda.gsfc.nasa.gov/data/foregrounds/HI4PI/{fn_HI4PI}")
    shutil.move(HI4PI, fn_HI4PI)
HI4PI = fits.open(fn_HI4PI)
img_HI4PI, footprint = reproject_from_healpix(fn_HI4PI, target_header, field=5)
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header),
                 frame_class=EllipticalFrame)
ax.imshow(img_HI4PI, norm=simple_norm(img_HI4PI, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
make_rgb(rgb, 'HI-CO-Dust')
#[Out]# <WCSAxesSubplot:>
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
make_rgb(rgb, 'HI-CO-Dust_m0.25', -0.25, layernames=('HI', 'CO', 'Dust'))
#[Out]# <WCSAxesSubplot:>
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
make_rgb(rgb, 'HI-CO-Dust_m0.35', -0.35, layernames=('HI', 'CO', 'Dust'))
#[Out]# <WCSAxesSubplot:>
# zoom on lower-left corner
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
make_rgb(rgb, 'HI-CO-Dust_m0.35_zoom', -0.35, layernames=('HI', 'CO', 'Dust'),
         axlims=(240, 720, 120, 360), frame_class=None)
#[Out]# <WCSAxesSubplot:xlabel='pos.galactic.lon', ylabel='pos.galactic.lat'>
# CMZoom
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
make_rgb(rgb, 'HI-CO-Dust_m0.35_zoomCMZ', -0.35, layernames=('HI', 'CO', 'Dust'),
         axlims=(240*2, 720*2, 120*2, 360*2), frame_class=None)
#[Out]# <WCSAxesSubplot:xlabel='pos.galactic.lon', ylabel='pos.galactic.lat'>
img_rosat5.shape, img_halpha.shape, img_synchrotron.shape
#[Out]# ((960, 1920), (960, 1920), (960, 1920))
rgb = np.array([simple_norm(img_rosat5,  min_percent=0.01, max_percent=99.99, log_a=5e1, stretch='log')(img_rosat5),
                simple_norm(img_halpha, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_halpha),
                simple_norm(img_synchrotron, min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_synchrotron)]).T.swapaxes(0,1)

make_rgb(rgb, 'XRay_Halpha_Synchro', layernames=('X-Ray', 'Halpha', 'Synchrotron'))
#[Out]# <WCSAxesSubplot:>
rgb = np.array([simple_norm(img_rosat5,  min_percent=0.01, max_percent=99.99, log_a=5e1, stretch='log')(img_rosat5),
                simple_norm(img_synchrotron, min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_synchrotron)]
                simple_norm(img_HI4PI, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
              ).T.swapaxes(0,1)

make_rgb(rgb, 'XRay_Synchro_HI4PI', layernames=('X-Ray', 'Synchrotron', 'HI4PI', ), hsv_rotation=-0.25)
rgb = np.array([simple_norm(img_rosat5,  min_percent=0.01, max_percent=99.99, log_a=5e1, stretch='log')(img_rosat5),
                simple_norm(img_synchrotron, min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_synchrotron),
                simple_norm(img_HI4PI, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
              ).T.swapaxes(0,1)

make_rgb(rgb, 'XRay_Synchro_HI4PI', layernames=('X-Ray', 'Synchrotron', 'HI4PI', ), hsv_rotation=-0.25)
rgb = np.array([simple_norm(img_rosat5,  min_percent=0.01, max_percent=99.99, log_a=5e1, stretch='log')(img_rosat5),
                simple_norm(img_synchrotron, min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_synchrotron),
                simple_norm(img_HI4PI, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),]
              ).T.swapaxes(0,1)

make_rgb(rgb, 'XRay_Synchro_HI4PI', layernames=('X-Ray', 'Synchrotron', 'HI4PI', ), hsv_rotation=-0.25)
#[Out]# <WCSAxesSubplot:>
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.axis('off')

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.01, 0, 0.2, 1.05]

axins1 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2m.bbox.extent)
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
#axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

#axins2 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
#                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
#                          axes_kwargs=dict(wcs=ax.wcs))
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2n.bbox.extent)
mark2 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins1.wcs).plot(ax=axins1)
#axins2.coords['glat'].set_ticklabel(visible=False)
#axins2.coords['glon'].set_ticklabel(visible=False)
#axins2.coords['glat'].set_ticks_visible(False)
#axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins1.set_visible(False)


axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.05, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins3.axis(merge_mask.bbox.extent)
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, edgecolor='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
rgb = np.array([simple_norm(img_rosat5,  min_percent=0.01, max_percent=99.99, log_a=5e1, stretch='log')(img_rosat5),
                simple_norm(img_halpha, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_halpha),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.99, log_a=5e1, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)

make_rgb(rgb, 'XRay_Halpha_ThermalDust', layernames=('X-Ray', 'Halpha', 'ThermalDust'))
#[Out]# <WCSAxesSubplot:>
rgb = np.array([simple_norm(img_rosat5,  min_percent=0.01, max_percent=99.99, log_a=5e1, stretch='log')(img_rosat5),
                simple_norm(img_halpha, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_halpha),
                simple_norm(img_CO21, min_percent=0.01, max_percent=99.99, log_a=5e1, stretch='log')(img_CO21)]).T.swapaxes(0,1)

make_rgb(rgb, 'XRay_Halpha_CO21', layernames=('X-Ray', 'Halpha', 'CO21'))
#[Out]# <WCSAxesSubplot:>
rgb = np.array([simple_norm(img_rosat5,  min_percent=0.01, max_percent=99.99, log_a=1e3, stretch='log')(img_rosat5),
                simple_norm(img_halpha, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_halpha),
                simple_norm(img_CO21, min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21)]).T.swapaxes(0,1)

make_rgb(rgb, 'XRay_Halpha_CO21', layernames=('X-Ray', 'Halpha', 'CO21'), hsv_rotation=-0.25)
#[Out]# <WCSAxesSubplot:>
xray_synchro = (simple_norm(img_rosat5,  min_percent=0.001, max_percent=99.999, stretch='linear')(img_rosat5) +
                simple_norm(img_synchrotron,  min_percent=0.001, max_percent=99.999, stretch='linear')(img_synchrotron))
rgb = np.array([simple_norm(xray_synchro,  min_percent=0.01, max_percent=99.99, log_a=1e2, stretch='log')(xray_synchro),
                simple_norm(img_halpha, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_halpha),
                simple_norm(img_CO21, min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21)]).T.swapaxes(0,1)

make_rgb(rgb, 'XRaySynchro_Halpha_CO21', layernames=('X-RaySynchro', 'Halpha', 'CO21'), hsv_rotation=-0.25)
#[Out]# <WCSAxesSubplot:>
rgb = np.array([simple_norm(img_rosat5,  min_percent=0.01, max_percent=99.99, log_a=2e2, stretch='log')(img_rosat5),
                simple_norm(img_halpha, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_halpha),
                simple_norm(img_HI4PI, min_percent=0.01, max_percent=99.99, log_a=2e2, stretch='log')(img_HI4PI)]).T.swapaxes(0,1)

make_rgb(rgb, 'XRay_Halpha_HI4PI', layernames=('X-Ray', 'Halpha', 'HI4PI'))
#[Out]# <WCSAxesSubplot:>
rgb = np.array([simple_norm(img_rosat5,  min_percent=0.01, max_percent=99.99, log_a=1e2, stretch='log')(img_rosat5),
                simple_norm(img_halpha, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_halpha),
                simple_norm(img_freefree, min_percent=0.01, max_percent=99.99, log_a=1e3, stretch='log')(img_freefree)]).T.swapaxes(0,1)

make_rgb(rgb, 'XRay_Halpha_freefree', layernames=('X-Ray', 'Halpha', 'freefree'))
#[Out]# <WCSAxesSubplot:>
rgb = np.array([simple_norm(img_rosat5,  min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_rosat5),
                simple_norm(img_halpha, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_halpha),
                simple_norm(img_freefree, min_percent=0.01, max_percent=99.99, log_a=1e2, stretch='log')(img_freefree)]).T.swapaxes(0,1)

make_rgb(rgb, 'XRay_Halpha_freefree', layernames=('X-Ray', 'Halpha', 'freefree'), hsv_rotation=-0.25)
#[Out]# <WCSAxesSubplot:>
target_header_cmz = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 1920
NAXIS2  =                  960
CTYPE1  = 'GLON-MOL'
CRPIX1  =                960.5
CRVAL1  =                  0.0
CDELT1  =                -0.05
CUNIT1  = 'deg     '
CTYPE2  = 'GLAT-MOL'
CRPIX2  =                480.5
CRVAL2  =                  0.0
CDELT2  =                 0.05
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
target_header_innergal = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 3840
NAXIS2  =                  960
CTYPE1  = 'GLON-MOL'
CRPIX1  =               1920.5
CRVAL1  =                  0.0
CDELT1  =                -0.05
CUNIT1  = 'deg     '
CTYPE2  = 'GLAT-MOL'
CRPIX2  =                480.5
CRVAL2  =                  0.0
CDELT2  =                 0.05
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
img_HI4PI_cmz, footprint = reproject_from_healpix(fn_HI4PI, target_header_cmz, field=5)
img_ThermalDust_cmz, footprint = reproject_from_healpix(fn_ThermalDust, target_header_cmz)
img_CO21_cmz, footprint = reproject_from_healpix(fn_CO21, target_header_cmz)
img_HI4PI_innergal, footprint = reproject_from_healpix(fn_HI4PI, target_header_innergal, field=5)
img_ThermalDust_innergal, footprint = reproject_from_healpix(fn_ThermalDust, target_header_innergal)
img_CO21_innergal, footprint = reproject_from_healpix(fn_CO21, target_header_innergal)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)
#[Out]# (240.0, 720.0)
from astropy import units as u
hi_cube_fn = '/orange/adamginsburg/cmz/hi/mcluregriffiths/GC.hi.tb.allgal.fits'
#if os.path.exists("GC.hi.tb.allgal.fits.gz"):
#    hi_cube_fh = fits.open("GC.hi.tb.allgal.fits.gz")
#else:
#    print("Not downloaded.")
#    #hi_cube_fh = download_file("http://www.atnf.csiro.au/research/HI/sgps/SGPS_1/GC.hi.tb.allgal.fits.gz")
hi_cube = SpectralCube.read(hi_cube_fn, use_dask=True)
peak_hi = hi_cube.max(axis=0)
mean_hi = hi_cube.mean(axis=0)
pl.imshow(peak_hi.value)
#[Out]# <matplotlib.image.AxesImage at 0x2b76a92b46d0>
pl.imshow(mean_hi.value, vmin=0)
#[Out]# <matplotlib.image.AxesImage at 0x2b76a93122e0>
from matplotlib.colors import ListedColormap
cmap = pl.cm.gray
gray_transparent = cmap(np.arange(cmap.N))
gray_transparent[:,-1] = np.linspace(0, 1, cmap.N)
gray_transparent = ListedColormap(gray_transparent)
cmap = pl.cm.Oranges
orange_transparent = cmap(np.arange(cmap.N))
orange_transparent[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent = ListedColormap(orange_transparent)

cmap = pl.cm.Oranges_r
orange_transparent_r = cmap(np.arange(cmap.N))
orange_transparent_r[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent_r = ListedColormap(orange_transparent_r)

orange_transparent2 = cmap(np.arange(cmap.N))
orange_transparent2[:,-1] = np.linspace(0, 1, cmap.N)
orange_transparent2[:,:-1] = [0.95, 0.35, 0.03]
orange_transparent2 = ListedColormap(orange_transparent2)
if os.path.exists("DHT02_Center_interp.fits"):
    cube_dame12co = SpectralCube.read('DHT02_Center_interp.fits', use_dask=True)
else:
    pass
peak_dameco = cube_dame12co.max(axis=0)
mean_dameco = cube_dame12co.mean(axis=0)
if os.path.exists('GalacticCenterMosaic_downsampled4x_2kms.fits'):
    co_cube = SpectralCube.read('GalacticCenterMosaic_downsampled4x_2kms.fits', use_dask=True)
peak_co = co_cube.max(axis=0)
mean_co = co_cube.mean(axis=0)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(mean_hi.value,
          transform=ax.get_transform(hi_cube.wcs.celestial),
          norm=simple_norm(mean_hi.value, min_percent=2, max_percent=99.9, stretch='asinh'),
          cmap=orange_transparent)
#[Out]# <matplotlib.image.AxesImage at 0x2b76a93d82e0>
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(mean_dameco.value,
          norm=simple_norm(mean_dameco.value, min_percent=2, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(cube_dame12co.wcs.celestial),
          cmap=orange_transparent)

pl.savefig("HI4PI_CO_Dust_withDameCOOrangeOverlay.png", bbox_inches='tight')
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(peak_co.value,
          norm=simple_norm(peak_co.value, min_percent=0.1, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(co_cube.wcs.celestial),
          cmap=orange_transparent)

pl.savefig("HI4PI_CO_Dust_withJCMTCOOrange.png", bbox_inches='tight')
atlasgal = fits.open('/orange/adamginsburg/galactic_plane_surveys/atlasgal/MOSAICS/apex_planck.fits')
print(atlasgal[0].data.shape)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=0.1, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap='gray')

pl.savefig("HI4PI_CO_Dust_withATLASGAL.png", bbox_inches='tight')
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=gray_transparent)
pl.savefig("HI4PI_CO_Dust_withATLASGALtransparent.png", bbox_inches='tight')
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
pl.savefig("HI4PI_CO_Dust_withATLASGALOrangetransparent.png", bbox_inches='tight')
from astroquery.vizier import Vizier
from astropy.coordinates import SkyCoord
almaimf_cat = Vizier.get_catalogs('J/A+A/662/A9/objects')[0]
almaimf_crds = SkyCoord(almaimf_cat['RAJ2000'], almaimf_cat['DEJ2000'], frame='fk5', unit=(u.h, u.deg))
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)


ax.scatter(almaimf_crds.galactic.l, almaimf_crds.galactic.b,
           marker='*', edgecolor='purple', facecolor='none', transform=ax.get_transform('galactic'))

pl.savefig("HI4PI_CO_Dust_withATLASGALOrangetransparent_ALMA-IMFtargets.png", bbox_inches='tight')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_innergal),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(540, 3840-540)
ax.set_ylim(0, 960)

ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)

pl.savefig("HI4PI_CO_Dust_innergal_withATLASGALOrangetransparent.png", bbox_inches='tight')

ax.scatter(almaimf_crds.galactic.l, almaimf_crds.galactic.b,
           marker='*', edgecolor='purple', facecolor='none', transform=ax.get_transform('galactic'))

pl.savefig("HI4PI_CO_Dust_innergal_withATLASGALOrangetransparent_ALMA-IMFtargets.png", bbox_inches='tight')


import regions
from astropy import coordinates
rect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(0*u.deg, 0*u.deg, frame='galactic'),
    width=np.abs((ax.get_xlim()[1] - ax.get_xlim()[0])*target_header_innergal['CDELT1'])*u.deg,
    height=(ax.get_ylim()[1] - ax.get_ylim()[0])*target_header_innergal['CDELT2']*u.deg,
)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35', -0.35, layernames=('HI', 'CO', 'Dust'), do_layers=False)
prect = rect.to_pixel(ax.wcs)
prect.visual['edgecolor'] = 'w'
innergalplot = prect.plot(ax=ax)

pl.savefig("HI-CO-Dust_m0.35_RGB_innergal_zoombox.png", bbox_inches='tight')

innergaltext = ax.text(0, 25, "Galactic Plane", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

cmzrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(0*u.deg, 0*u.deg, frame='galactic'),
    width=12*u.deg,
    height=4.8*u.deg,
)
pcmzrect = cmzrect.to_pixel(ax.wcs)
pcmzrect.visual['edgecolor'] = 'w'
cmzplot = pcmzrect.plot(ax=ax)

cmztext = ax.text(0, 5, "Central Molecular Zone", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(209, -15, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_zones.png", bbox_inches='tight')

innergalplot.set_visible(False)
cmzplot.set_visible(False)
innergaltext.set_visible(False)
cmztext.set_visible(False)

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_orion.png", bbox_inches='tight')
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)

cmzrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(0*u.deg, 0*u.deg, frame='galactic'),
    width=12*u.deg,
    height=4.8*u.deg,
)
pcmzrect = cmzrect.to_pixel(ax.wcs)
pcmzrect.visual['edgecolor'] = 'w'
pcmzrect.plot(ax=ax)

pl.savefig("HI4PI_CO_Dust_withATLASGALOrangetransparent_cmzbox.png", bbox_inches='tight')
hnco_cube = SpectralCube.read("CMZ_3mm_HNCO.fits", use_dask=True)
hnco_cube.shape
#[Out]# (327, 165, 765)
target_header_cmz_hires = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 1200
NAXIS2  =                  480
CTYPE1  = 'GLON-CAR'
CRPIX1  =                600.5
CRVAL1  =                  0.0
CDELT1  =                -0.01
CUNIT1  = 'deg     '
CTYPE2  = 'GLAT-CAR'
CRPIX2  =                240.5
CRVAL2  =                  0.0
CDELT2  =                 0.01
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
hi_cube.spectral_slab(100*u.km/u.s, 300*u.km/u.s).mean(axis=0).quicklook()
hi_cube.spectral_slab(-300*u.km/u.s, -100*u.km/u.s).mean(axis=0).quicklook()
mean_hi_highv = (hi_cube.spectral_slab(-300*u.km/u.s, -100*u.km/u.s).mean(axis=0) + hi_cube.spectral_slab(100*u.km/u.s, 300*u.km/u.s).mean(axis=0))
img_hi_cmz_hires, footprint = reproject.reproject_interp(mean_hi_highv.hdu, target_header_cmz_hires)
img_agal_cmz_hires, footprint = reproject.reproject_interp(atlasgal, target_header_cmz_hires)
img_meerkat_cmz_hires, footprint = reproject.reproject_interp((meerkat[0].data.squeeze(), WCS(meerkat[0].header).celestial), target_header_cmz_hires)
img_co_cmz_hires, footprint = reproject.reproject_interp(mean_co.hdu, target_header_cmz_hires)
for im in (img_hi_cmz_hires, img_agal_cmz_hires, img_co_cmz_hires):
    im[im==0] = np.nan
glimpsei4 = fits.open('/orange/adamginsburg/cmz/glimpse_data/GLM_00000+0000_mosaic_I4.fits')
fn_meerkat = 'MeerKAT_Galactic_Centre_1284MHz-StokesI.fits'
if not os.path.exists(fn_meerkat):
    meerkat = download_file(f"https://archive-gw-1.kat.ac.za/public/repository/10.48479/fyst-hj47/data/{fn_meerkat}")
    shutil.move(meerkat, fn_meerkat)
meerkat = fits.open(fn_meerkat)
fn_meerkat = 'MeerKAT_Galactic_Centre_1284MHz-StokesI.fits'
if not os.path.exists(fn_meerkat):
    meerkat = download_file(f"https://archive-gw-1.kat.ac.za/public/repository/10.48479/fyst-hj47/data/{fn_meerkat}")
    shutil.move(meerkat, fn_meerkat)
meerkat = fits.open(fn_meerkat)
glimpsei4 = fits.open('/orange/adamginsburg/cmz/glimpse_data/GLM_00000+0000_mosaic_I4.fits')
img_hi_cmz_hires, footprint = reproject.reproject_interp(mean_hi_highv.hdu, target_header_cmz_hires)
img_agal_cmz_hires, footprint = reproject.reproject_interp(atlasgal, target_header_cmz_hires)
img_meerkat_cmz_hires, footprint = reproject.reproject_interp((meerkat[0].data.squeeze(), WCS(meerkat[0].header).celestial), target_header_cmz_hires)
img_co_cmz_hires, footprint = reproject.reproject_interp(mean_co.hdu, target_header_cmz_hires)
for im in (img_hi_cmz_hires, img_agal_cmz_hires, img_co_cmz_hires):
    im[im==0] = np.nan
pl.imshow(img_meerkat_cmz_hires, norm=simple_norm(img_meerkat_cmz_hires, min_percent=1, max_percent=99.99, log_a=5e-1, stretch='log'))
#[Out]# <matplotlib.image.AxesImage at 0x2b76b03d96a0>
pl.imshow(img_hi_cmz_hires, norm=simple_norm(img_hi_cmz_hires,   min_percent=25, max_percent=99.99, log_a=5e-1, stretch='linear'))
#[Out]# <matplotlib.image.AxesImage at 0x2b76b0467850>
pl.imshow(img_co_cmz_hires, norm=simple_norm(img_co_cmz_hires,   min_percent=5, max_percent=99.99, log_a=1e1, stretch='asinh'))
#[Out]# <matplotlib.image.AxesImage at 0x2b76b04b5c40>
pl.imshow(img_agal_cmz_hires, norm=simple_norm(img_agal_cmz_hires, min_percent=1, max_percent=99.9, log_a=3e1, stretch='log'))
#[Out]# <matplotlib.image.AxesImage at 0x2b76b0512f40>
rgb = np.array([simple_norm(img_hi_cmz_hires,   min_percent=25, max_percent=99.99, log_a=4e1, stretch='linear')(img_hi_cmz_hires),
                simple_norm(img_co_cmz_hires,   min_percent=5, max_percent=99.99, log_a=4e1, stretch='asinh')(img_co_cmz_hires),
                simple_norm(img_agal_cmz_hires, min_percent=1, max_percent=99.99, log_a=4e1, stretch='log')(img_agal_cmz_hires)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(np.nan_to_num(rgb))
hsv[:,:,0] += -0.35#.45  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz_hires),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

ax.set_xlim(100, 1100);
ax.set_ylim(140, 340);

pl.savefig("HI_CO_Dust_BigCMZ.png", bbox_inches='tight')
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset
from mpl_toolkits.axes_grid1.inset_locator import TransformedBbox, BboxPatch, BboxConnector, Path
from matplotlib.transforms import Bbox
from matplotlib.patches import Polygon, PathPatch, ConnectionPatch

def mark_inset_generic(axins, parent_ax, data, loc1=1, loc2=3,
                       loc1in=None, loc2in=None, edgecolor='b', zorder1=100, zorder2=100, polyzorder=1):
    bl = axins.wcs.pixel_to_world(0, 0)
    br = axins.wcs.pixel_to_world(data.shape[1], 0)
    tl = axins.wcs.pixel_to_world(0, data.shape[0]) # x,y not y,x
    tr = axins.wcs.pixel_to_world(data.shape[1], data.shape[0]) # x,y not y,x
    
    fig = parent_ax.get_figure()
    
    frame = parent_ax.wcs.wcs.radesys.lower()
    frame = ax.wcs.world_axis_physical_types[0].split(".")[1]
    
    blt = bl.transform_to(frame)
    brt = br.transform_to(frame)
    tlt = tl.transform_to(frame)
    trt = tr.transform_to(frame)
    xys = [parent_ax.wcs.wcs_world2pix([[crd.spherical.lon.deg,
                                         crd.spherical.lat.deg]],0)[0]
           for crd in (trt, tlt, blt, brt, trt)]
    
    markinkwargs = dict(fc='none', ec=edgecolor)
    ppoly = Polygon(xys, fill=False, zorder=polyzorder, **markinkwargs)
    parent_ax.add_patch(ppoly)
    
    corners = parent_ax.transData.inverted().transform(xys)
    
    axcorners = [(1,1), (0,1), (0,0), (1,0)]
    corners = [(crd.spherical.lon.deg, crd.spherical.lat.deg)
               for crd in (trt, tlt, blt, brt)]
    
    if loc1in is None:
        loc1in = loc1
    if loc2in is None:
        loc2in = loc2
    
    con1 = ConnectionPatch(xyA=axcorners[loc1-1], coordsA='axes fraction', axesA=axins,
                           xyB=corners[loc1in-1], coordsB=parent_ax.get_transform('world'), axesB=parent_ax,
                           linestyle='-', color=edgecolor, zorder=zorder1)
    con2 = ConnectionPatch(xyA=axcorners[loc2-1], coordsA='axes fraction', axesA=axins,
                           xyB=corners[loc2in-1], coordsB=parent_ax.get_transform('world'), axesB=parent_ax,
                           linestyle='-', color=edgecolor, zorder=zorder2)    
    fig.add_artist(con1)
    fig.add_artist(con2)
    
    return con1, con2
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

fig = plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(2,1,2, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
#ax.set_xlim(240*2, 720*2)
ax.set_xlim(0, 1920)
ax.set_ylim(120*2, 360*2)

ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)

#cmzrect = regions.RectangleSkyRegion(
#    coordinates.SkyCoord(0*u.deg, 0*u.deg, frame='galactic'),
#    width=12*u.deg,
#    height=4.8*u.deg,
#)
#pcmzrect = cmzrect.to_pixel(ax.wcs)
#pcmzrect.visual['edgecolor'] = 'w'
#pcmzrect.plot(ax=ax)

rgb = np.array([simple_norm(img_hi_cmz_hires,   min_percent=25, max_percent=99.99, log_a=4e1, stretch='linear')(np.nan_to_num(img_hi_cmz_hires)),
                simple_norm(img_co_cmz_hires,   min_percent=5, max_percent=99.99, log_a=4e1, stretch='asinh')(np.nan_to_num(img_co_cmz_hires)),
                simple_norm(img_agal_cmz_hires, min_percent=1, max_percent=99.99, log_a=4e1, stretch='log')(np.nan_to_num(img_agal_cmz_hires))]).T.swapaxes(0,1)
hsv = rgb_to_hsv(np.nan_to_num(rgb))
hsv[:,:,0] += -0.35#.45  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0, 0.25, 1, 0.5],
                   bbox_transform=fig.transFigure,
                   loc='lower center',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=WCS(target_header_cmz_hires)))
axins.imshow(rgb_scaled)
axins.coords['glat'].set_ticklabel(visible=False)
axins.coords['glon'].set_ticklabel(visible=False)
axins.coords['glat'].set_ticks_visible(False)
axins.coords['glon'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=img_hi_cmz_hires, loc1=4, edgecolor='w')

pl.savefig("HI4PI_CO_Dust_withATLASGALOrangetransparent_cmzbox_insetzoom.png", bbox_inches='tight')
import PIL
import pyavm
np.array(PIL.Image.open('gc_fullres_6.jpg')).shape
#[Out]# (3295, 6473, 3)
rgb = np.array([simple_norm(img_hi_cmz_hires,   min_percent=25, max_percent=99.99, log_a=4e1, stretch='linear')(np.nan_to_num(img_hi_cmz_hires)),
                simple_norm(img_co_cmz_hires,   min_percent=5, max_percent=99.99, log_a=4e1, stretch='asinh')(np.nan_to_num(img_co_cmz_hires)),
                simple_norm(img_agal_cmz_hires, min_percent=1, max_percent=99.99, log_a=4e1, stretch='log')(np.nan_to_num(img_agal_cmz_hires))]).T.swapaxes(0,1)
hsv = rgb_to_hsv(np.nan_to_num(rgb))
hsv[:,:,0] += -0.35
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

fig = plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(2,1,1, projection=WCS(target_header_cmz_hires),)
ax.imshow(rgb_scaled)
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)


rgb = np.array(PIL.Image.open('gc_fullres_6.jpg'))
ww = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.01, 0.2, 1, 0.5],
                   bbox_transform=fig.transFigure,
                   loc='upper center',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb[::-1,:,:])
axins.coords['glat'].set_ticklabel(visible=False)
axins.coords['glon'].set_ticklabel(visible=False)
axins.coords['glat'].set_ticks_visible(False)
axins.coords['glon'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, edgecolor='w')

pl.savefig("HI-CO-Dust_zoominto3color.png", bbox_inches='tight')
rgb = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
ww = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

fig = plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=ww)
ax.imshow(rgb)
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

aces7m = fits.open('/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
aces7mwcs = WCS(aces7m[0].header)
aces7mrepr,_ = reproject.reproject_interp(aces7m, ww, shape_out=rgb.shape[:2])
aces7mrepr[aces7mrepr < 0] = np.nan
ax.imshow(aces7mrepr, 
          norm=simple_norm(aces7mrepr, stretch='log', max_percent=99.96, min_percent=1),
          cmap=orange_transparent)

pl.savefig("gc_fullres_6_small_withACES7m.png", bbox_inches='tight', pad_inches=0)

rgb = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
ww = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

fig = plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(2,1,2, projection=ww)
ax.imshow(rgb)
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

aces7m = fits.open('/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
aces7mwcs = WCS(aces7m[0].header)
aces7mrepr,_ = reproject.reproject_interp(aces7m, ww, shape_out=rgb.shape[:2])
aces7mrepr[aces7mrepr < 0] = np.nan
ax.imshow(aces7mrepr, 
          norm=simple_norm(aces7mrepr, stretch='log', max_percent=99.96, min_percent=1),
          cmap=orange_transparent)

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.01, 0.5, 1, 0.5],
                   bbox_transform=fig.transFigure,
                   loc='upper center',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=aces12mwcs))
axins.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )

axins.coords['glat'].set_ticklabel(visible=False)
axins.coords['glon'].set_ticklabel(visible=False)
axins.coords['glat'].set_ticks_visible(False)
axins.coords['glon'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=aces12m[0].data, loc1=4, edgecolor='y')


pl.savefig("gc_fullres_6_small_withACES7m_12minset.png", bbox_inches='tight')
import regions
from astropy import coordinates
from astropy import units as u, constants
import astropy.visualization.wcsaxes
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0

fig = plt.figure(figsize=(10,5), frameon=False)
ax = plt.subplot(1,1,1, projection=aces12mwcs)


ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.axis('off')

sgrb2m = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6672*u.deg,  -00.03640*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2n = regions.CircleSkyRegion(
    coordinates.SkyCoord(000.6773*u.deg,  -00.029*u.deg, frame='galactic'),
    radius=25*u.arcsec)
sgrb2m.visual['edgecolor'] = 'r'
sgrb2n.visual['edgecolor'] = 'r'

merge = psgrb2n & psgrb2m
merge_mask = merge.to_mask()
slcs_merge,_ = merge_mask.get_overlap_slices(aces12m[0].data.shape)

# moved down here for debugging...
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
            )


psgrb2m = sgrb2m.to_pixel(ax.wcs)
point_sgrb2m = psgrb2m.plot(ax=ax)
msgrb2m = psgrb2m.to_mask()
slcs_sgrb2m,_ = msgrb2m.get_overlap_slices(aces12m[0].data.shape)

bbox = [0.01, 0, 0.2, 1.05]

axins1 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox,
                           bbox_transform=fig.transFigure,
                           axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                           axes_kwargs=dict(wcs=ax.wcs)
                          )
axins1.axis('off')
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2m.bbox.extent)
mark1 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2m_in = sgrb2m.to_pixel(axins1.wcs).plot(ax=axins1)
axins1.coords['glat'].set_ticklabel(visible=False)
axins1.coords['glon'].set_ticklabel(visible=False)
axins1.coords['glat'].set_ticks_visible(False)
axins1.coords['glon'].set_ticks_visible(False)


pl.savefig("aces_mark_sgrb2m.png", bbox_inches='tight', dpi=200)

point_sgrb2m.set_visible(False)
point_sgrb2m_in.set_visible(False)
#axins1.set_visible(False)
for pp in mark1:
    pp.set_visible(False)

psgrb2n = sgrb2n.to_pixel(ax.wcs)
psgrb2n.visual['edgecolor'] = 'r'
point_sgrb2n = psgrb2n.plot(ax=ax)
msgrb2n = psgrb2n.to_mask()
slcs_sgrb2n,_ = msgrb2n.get_overlap_slices(aces12m[0].data.shape)

#axins2 = zoomed_inset_axes(ax, 30, loc='upper left', bbox_to_anchor=bbox, bbox_transform=fig.transFigure,
#                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
#                          axes_kwargs=dict(wcs=ax.wcs))
axins1.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins1.axis(msgrb2n.bbox.extent)
mark2 = mark_inset(ax, axins1, loc1=1, loc2=3, edgecolor='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins1.wcs).plot(ax=axins1)
#axins2.coords['glat'].set_ticklabel(visible=False)
#axins2.coords['glon'].set_ticklabel(visible=False)
#axins2.coords['glat'].set_ticks_visible(False)
#axins2.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2n.png", bbox_inches='tight', dpi=200)

point_sgrb2n.set_visible(False)
point_sgrb2n_in.set_visible(False)
for pp in mark2:
    pp.set_visible(False)
axins1.set_visible(False)


axins3 = zoomed_inset_axes(ax, 15, loc='upper left',
                           bbox_to_anchor=[0.05, 0, 0.2, 1], bbox_transform=fig.transFigure,
                          axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                          axes_kwargs=dict(wcs=ax.wcs))
axins3.axis('off')
axins3.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.5,),
             cmap='gray'
            )
axins3.axis(merge_mask.bbox.extent)
mark3 = mark_inset(ax, axins3, loc1=1, loc2=3, edgecolor='r')
point_sgrb2n_in = sgrb2n.to_pixel(axins3.wcs).plot(ax=axins3)
point_sgrb2m_in = sgrb2m.to_pixel(axins3.wcs).plot(ax=axins3)
axins3.coords['glat'].set_ticklabel(visible=False)
axins3.coords['glon'].set_ticklabel(visible=False)
axins3.coords['glat'].set_ticks_visible(False)
axins3.coords['glon'].set_ticks_visible(False)

pl.savefig("aces_mark_sgrb2mANDn.png", bbox_inches='tight', dpi=200)
# FAILED attempt to show with 12m


rgb = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
ww = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

fig = plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=ww)
ax.imshow(rgb)
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12m[0].data[aces12m[0].data < -0.0005] = 0

aces12mwcs = WCS(aces12m[0].header)
aces12mrepr,_ = reproject.reproject_interp(aces12m, ww, shape_out=rgb.shape[:2])
aces12mrepr[aces12mrepr < -5e-4] = 0
aces12mrepr[aces12mrepr < 1e-4] = np.nan
ax.imshow(aces12mrepr, 
          norm=simple_norm(aces12mrepr, stretch='log', max_percent=99.5, min_cut=1e-4),
          cmap=orange_transparent)
pl.savefig("gc_fullres_6_small_withACES12m.png", bbox_inches='tight')
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(meerkat[0].data.squeeze(),
          norm=simple_norm(meerkat[0].data, min_percent=0.1, max_percent=99.9, stretch='log'),
          transform=ax.get_transform(WCS(meerkat[0].header).celestial),
          cmap='gray')
#[Out]# <matplotlib.image.AxesImage at 0x2b771828e6a0>
aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
if os.path.exists('meerkat_projectedto_aces.fits'):
    img_meerkat_ACES = fits.getdata('meerkat_projectedto_aces.fits')
else:
    img_meerkat_ACES,_ = reproject.reproject_interp((meerkat[0].data.squeeze(), WCS(meerkat[0].header).celestial),
                                                  aces12mwcs.celestial, shape_out=aces12m[0].data.shape)
    fits.PrimaryHDU(data=img_meerkat_ACES, header=aces12m[0].header).writeto('meerkat_projectedto_aces.fits')
if os.path.exists('glimpsei4_projectedto_aces.fits'):
    img_glimpsei4_ACES = fits.getdata('glimpsei4_projectedto_aces.fits')
else:
    img_glimpsei4_ACES,_ = reproject.reproject_interp(glimpsei4, aces12mwcs.celestial, shape_out=aces12m[0].data.shape)
    fits.PrimaryHDU(data=img_glimpsei4_ACES, header=aces12m[0].header).writeto('glimpsei4_projectedto_aces.fits')
rgb = np.array([simple_norm(img_meerkat_ACES,   min_percent=1, max_percent=99.95, log_a=4e1, stretch='log')(np.nan_to_num(img_meerkat_ACES)),
                simple_norm(aces12m[0].data.squeeze(),   min_percent=1, max_percent=99.95, log_a=5e1, stretch='log')(np.nan_to_num(aces12m[0].data.squeeze())),
                simple_norm(img_glimpsei4_ACES, min_percent=1, max_percent=99.9, log_a=4e1, stretch='log')(np.nan_to_num(img_glimpsei4_ACES))]).T.swapaxes(0,1)
pl.imshow(rgb[4000:6000,12000:14000,:], origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b76b074d460>
pl.imshow(rgb, origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b76b0556ac0>
img_meerkat_ACES.shape, img_glimpse_ACES.shape, aces12m[0].data.shape
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(meerkat[0].data.squeeze(),
          norm=simple_norm(meerkat[0].data, min_percent=0.1, max_percent=99.9, stretch='log'),
          transform=ax.get_transform(WCS(meerkat[0].header).celestial),
          interpolation='nearest',
          cmap='gray')
#[Out]# <matplotlib.image.AxesImage at 0x2b7718260730>
img_meerkat_ACES.shape, img_glimpsei4_ACES.shape, aces12m[0].data.shape
#[Out]# ((10200, 27800), (10200, 27800), (10200, 27800))
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
ax.set_xlim(240*2, 720*2)
ax.set_ylim(120*2, 360*2)

ax.imshow(meerkat[0].data.squeeze(),
          norm=simple_norm(meerkat[0].data, min_percent=0.1, max_percent=99.9, stretch='log'),
          transform=ax.get_transform(WCS(meerkat[0].header).celestial),
          interpolation='none',
          cmap='gray')
#[Out]# <matplotlib.image.AxesImage at 0x2b7718089af0>
SkyCoord.from_name('M42')
#[Out]# <SkyCoord (ICRS): (ra, dec) in deg
#[Out]#     (83.82, -5.39)>
target_header_orion = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 1920
NAXIS2  =                  960
CTYPE1  = 'RA---MOL'
CRPIX1  =                960.5
CRVAL1  =                83.82
CDELT1  =             -0.16875
CUNIT1  = 'deg     '
CTYPE2  = 'DEC--MOL'
CRPIX2  =                480.5
CRVAL2  =                -5.39
CDELT2  =              0.16875
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
img_HI4PI_orion, footprint = reproject_from_healpix(fn_HI4PI, target_header_orion, field=5)
plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_orion),
                 frame_class=EllipticalFrame)
ax.imshow(img_HI4PI_orion, norm=simple_norm(img_HI4PI_orion, min_percent=1, max_percent=99.99, stretch='log'))
#ax.coords.grid(color='white')
ax.coords['glat'].set_ticklabel(visible=False)
ax.coords['glon'].set_ticklabel(visible=False)
ax.coords['glat'].set_ticks_visible(False)
ax.coords['glon'].set_ticks_visible(False)
img_HI4PI_orion, footprint = reproject_from_healpix(fn_HI4PI,
                                                    target_header_orion,
                                                    field=5)
plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_orion),
                 frame_class=EllipticalFrame)
ax.axis('off')
ax.imshow(img_HI4PI_orion,
          norm=simple_norm(img_HI4PI_orion,
                           min_percent=1,
                           max_percent=99.99,
                           stretch='log'))
#ax.coords.grid(color='white')
ax.coords['ra'].set_ticklabel(visible=False)
ax.coords['dec'].set_ticklabel(visible=False)
ax.coords['ra'].set_ticks_visible(False)
ax.coords['dec'].set_ticks_visible(False)
img_CO21, footprint = reproject_from_healpix(fn_CO21, target_header)
img_CO21 = fix_nans(img_CO21)
img_CO21orion, footprint = reproject_from_healpix(fn_CO21, target_header_orion)
img_CO21orion = fix_nans(img_CO21orion)
img_ThermalDust, footprint = reproject_from_healpix(fn_ThermalDust, target_header)
img_ThermalDustorion, footprint = reproject_from_healpix(fn_ThermalDust, target_header_orion)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PIorion,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PIorion),
                simple_norm(img_CO21orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21orion),
                simple_norm(img_ThermalDustorion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDustorion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)
prect = rect.to_pixel(ax.wcs)
prect.visual['edgecolor'] = 'w'
innergalplot = prect.plot(ax=ax)


orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(209, -15, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_orion.png", bbox_inches='tight')
def h_rot(rgb, rot):
    hsv = rgb_to_hsv(rgb)
    hsv[:,:,0] += rot  # 0.25 = 90/360
    hsv[:,:,0] = hsv[:,:,0] % 1 
    rgb_scaled = hsv_to_rgb(hsv)
    return rgb_scaled

def make_rgb(rgb, basename, hsv_rotation=0, layernames='RGB',
             do_layers=True,
             header=target_header,
             axlims=None, frame_class=EllipticalFrame):
    plt.figure(figsize=(10,5), dpi=200)
    ax = plt.subplot(1,1,1, projection=WCS(header),
                     frame_class=frame_class)
    #ax.coords.grid(color='white')
    try:
        ax.coords['glat'].set_ticklabel(visible=False)
        ax.coords['glon'].set_ticklabel(visible=False)
        ax.coords['glat'].set_ticks_visible(False)
        ax.coords['glon'].set_ticks_visible(False)
    except Exception:
        ax.coords['ra'].set_ticklabel(visible=False)
        ax.coords['dec'].set_ticklabel(visible=False)
        ax.coords['ra'].set_ticks_visible(False)
        ax.coords['dec'].set_ticks_visible(False)
    if do_layers:
        for ind, color in zip((0, 1, 2), (layernames)):
            rgbc = np.zeros_like(rgb)
            rgbc[:, :, ind] = rgb[:, :, ind]
            if hsv_rotation != 0:
                rgbc = h_rot(rgbc, hsv_rotation)
            ax.imshow(rgbc)
            pl.savefig(f'{basename}_{color}.png', bbox_inches='tight', transparent=True)
    if hsv_rotation != 0:
        rgb = h_rot(rgb, hsv_rotation)
    ax.imshow(rgb)
    if axlims is not None:
        ax.axis(axlims)
    pl.savefig(f'{basename}_RGB.png', bbox_inches='tight', transparent=True)
    return ax
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PIorion,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PIorion),
                simple_norm(img_CO21orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21orion),
                simple_norm(img_ThermalDustorion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDustorion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)
prect = rect.to_pixel(ax.wcs)
prect.visual['edgecolor'] = 'w'
innergalplot = prect.plot(ax=ax)


orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(209, -15, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_orion.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PIorion),
                simple_norm(img_CO21orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21orion),
                simple_norm(img_ThermalDustorion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDustorion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)
prect = rect.to_pixel(ax.wcs)
prect.visual['edgecolor'] = 'w'
innergalplot = prect.plot(ax=ax)


orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(209, -15, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_orion.png", bbox_inches='tight')
img_HI4PI, footprint = reproject_from_healpix(fn_HI4PI, target_header, field=5)
img_HI4PIorion, footprint = reproject_from_healpix(fn_HI4PI, target_header_orion, field=5)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PIorion),
                simple_norm(img_CO21orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21orion),
                simple_norm(img_ThermalDustorion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDustorion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)
prect = rect.to_pixel(ax.wcs)
prect.visual['edgecolor'] = 'w'
innergalplot = prect.plot(ax=ax)


orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(209, -15, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


pl.savefig("HI-CO-Dust_m0.35_orion_RGB_labeled_orion.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PIorion),
                simple_norm(img_CO21orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21orion),
                simple_norm(img_ThermalDustorion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDustorion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(209, -15, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


pl.savefig("HI-CO-Dust_m0.35_orion_RGB_labeled_orion.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PIorion),
                simple_norm(img_CO21orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21orion),
                simple_norm(img_ThermalDustorion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDustorion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(83.82, -5, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


pl.savefig("HI-CO-Dust_m0.35_orion_RGB_labeled_orion.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PIorion),
                simple_norm(img_CO21orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21orion),
                simple_norm(img_ThermalDustorion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDustorion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(83.82, -3, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_orion_RGB_labeled_orion.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PIorion),
                simple_norm(img_CO21orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21orion),
                simple_norm(img_ThermalDustorion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDustorion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(83.82, -2, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_orion_RGB_labeled_orion.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,      min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PIorion),
                simple_norm(img_CO21orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21orion),
                simple_norm(img_ThermalDustorion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDustorion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(83.82, -2, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
ax.axis([80,90,-10,0])

#pl.savefig("HI-CO-Dust_m0.35_orion_RGB_labeled_orion.png", bbox_inches='tight')
#[Out]# (80.0, 90.0, -10.0, 0.0)
img_CO21, footprint = reproject_from_healpix(fn_CO21, target_header)
img_CO21 = fix_nans(img_CO21)
img_CO21_orion, footprint = reproject_from_healpix(fn_CO21, target_header_orion)
img_CO21_orion = fix_nans(img_CO21_orion)
img_ThermalDust, footprint = reproject_from_healpix(fn_ThermalDust, target_header)
img_ThermalDust_orion, footprint = reproject_from_healpix(fn_ThermalDust, target_header_orion)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_orion),
                simple_norm(img_CO21_orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_orion),
                simple_norm(img_ThermalDust_orion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_orion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(83.82, -2, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

#pl.savefig("HI-CO-Dust_m0.35_orion_RGB_labeled_orion.png", bbox_inches='tight')
ax.transData.transform([80,90,-10,0])
#[Out]# array([333.30989583, 196.17447917, 262.52864583, 125.39322917])
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_orion),
                simple_norm(img_CO21_orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_orion),
                simple_norm(img_ThermalDust_orion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_orion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(83.82, -2, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
print(ax.axis())
ax.axis(ax.transData.transform([80,90,-10,0]))
#pl.savefig("HI-CO-Dust_m0.35_orion_RGB_labeled_orion.png", bbox_inches='tight')
#[Out]# (333.30989583333337,
#[Out]#  196.17447916666669,
#[Out]#  262.52864583333337,
#[Out]#  125.39322916666667)
ax.transData.transform([80,-10])
#[Out]# array([2042.09941132, 1625.40837448])
ax.transData.transform([80])
ax.transData.transform([80,-10])
#[Out]# array([2042.09941132, 1625.40837448])
ax.transData.transform([10,10])
#[Out]# array([2427.48490315, 1515.29823395])
ax.transData.transform([1920])
ax.transData.transform([1920,960])
#[Out]# array([-8088.0335169 , -3714.93344094])
ax.transData.transform([80, 0])
#[Out]# array([2042.09941132, 1570.35330422])
ax.transData.transform([0, 0])
#[Out]# array([2482.53997341, 1570.35330422])
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_orion),
                simple_norm(img_CO21_orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_orion),
                simple_norm(img_ThermalDust_orion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_orion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(83.82, -2, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
print(ax.axis())
ax.axis([900,1020,440,520])
#pl.savefig("HI-CO-Dust_m0.35_orion_RGB_labeled_orion.png", bbox_inches='tight')
#[Out]# (900.0, 1020.0, 440.0, 520.0)
target_header_oricloud = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 3840
NAXIS2  =                  960
CTYPE1  = 'RA---TAN'
CRPIX1  =                83.82
CRVAL1  =                  0.0
CDELT1  =                -0.05
CUNIT1  = 'deg     '
CTYPE2  = 'DEC--TAN'
CRPIX2  =                480.5
CRVAL2  =                -5.38
CDELT2  =                 0.05
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_oricloud,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21_oricloud,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust_oricloud, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_oricloud', -0.35,
              header=target_header_oricloud,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(83.82, -2, "oricloud", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
#pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
target_header_oricloud = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 3840
NAXIS2  =                  960
CTYPE1  = 'RA---TAN'
CRPIX1  =                83.82
CRVAL1  =                  0.0
CDELT1  =                -0.05
CUNIT1  = 'deg     '
CTYPE2  = 'DEC--TAN'
CRPIX2  =                480.5
CRVAL2  =                -5.38
CDELT2  =                 0.05
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
img_HI4PI_oricloud, footprint = reproject_from_healpix(fn_HI4PI, target_header_oricloud, field=5)
img_ThermalDust_oricloud, footprint = reproject_from_healpix(fn_ThermalDust, target_header_oricloud)
img_CO21_oricloud, footprint = reproject_from_healpix(fn_CO21, target_header_oricloud)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_oricloud,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21_oricloud,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust_oricloud, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_oricloud', -0.35,
              header=target_header_oricloud,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(83.82, -2, "oricloud", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
#pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_oricloud,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21_oricloud,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust_oricloud, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(83.82, -2, "oricloud", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
#pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_oricloud,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21_oricloud,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust_oricloud, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
#oriplot = poricloudrect.plot(ax=ax)

#oritext = ax.text(83.82, -2, "oricloud", transform=ax.get_transform('world'),
#        color='w', horizontalalignment='center')
#pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
target_header_oricloud = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 3840
NAXIS2  =                  960
CTYPE1  = 'RA---TAN'
CRPIX1  =               1920.5
CRVAL1  =                83.82
CDELT1  =                -0.05
CUNIT1  = 'deg     '
CTYPE2  = 'DEC--TAN'
CRPIX2  =                480.5
CRVAL2  =                -5.39
CDELT2  =                 0.05
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
img_HI4PI_oricloud, footprint = reproject_from_healpix(fn_HI4PI, target_header_oricloud, field=5)
img_ThermalDust_oricloud, footprint = reproject_from_healpix(fn_ThermalDust, target_header_oricloud)
img_CO21_oricloud, footprint = reproject_from_healpix(fn_CO21, target_header_oricloud)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_oricloud,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21_oricloud,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust_oricloud, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
#oriplot = poricloudrect.plot(ax=ax)

#oritext = ax.text(83.82, -2, "oricloud", transform=ax.get_transform('world'),
#        color='w', horizontalalignment='center')
#pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
target_header_oricloud = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 1920
NAXIS2  =                 1920
CTYPE1  = 'RA---TAN'
CRPIX1  =                960.5
CRVAL1  =                83.82
CDELT1  =                -0.05
CUNIT1  = 'deg     '
CTYPE2  = 'DEC--TAN'
CRPIX2  =                960.5
CRVAL2  =                -5.39
CDELT2  =                 0.05
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
img_HI4PI_oricloud, footprint = reproject_from_healpix(fn_HI4PI, target_header_oricloud, field=5)
img_ThermalDust_oricloud, footprint = reproject_from_healpix(fn_ThermalDust, target_header_oricloud)
img_CO21_oricloud, footprint = reproject_from_healpix(fn_CO21, target_header_oricloud)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_oricloud,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21_oricloud,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust_oricloud, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=5*u.deg,
    height=5*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(83.82, -2, "oricloud", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_oricloud,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21_oricloud,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust_oricloud, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=10*u.deg,
    height=10*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(83.82, 2, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,      min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PIorion),
                simple_norm(img_CO21orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21orion),
                simple_norm(img_ThermalDust_orion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_orion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=10*u.deg,
    height=10*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(83.82, 2, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_orion_RGB_labeled_orion.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_oricloud,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21_oricloud,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust_oricloud, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(83.82, 5, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI_orion,      min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PIorion),
                simple_norm(img_CO21orion,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21orion),
                simple_norm(img_ThermalDust_orion, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_orion)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35_orion', -0.35,
              header=target_header_orion,
              layernames=('HI', 'CO', 'Dust'), do_layers=False)

orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(83.82, 5, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_orion_RGB_labeled_orion.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(83.82, 5, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(85, 4, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(82, 4, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(80, 4, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35', -0.35, layernames=('HI', 'CO', 'Dust'), do_layers=False)
prect = rect.to_pixel(ax.wcs)
prect.visual['edgecolor'] = 'w'
innergalplot = prect.plot(ax=ax)

pl.savefig("HI-CO-Dust_m0.35_RGB_innergal_zoombox.png", bbox_inches='tight')

innergaltext = ax.text(0, 25, "Galactic Plane", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

cmzrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(0*u.deg, 0*u.deg, frame='galactic'),
    width=12*u.deg,
    height=4.8*u.deg,
)
pcmzrect = cmzrect.to_pixel(ax.wcs)
pcmzrect.visual['edgecolor'] = 'w'
cmzplot = pcmzrect.plot(ax=ax)

cmztext = ax.text(0, 5, "Central Molecular Zone", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(209, -10, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_zones.png", bbox_inches='tight')

innergalplot.set_visible(False)
cmzplot.set_visible(False)
innergaltext.set_visible(False)
cmztext.set_visible(False)

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_orion.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35', -0.35, layernames=('HI', 'CO', 'Dust'), do_layers=False)
prect = rect.to_pixel(ax.wcs)
prect.visual['edgecolor'] = 'w'
innergalplot = prect.plot(ax=ax)

pl.savefig("HI-CO-Dust_m0.35_RGB_innergal_zoombox.png", bbox_inches='tight')

innergaltext = ax.text(0, 25, "Galactic Plane", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

cmzrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(0*u.deg, 0*u.deg, frame='galactic'),
    width=12*u.deg,
    height=4.8*u.deg,
)
pcmzrect = cmzrect.to_pixel(ax.wcs)
pcmzrect.visual['edgecolor'] = 'w'
cmzplot = pcmzrect.plot(ax=ax)

cmztext = ax.text(0, 5, "Central Molecular Zone", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)

oritext = ax.text(209, -7, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_zones.png", bbox_inches='tight')

innergalplot.set_visible(False)
cmzplot.set_visible(False)
innergaltext.set_visible(False)
cmztext.set_visible(False)

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_orion.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(80, 4, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
ax.axis([480,1440,480,1440])
pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight')
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

oricloudrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
poricloudrect = oricloudrect.to_pixel(ax.wcs)
poricloudrect.visual['edgecolor'] = 'w'
oriplot = poricloudrect.plot(ax=ax)

oritext = ax.text(80, 4, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')
ax.axis([480,1440,480,1440])
pl.savefig("HI-CO-Dust_m0.35_oricloud_RGB_labeled_oricloud.png", bbox_inches='tight',
           pad_inches=0)
rgb = np.array(PIL.Image.open('https://keflavich.github.io/talks/assets_orion/Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'))[::-1, :, :]
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
rgb = np.array(PIL.Image.open(trapezium))[::-1, :, :]
pl.imshow(rgb)
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
pl.imshow(rgb)
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
    print(dl)
rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
pl.imshow(rgb)
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
    shutil.move(dl, fn_trapezium)
rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b76b168ad90>
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
    shutil.move(dl, fn_trapezium)
rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
pl.imshow(rgb, origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b76b16b48e0>
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
    shutil.move(dl, fn_trapezium)
rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
pl.imshow(rgb, origin='lower')
avm = pyavm.AVM.from_image(fn_trapezium)
avm.wcs
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
    shutil.move(dl, fn_trapezium)
rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
pl.imshow(rgb, origin='lower')
avm = pyavm.AVM.from_image(fn_trapezium)
avm.to_wcs()
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
    shutil.move(dl, fn_trapezium)
rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
pl.imshow(rgb, origin='lower')
avm = pyavm.AVM.from_image(fn_trapezium)
avm.to_wcs()
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
#if not os.path.exists(fn_trapezium):
dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
shutil.move(dl, fn_trapezium)
rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
pl.imshow(rgb, origin='lower')
avm = pyavm.AVM.from_image(fn_trapezium)
avm.to_wcs()
get_ipython().run_line_magic('rm', 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png')
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
    shutil.move(dl, fn_trapezium)
rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
pl.imshow(rgb, origin='lower')
avm = pyavm.AVM.from_image(fn_trapezium)
avm.to_wcs()
#[Out]# WCS Keywords
#[Out]# 
#[Out]# Number of WCS axes: 2
#[Out]# CTYPE : 'RA---TAN'  'DEC--TAN'  
#[Out]# CRVAL : 83.812572  -5.3628206  
#[Out]# CRPIX : 4375.0  5625.0  
#[Out]# PC1_1 PC1_2  : 1.0  0.0  
#[Out]# PC2_1 PC2_2  : 0.0  1.0  
#[Out]# CDELT : -5.5e-06  5.5e-06  
#[Out]# NAXIS : 0  0
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
    shutil.move(dl, fn_trapezium)
rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])
pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])

print("ax.wcs.world_axis_physical_types[0].split(".")[1]", ax.wcs.world_axis_physical_types[0].split(".")[1])

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])

print("ax.wcs.world_axis_physical_types[0].split('.')[1]", ax.wcs.world_axis_physical_types[0].split(".")[1])

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])

print("ax.wcs.world_axis_physical_types[0].split('.')[1]", ax.wcs.world_axis_physical_types[0])

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
from mpl_toolkits.axes_grid1.inset_locator import TransformedBbox, BboxPatch, BboxConnector, Path
from matplotlib.transforms import Bbox
from matplotlib.patches import Polygon, PathPatch, ConnectionPatch

def mark_inset_generic(axins, parent_ax, data, loc1=1, loc2=3,
                       loc1in=None, loc2in=None, edgecolor='b', zorder1=100, zorder2=100, polyzorder=1):
    bl = axins.wcs.pixel_to_world(0, 0)
    br = axins.wcs.pixel_to_world(data.shape[1], 0)
    tl = axins.wcs.pixel_to_world(0, data.shape[0]) # x,y not y,x
    tr = axins.wcs.pixel_to_world(data.shape[1], data.shape[0]) # x,y not y,x
    
    fig = parent_ax.get_figure()
    
    frame = parent_ax.wcs.wcs.radesys.lower()
    frame = ax.wcs.world_axis_physical_types[0].split(".")[1]
    if frame == 'eq':
        frame = 'icrs'
    
    blt = bl.transform_to(frame)
    brt = br.transform_to(frame)
    tlt = tl.transform_to(frame)
    trt = tr.transform_to(frame)
    xys = [parent_ax.wcs.wcs_world2pix([[crd.spherical.lon.deg,
                                         crd.spherical.lat.deg]],0)[0]
           for crd in (trt, tlt, blt, brt, trt)]
    
    markinkwargs = dict(fc='none', ec=edgecolor)
    ppoly = Polygon(xys, fill=False, zorder=polyzorder, **markinkwargs)
    parent_ax.add_patch(ppoly)
    
    corners = parent_ax.transData.inverted().transform(xys)
    
    axcorners = [(1,1), (0,1), (0,0), (1,0)]
    corners = [(crd.spherical.lon.deg, crd.spherical.lat.deg)
               for crd in (trt, tlt, blt, brt)]
    
    if loc1in is None:
        loc1in = loc1
    if loc2in is None:
        loc2in = loc2
    
    con1 = ConnectionPatch(xyA=axcorners[loc1-1], coordsA='axes fraction', axesA=axins,
                           xyB=corners[loc1in-1], coordsB=parent_ax.get_transform('world'), axesB=parent_ax,
                           linestyle='-', color=edgecolor, zorder=zorder1)
    con2 = ConnectionPatch(xyA=axcorners[loc2-1], coordsA='axes fraction', axesA=axins,
                           xyB=corners[loc2in-1], coordsB=parent_ax.get_transform('world'), axesB=parent_ax,
                           linestyle='-', color=edgecolor, zorder=zorder2)    
    fig.add_artist(con1)
    fig.add_artist(con2)
    
    return con1, con2
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])

print("ax.wcs.world_axis_physical_types[0].split('.')[1]", ax.wcs.world_axis_physical_types[0])

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
from mpl_toolkits.axes_grid1.inset_locator import TransformedBbox, BboxPatch, BboxConnector, Path
from matplotlib.transforms import Bbox
from matplotlib.patches import Polygon, PathPatch, ConnectionPatch

def mark_inset_generic(axins, parent_ax, data, loc1=1, loc2=3,
                       loc1in=None, loc2in=None, edgecolor='b', zorder1=100, zorder2=100, polyzorder=1):
    bl = axins.wcs.pixel_to_world(0, 0)
    br = axins.wcs.pixel_to_world(data.shape[1], 0)
    tl = axins.wcs.pixel_to_world(0, data.shape[0]) # x,y not y,x
    tr = axins.wcs.pixel_to_world(data.shape[1], data.shape[0]) # x,y not y,x
    
    fig = parent_ax.get_figure()
    
    #frame = parent_ax.wcs.wcs.radesys.lower()
    #frame = ax.wcs.world_axis_physical_types[0].split(".")[1]
    frame = wcs.utils.wcs_to_celestial_frame(ax.wcs)
    
    blt = bl.transform_to(frame)
    brt = br.transform_to(frame)
    tlt = tl.transform_to(frame)
    trt = tr.transform_to(frame)
    xys = [parent_ax.wcs.wcs_world2pix([[crd.spherical.lon.deg,
                                         crd.spherical.lat.deg]],0)[0]
           for crd in (trt, tlt, blt, brt, trt)]
    
    markinkwargs = dict(fc='none', ec=edgecolor)
    ppoly = Polygon(xys, fill=False, zorder=polyzorder, **markinkwargs)
    parent_ax.add_patch(ppoly)
    
    corners = parent_ax.transData.inverted().transform(xys)
    
    axcorners = [(1,1), (0,1), (0,0), (1,0)]
    corners = [(crd.spherical.lon.deg, crd.spherical.lat.deg)
               for crd in (trt, tlt, blt, brt)]
    
    if loc1in is None:
        loc1in = loc1
    if loc2in is None:
        loc2in = loc2
    
    con1 = ConnectionPatch(xyA=axcorners[loc1-1], coordsA='axes fraction', axesA=axins,
                           xyB=corners[loc1in-1], coordsB=parent_ax.get_transform('world'), axesB=parent_ax,
                           linestyle='-', color=edgecolor, zorder=zorder1)
    con2 = ConnectionPatch(xyA=axcorners[loc2-1], coordsA='axes fraction', axesA=axins,
                           xyB=corners[loc2in-1], coordsB=parent_ax.get_transform('world'), axesB=parent_ax,
                           linestyle='-', color=edgecolor, zorder=zorder2)    
    fig.add_artist(con1)
    fig.add_artist(con2)
    
    return con1, con2
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
from mpl_toolkits.axes_grid1.inset_locator import TransformedBbox, BboxPatch, BboxConnector, Path
from astropy import wcs
from matplotlib.transforms import Bbox
from matplotlib.patches import Polygon, PathPatch, ConnectionPatch

def mark_inset_generic(axins, parent_ax, data, loc1=1, loc2=3,
                       loc1in=None, loc2in=None, edgecolor='b', zorder1=100, zorder2=100, polyzorder=1):
    bl = axins.wcs.pixel_to_world(0, 0)
    br = axins.wcs.pixel_to_world(data.shape[1], 0)
    tl = axins.wcs.pixel_to_world(0, data.shape[0]) # x,y not y,x
    tr = axins.wcs.pixel_to_world(data.shape[1], data.shape[0]) # x,y not y,x
    
    fig = parent_ax.get_figure()
    
    #frame = parent_ax.wcs.wcs.radesys.lower()
    #frame = ax.wcs.world_axis_physical_types[0].split(".")[1]
    frame = wcs.utils.wcs_to_celestial_frame(ax.wcs)
    
    blt = bl.transform_to(frame)
    brt = br.transform_to(frame)
    tlt = tl.transform_to(frame)
    trt = tr.transform_to(frame)
    xys = [parent_ax.wcs.wcs_world2pix([[crd.spherical.lon.deg,
                                         crd.spherical.lat.deg]],0)[0]
           for crd in (trt, tlt, blt, brt, trt)]
    
    markinkwargs = dict(fc='none', ec=edgecolor)
    ppoly = Polygon(xys, fill=False, zorder=polyzorder, **markinkwargs)
    parent_ax.add_patch(ppoly)
    
    corners = parent_ax.transData.inverted().transform(xys)
    
    axcorners = [(1,1), (0,1), (0,0), (1,0)]
    corners = [(crd.spherical.lon.deg, crd.spherical.lat.deg)
               for crd in (trt, tlt, blt, brt)]
    
    if loc1in is None:
        loc1in = loc1
    if loc2in is None:
        loc2in = loc2
    
    con1 = ConnectionPatch(xyA=axcorners[loc1-1], coordsA='axes fraction', axesA=axins,
                           xyB=corners[loc1in-1], coordsB=parent_ax.get_transform('world'), axesB=parent_ax,
                           linestyle='-', color=edgecolor, zorder=zorder1)
    con2 = ConnectionPatch(xyA=axcorners[loc2-1], coordsA='axes fraction', axesA=axins,
                           xyB=corners[loc2in-1], coordsB=parent_ax.get_transform('world'), axesB=parent_ax,
                           linestyle='-', color=edgecolor, zorder=zorder2)    
    fig.add_artist(con1)
    fig.add_artist(con2)
    
    return con1, con2
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright_fullsize.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
    shutil.move(dl, fn_trapezium)
fn_orion4d_cont = "Orion4D_ISF_Continuum_CLEAN_b0.5_30kltaper_DEEP.image.pbcor.fits"
if 
    dl = download_file("https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/I1GQER/DHGPFZ")
    shutil.move(dl, fn_orion4d_cont)
fn_orion4d_cont = "Orion4D_ISF_Continuum_CLEAN_b0.5_30kltaper_DEEP.image.pbcor.fits"
if not os.path.exists(fn_orion4d_cont):
    dl = download_file("https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/I1GQER/DHGPFZ")
    shutil.move(dl, fn_orion4d_cont)
pl.imshow(fits.getdata(fn_orion4d_cont))
pl.imshow(fits.getdata(fn_orion4d_cont).squeeze())
#[Out]# <matplotlib.image.AxesImage at 0x2b76a89e4a30>
pl.figure(dpi=200)
pl.imshow(fits.getdata(fn_orion4d_cont).squeeze(), origin='lower')
#[Out]# <matplotlib.image.AxesImage at 0x2b76a8d1d640>
pl.figure(dpi=200)
pl.imshow(fits.getdata(fn_orion4d_cont).squeeze(), origin='lower', vmin=0, vmax=0.01)
#[Out]# <matplotlib.image.AxesImage at 0x2b76b022b1c0>
pl.figure(dpi=200)
pl.imshow(fits.getdata(fn_orion4d_cont).squeeze(), origin='lower', vmin=0, vmax=0.001)
#[Out]# <matplotlib.image.AxesImage at 0x2b76a8d2ddf0>
fn_orion_mustang = "MUSTANG_OrionClean9.0-24nov08.fits"
if not os.path.exists(fn_orion_mustang):
    dl = download_file("https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/LZELK1/MZNCT1")
    shutil.move(dl, fn_orion_mustang)
pl.imshow(fits.getdata(fn_orion_mustang))
pl.imshow(fits.getdata(fn_orion_mustang).squeeze())
#[Out]# <matplotlib.image.AxesImage at 0x2b76b1395070>
fn_carmaorion_12co = "mom0_12co_pix_2_Tmb.fits"
fn_carmaorion_13co = "mom0_13co_pix_2_Tmb.fits"

if not os.path.exists(fn_carmaorion_12co):
    dl=download_file("https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/6Q26PN/MRUINN")
    shutil.move(dl, fn_carmaorion_12co)
    dl=download_file("https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/6Q26PN/AIYBES")
    shutil.move(dl, fn_carmaorion_13co)
pl.imshow(fits.getdata(fn_carmaorion_12co).squeeze())
#[Out]# <matplotlib.image.AxesImage at 0x2b76b12c0940>
target_header_omc = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 1920
NAXIS2  =                 1920
CTYPE1  = 'RA---TAN'
CRPIX1  =                960.5
CRVAL1  =                83.82
CDELT1  =               -0.001
CUNIT1  = 'deg     '
CTYPE2  = 'DEC--TAN'
CRPIX2  =                960.5
CRVAL2  =                -5.39
CDELT2  =                0.001
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
img_carmaori_omc, footprint = reproject.reproject_interp(fn_carmaorion_12co, target_header_omc)
pl.imshow(img_carmaori_omc)
img_carmaori_omc, footprint = reproject.reproject_interp((fits.getdata(fn_carmaorion_12co).squeeze(), fits.getheader(fn_carmaorion_12co)), target_header_omc)
pl.imshow(img_carmaori_omc)
img_carmaori_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_12co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_12co)).celestial),
    target_header_omc)
pl.imshow(img_carmaori_omc)
#[Out]# <matplotlib.image.AxesImage at 0x2b76b10bbfa0>
img_carmaori_12co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_12co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_12co)).celestial),
    target_header_omc)

img_carmaori_13co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_13co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_13co)).celestial),
    target_header_omc)

img_mustang_orion_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_mustang_orion).squeeze(),
     WCS(fits.getheader(fn_mustang_orion)).celestial),
    target_header_omc)
img_carmaori_12co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_12co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_12co)).celestial),
    target_header_omc)

img_carmaori_13co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_13co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_13co)).celestial),
    target_header_omc)

img_orion_mustang_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_orion_mustang).squeeze(),
     WCS(fits.getheader(fn_orion_mustang)).celestial),
    target_header_omc)
pl.imshow(img_carmaori_omc)
#[Out]# <matplotlib.image.AxesImage at 0x2b76b140fd30>
pl.imshow(img_orion_mustang_omc)
#[Out]# <matplotlib.image.AxesImage at 0x2b76b12909a0>
target_header_omc = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 1920
NAXIS2  =                 1920
CTYPE1  = 'RA---TAN'
CRPIX1  =                960.5
CRVAL1  =                83.82
CDELT1  =              -0.0005
CUNIT1  = 'deg     '
CTYPE2  = 'DEC--TAN'
CRPIX2  =                960.5
CRVAL2  =                -5.39
CDELT2  =               0.0005
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
fn_carmaorion_12co = "mom0_12co_pix_2_Tmb.fits"
fn_carmaorion_13co = "mom0_13co_pix_2_Tmb.fits"

if not os.path.exists(fn_carmaorion_12co):
    dl=download_file("https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/6Q26PN/MRUINN")
    shutil.move(dl, fn_carmaorion_12co)
    dl=download_file("https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/6Q26PN/AIYBES")
    shutil.move(dl, fn_carmaorion_13co)
fn_orion_mustang = "MUSTANG_OrionClean9.0-24nov08.fits"
if not os.path.exists(fn_orion_mustang):
    dl = download_file("https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/LZELK1/MZNCT1")
    shutil.move(dl, fn_orion_mustang)
img_carmaori_12co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_12co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_12co)).celestial),
    target_header_omc)

img_carmaori_13co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_13co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_13co)).celestial),
    target_header_omc)

img_orion_mustang_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_orion_mustang).squeeze(),
     WCS(fits.getheader(fn_orion_mustang)).celestial),
    target_header_omc)
fn_orion_bolocam = 'orionfruitawf2.fits'
img_carmaori_12co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_12co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_12co)).celestial),
    target_header_omc)

img_carmaori_13co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_13co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_13co)).celestial),
    target_header_omc)

img_orion_mustang_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_orion_mustang).squeeze(),
     WCS(fits.getheader(fn_orion_mustang)).celestial),
    target_header_omc)

img_orion_bolocam_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_orion_bolocam).squeeze(),
     WCS(fits.getheader(fn_orion_bolocam)).celestial),
    target_header_omc)
pl.imshow(img_carmaori_omc)
#[Out]# <matplotlib.image.AxesImage at 0x2b76c255a880>
pl.imshow(img_orion_mustang_omc)
#[Out]# <matplotlib.image.AxesImage at 0x2b76c26b5af0>
pl.imshow(img_orion_bolocam_omc)
#[Out]# <matplotlib.image.AxesImage at 0x2b76c2535490>
target_header_omc = fits.Header.fromstring("""
NAXIS   =                    2
NAXIS1  =                 1920
NAXIS2  =                 1920
CTYPE1  = 'RA---TAN'
CRPIX1  =                960.5
CRVAL1  =                83.82
CDELT1  =              -0.0005
CUNIT1  = 'deg     '
CTYPE2  = 'DEC--TAN'
CRPIX2  =                960.5
CRVAL2  =                -5.39
CDELT2  =               0.0005
CUNIT2  = 'deg     '
COORDSYS= 'icrs    '
""", sep='\n')
fn_carmaorion_12co = "mom0_12co_pix_2_Tmb.fits"
fn_carmaorion_13co = "mom0_13co_pix_2_Tmb.fits"

if not os.path.exists(fn_carmaorion_12co):
    dl=download_file("https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/6Q26PN/MRUINN")
    shutil.move(dl, fn_carmaorion_12co)
    dl=download_file("https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/6Q26PN/AIYBES")
    shutil.move(dl, fn_carmaorion_13co)
fn_orion_mustang = "MUSTANG_OrionClean9.0-24nov08.fits"
if not os.path.exists(fn_orion_mustang):
    dl = download_file("https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/LZELK1/MZNCT1")
    shutil.move(dl, fn_orion_mustang)
fn_orion_bolocam = 'orionfruitawf2.fits'
img_carmaori_12co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_12co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_12co)).celestial),
    target_header_omc)

img_carmaori_13co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_13co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_13co)).celestial),
    target_header_omc)

img_orion_mustang_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_orion_mustang).squeeze(),
     WCS(fits.getheader(fn_orion_mustang)).celestial),
    target_header_omc)

img_orion_bolocam_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_orion_bolocam).squeeze(),
     WCS(fits.getheader(fn_orion_bolocam)).celestial),
    target_header_omc)
pl.imshow(img_carmaori_omc)
#[Out]# <matplotlib.image.AxesImage at 0x2b76c27b2d00>
pl.imshow(img_orion_mustang_omc)
#[Out]# <matplotlib.image.AxesImage at 0x2b76c28bb340>
pl.imshow(img_orion_bolocam_omc)
#[Out]# <matplotlib.image.AxesImage at 0x2b76c291ba00>
1920*0.0005
#[Out]# 0.96
pl.imshow(img_carmaori_12co_omc)
#[Out]# <matplotlib.image.AxesImage at 0x2b76c2a50520>
rgb = np.array([simple_norm(img_carmaori_12co_omc,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b76c23ea700>
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b76c244e070>
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=0.1, max_percent=99.90, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b76d23f5c10>
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=0.1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b76d2432e20>
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=0.1, max_percent=99.5, log_a=5e3, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b76d2490070>
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=0.1, max_percent=99.5, log_a=1e3, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b76d24f0280>
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=0.1, max_percent=99.0, log_a=1e3, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b76d2551490>
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=0.1, max_percent=99.0, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b76d25b06a0>
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.0, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b76d26108b0>
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.0, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
pl.imshow(img_orion_bolocam_omc,
          norm=simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.0,
                            log_a=5e2, stretch='log'))
#[Out]# <matplotlib.image.AxesImage at 0x2b76d2cfb8e0>
pl.imshow(img_orion_bolocam_omc,
          norm=simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5,
                            log_a=5e2, stretch='log'))
#[Out]# <matplotlib.image.AxesImage at 0x2b76d2750fd0>
img_orion_bolocam_omc[img_orion_bolocam_omc<0] = 0
pl.imshow(img_orion_bolocam_omc,
          norm=simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5,
                            log_a=5e2, stretch='log'))
#[Out]# <matplotlib.image.AxesImage at 0x2b76d27f5a60>
img_carmaori_12co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_12co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_12co)).celestial),
    target_header_omc)

img_carmaori_13co_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_carmaorion_13co).squeeze(),
     WCS(fits.getheader(fn_carmaorion_13co)).celestial),
    target_header_omc)

img_orion_mustang_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_orion_mustang).squeeze(),
     WCS(fits.getheader(fn_orion_mustang)).celestial),
    target_header_omc)

img_orion_bolocam_omc, footprint = reproject.reproject_interp(
    (fits.getdata(fn_orion_bolocam).squeeze(),
     WCS(fits.getheader(fn_orion_bolocam)).celestial),
    target_header_omc)
img_orion_bolocam_omc[img_orion_bolocam_omc<-0.5] = 0
pl.imshow(img_orion_bolocam_omc,
          norm=simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5,
                            log_a=5e2, stretch='log'))
#[Out]# <matplotlib.image.AxesImage at 0x2b76d2b5c1f0>
img_orion_bolocam_omc[img_orion_bolocam_omc<-0.5] = 0
pl.imshow(img_orion_bolocam_omc,
          norm=simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.9,
                            log_a=5e2, stretch='log'))
#[Out]# <matplotlib.image.AxesImage at 0x2b76d29889a0>
img_orion_bolocam_omc[img_orion_bolocam_omc<-0.5] = 0
pl.imshow(img_orion_bolocam_omc,
          norm=simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.95,
                            log_a=5e2, stretch='log'))
#[Out]# <matplotlib.image.AxesImage at 0x2b76d2d0d2b0>
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.95,
                            log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
pl.imshow(rgb)
#[Out]# <matplotlib.image.AxesImage at 0x2b76d2a0beb0>
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.9, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.85, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='k')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.85, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='orange')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 1, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='orange')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.8, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='orange')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='orange')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb_scaled)
ax.axis('off')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='orange')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='orange')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='purple')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='purple')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright2.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
    shutil.move(dl, fn_trapezium)
fn_trapezium = 'Trapezium_GEMS_mosaic_redblueorange_normed_small_contrast_bright.png'
if not os.path.exists(fn_trapezium):
    dl = download_file(f'https://keflavich.github.io/talks/assets_orion/{fn_trapezium}')
    shutil.move(dl, fn_trapezium)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])


rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
get_ipython().run_line_magic('rm', '$fn_trapezium')
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])
ax.axis([720,1160,720,1160])


rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.8, 0.0, 0.3, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='w')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])
ax.axis([720,1160,720,1160])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.coords['ra'].set_ticklabel(visible=False)
axins.coords['dec'].set_ticklabel(visible=False)
axins.coords['ra'].set_ticks_visible(False)
axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
# axins.coords['ra'].set_ticklabel(visible=False)
# axins.coords['dec'].set_ticklabel(visible=False)
# axins.coords['ra'].set_ticks_visible(False)
# axins.coords['dec'].set_ticks_visible(False)

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
#ax.axis('off')
ax.axis([480, 1440, 480, 1440])

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
#axins.axis('off')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

#ax.axis([600,1280,600,1280])
#ax.axis([720,1160,720,1160])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI_oricloud),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21_oricloud),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust_oricloud)]).T.swapaxes(0,1)

hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=WCS(target_header_oricloud),)
ax.imshow(rgb_scaled)
ax.axis('off')

ax.axis([600,1280,600,1280])
ax.axis([720,1160,720,1160])
ax.axis([800,1080,800,1080])


rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
theta1c = SkyCoord.from_name('Theta 1c Orionis')
theta1c
theta1c = SkyCoord.from_name('name Theta 1c Orionis')
theta1c
theta1c = SkyCoord.from_name('* tet01 Ori C')
theta1c
#[Out]# <SkyCoord (ICRS): (ra, dec) in deg
#[Out]#     (83.81860957, -5.3897005)>
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()
ww = WCS(fits.Header.fromstring(trapezium_header), sep='\n')

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
trapezium_header = """
WCSAXES =                    2 / Number of coordinate axes
CRPIX1  =             780.4109 / Pixel coordinate of reference point
CRPIX2  =             989.4288 / Pixel coordinate of reference point
PC1_1   =             -3.1E-05 / Coordinate transformation matrix element
PC2_2   =              3.1E-05 / Coordinate transformation matrix element
CDELT1  =                  1.0 / [deg] Coordinate increment at reference point
CDELT2  =                  1.0 / [deg] Coordinate increment at reference point
CUNIT1  = 'deg'                / Units of coordinate increment and value
CUNIT2  = 'deg'                / Units of coordinate increment and value
CTYPE1  = 'RA---TAN'           / Right ascension, gnomonic projection
CTYPE2  = 'DEC--TAN'           / Declination, gnomonic projection
CRVAL1  =             83.81251 / [deg] Coordinate value at reference point
CRVAL2  =           -5.3631591 / [deg] Coordinate value at reference point
LONPOLE =                180.0 / [deg] Native longitude of celestial pole
LATPOLE =           -5.3631591 / [deg] Native latitude of celestial pole
MJDREF  =                  0.0 / [d] MJD of fiducial time
RADESYS = 'FK5'                / Equatorial coordinate system
EQUINOX =               2000.0 / [yr] Equinox of equatorial coordinates
"""
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()
ww = WCS(fits.Header.fromstring(trapezium_header), sep='\n')

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()
ww = WCS(fits.Header.fromstring(trapezium_header, sep='\n'))

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
trapezium_header = """
WCSAXES =                    2 / Number of coordinate axes
CRPIX1  =             700.4109 / Pixel coordinate of reference point
CRPIX2  =             989.4288 / Pixel coordinate of reference point
PC1_1   =             -3.1E-05 / Coordinate transformation matrix element
PC2_2   =              3.1E-05 / Coordinate transformation matrix element
CDELT1  =                  1.0 / [deg] Coordinate increment at reference point
CDELT2  =                  1.0 / [deg] Coordinate increment at reference point
CUNIT1  = 'deg'                / Units of coordinate increment and value
CUNIT2  = 'deg'                / Units of coordinate increment and value
CTYPE1  = 'RA---TAN'           / Right ascension, gnomonic projection
CTYPE2  = 'DEC--TAN'           / Declination, gnomonic projection
CRVAL1  =             83.81251 / [deg] Coordinate value at reference point
CRVAL2  =           -5.3631591 / [deg] Coordinate value at reference point
LONPOLE =                180.0 / [deg] Native longitude of celestial pole
LATPOLE =           -5.3631591 / [deg] Native latitude of celestial pole
MJDREF  =                  0.0 / [d] MJD of fiducial time
RADESYS = 'FK5'                / Equatorial coordinate system
EQUINOX =               2000.0 / [yr] Equinox of equatorial coordinates
"""
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()
ww = WCS(fits.Header.fromstring(trapezium_header, sep='\n'))

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
trapezium_header = """
WCSAXES =                    2 / Number of coordinate axes
CRPIX1  =             900.4109 / Pixel coordinate of reference point
CRPIX2  =             989.4288 / Pixel coordinate of reference point
PC1_1   =             -3.1E-05 / Coordinate transformation matrix element
PC2_2   =              3.1E-05 / Coordinate transformation matrix element
CDELT1  =                  1.0 / [deg] Coordinate increment at reference point
CDELT2  =                  1.0 / [deg] Coordinate increment at reference point
CUNIT1  = 'deg'                / Units of coordinate increment and value
CUNIT2  = 'deg'                / Units of coordinate increment and value
CTYPE1  = 'RA---TAN'           / Right ascension, gnomonic projection
CTYPE2  = 'DEC--TAN'           / Declination, gnomonic projection
CRVAL1  =             83.81251 / [deg] Coordinate value at reference point
CRVAL2  =           -5.3631591 / [deg] Coordinate value at reference point
LONPOLE =                180.0 / [deg] Native longitude of celestial pole
LATPOLE =           -5.3631591 / [deg] Native latitude of celestial pole
MJDREF  =                  0.0 / [d] MJD of fiducial time
RADESYS = 'FK5'                / Equatorial coordinate system
EQUINOX =               2000.0 / [yr] Equinox of equatorial coordinates
"""
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()
ww = WCS(fits.Header.fromstring(trapezium_header, sep='\n'))

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')


pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
trapezium_header = """
WCSAXES =                    2 / Number of coordinate axes
CRPIX1  =             950.4109 / Pixel coordinate of reference point
CRPIX2  =             1050.4288 / Pixel coordinate of reference point
PC1_1   =             -3.1E-05 / Coordinate transformation matrix element
PC2_2   =              3.1E-05 / Coordinate transformation matrix element
CDELT1  =                  1.0 / [deg] Coordinate increment at reference point
CDELT2  =                  1.0 / [deg] Coordinate increment at reference point
CUNIT1  = 'deg'                / Units of coordinate increment and value
CUNIT2  = 'deg'                / Units of coordinate increment and value
CTYPE1  = 'RA---TAN'           / Right ascension, gnomonic projection
CTYPE2  = 'DEC--TAN'           / Declination, gnomonic projection
CRVAL1  =             83.81251 / [deg] Coordinate value at reference point
CRVAL2  =           -5.3631591 / [deg] Coordinate value at reference point
LONPOLE =                180.0 / [deg] Native longitude of celestial pole
LATPOLE =           -5.3631591 / [deg] Native latitude of celestial pole
MJDREF  =                  0.0 / [d] MJD of fiducial time
RADESYS = 'FK5'                / Equatorial coordinate system
EQUINOX =               2000.0 / [yr] Equinox of equatorial coordinates
"""
trapezium_header = """
WCSAXES =                    2 / Number of coordinate axes
CRPIX1  =             950.4109 / Pixel coordinate of reference point
CRPIX2  =             1050.4288 / Pixel coordinate of reference point
PC1_1   =             -3.1E-05 / Coordinate transformation matrix element
PC2_2   =              3.1E-05 / Coordinate transformation matrix element
CDELT1  =                  1.0 / [deg] Coordinate increment at reference point
CDELT2  =                  1.0 / [deg] Coordinate increment at reference point
CUNIT1  = 'deg'                / Units of coordinate increment and value
CUNIT2  = 'deg'                / Units of coordinate increment and value
CTYPE1  = 'RA---TAN'           / Right ascension, gnomonic projection
CTYPE2  = 'DEC--TAN'           / Declination, gnomonic projection
CRVAL1  =             83.81251 / [deg] Coordinate value at reference point
CRVAL2  =           -5.3631591 / [deg] Coordinate value at reference point
LONPOLE =                180.0 / [deg] Native longitude of celestial pole
LATPOLE =           -5.3631591 / [deg] Native latitude of celestial pole
MJDREF  =                  0.0 / [d] MJD of fiducial time
RADESYS = 'FK5'                / Equatorial coordinate system
EQUINOX =               2000.0 / [yr] Equinox of equatorial coordinates
"""
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()
ww = WCS(fits.Header.fromstring(trapezium_header, sep='\n'))

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')

pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
trapezium_header = """
WCSAXES =                    2 / Number of coordinate axes
CRPIX1  =             1050.4109 / Pixel coordinate of reference point
CRPIX2  =             1030.4288 / Pixel coordinate of reference point
PC1_1   =             -3.1E-05 / Coordinate transformation matrix element
PC2_2   =              3.1E-05 / Coordinate transformation matrix element
CDELT1  =                  1.0 / [deg] Coordinate increment at reference point
CDELT2  =                  1.0 / [deg] Coordinate increment at reference point
CUNIT1  = 'deg'                / Units of coordinate increment and value
CUNIT2  = 'deg'                / Units of coordinate increment and value
CTYPE1  = 'RA---TAN'           / Right ascension, gnomonic projection
CTYPE2  = 'DEC--TAN'           / Declination, gnomonic projection
CRVAL1  =             83.81251 / [deg] Coordinate value at reference point
CRVAL2  =           -5.3631591 / [deg] Coordinate value at reference point
LONPOLE =                180.0 / [deg] Native longitude of celestial pole
LATPOLE =           -5.3631591 / [deg] Native latitude of celestial pole
MJDREF  =                  0.0 / [d] MJD of fiducial time
RADESYS = 'FK5'                / Equatorial coordinate system
EQUINOX =               2000.0 / [yr] Equinox of equatorial coordinates
"""
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()
ww = WCS(fits.Header.fromstring(trapezium_header, sep='\n'))

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')

pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
trapezium_header = """
WCSAXES =                    2 / Number of coordinate axes
CRPIX1  =             1020.4109 / Pixel coordinate of reference point
CRPIX2  =             1020.4288 / Pixel coordinate of reference point
PC1_1   =             -3.1E-05 / Coordinate transformation matrix element
PC2_2   =              3.1E-05 / Coordinate transformation matrix element
CDELT1  =                  1.0 / [deg] Coordinate increment at reference point
CDELT2  =                  1.0 / [deg] Coordinate increment at reference point
CUNIT1  = 'deg'                / Units of coordinate increment and value
CUNIT2  = 'deg'                / Units of coordinate increment and value
CTYPE1  = 'RA---TAN'           / Right ascension, gnomonic projection
CTYPE2  = 'DEC--TAN'           / Declination, gnomonic projection
CRVAL1  =             83.81251 / [deg] Coordinate value at reference point
CRVAL2  =           -5.3631591 / [deg] Coordinate value at reference point
LONPOLE =                180.0 / [deg] Native longitude of celestial pole
LATPOLE =           -5.3631591 / [deg] Native latitude of celestial pole
MJDREF  =                  0.0 / [d] MJD of fiducial time
RADESYS = 'FK5'                / Equatorial coordinate system
EQUINOX =               2000.0 / [yr] Equinox of equatorial coordinates
"""
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()
ww = WCS(fits.Header.fromstring(trapezium_header, sep='\n'))

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')

pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

#ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
#             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()
ww = WCS(fits.Header.fromstring(trapezium_header, sep='\n'))

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
#axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
#             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')

pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
fn_trapezium_alma = 'Trapezium_GEMS_mosaic_redblueorange_ALMA_normed_small_contrast_bright.png'
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

#ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
#             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium_alma))[::-1, :, :]
ww = WCS(fits.Header.fromstring(trapezium_header, sep='\n'))

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
#axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
#             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')

pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

#ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
#             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium))[::-1, :, :]
avm = pyavm.AVM.from_image(fn_trapezium)
ww = avm.to_wcs()
ww = WCS(fits.Header.fromstring(trapezium_header, sep='\n'))

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
#axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
#             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')

pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
rgb = np.array([simple_norm(img_carmaori_12co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_12co_omc),
                simple_norm(img_carmaori_13co_omc, min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_carmaori_13co_omc),
                simple_norm(img_orion_bolocam_omc, min_percent=1, max_percent=99.5, log_a=5e2, stretch='log')(img_orion_bolocam_omc)]).T.swapaxes(0,1)
ww = WCS(target_header_omc)

plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,2,1, projection=ww,)
ax.imshow(rgb)
ax.axis('off')
ax.axis([480, 1440, 480, 1440])

#ax.scatter(theta1c.ra, theta1c.dec, transform=ax.get_transform('world'),
#             marker='*', color='y')

rgb = np.array(PIL.Image.open(fn_trapezium_alma))[::-1, :, :]
ww = WCS(fits.Header.fromstring(trapezium_header, sep='\n'))

axins = inset_axes(ax,
                   width=4, height=4,
                   bbox_to_anchor=[0.0, 0.0, 0.9, 1],
                   bbox_transform=fig.transFigure,
                   loc='center right',
                   axes_class=astropy.visualization.wcsaxes.core.WCSAxes,
                   axes_kwargs=dict(wcs=ww))
axins.imshow(rgb)
axins.axis('off')
#axins.scatter(theta1c.ra, theta1c.dec, transform=axins.get_transform('world'),
#             marker='*', color='y')

mark_inset_generic(axins, ax, data=rgb[:,:,0], loc2=2, loc1=3, edgecolor='white')

pl.savefig("HI-CO-Dust_m0.35_oricloud-rezoom-trapezium-ALMA_RGB.png",
           bbox_inches='tight',
           pad_inches=0)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35', -0.35, layernames=('HI', 'CO', 'Dust'), do_layers=False)
prect = rect.to_pixel(ax.wcs)
prect.visual['edgecolor'] = 'w'
innergalplot = prect.plot(ax=ax)

pl.savefig("HI-CO-Dust_m0.35_RGB_innergal_zoombox.png", bbox_inches='tight')

innergaltext = ax.text(0, 25, "Galactic Plane", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

cmzrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(0*u.deg, 0*u.deg, frame='galactic'),
    width=12*u.deg,
    height=4.8*u.deg,
)
pcmzrect = cmzrect.to_pixel(ax.wcs)
pcmzrect.visual['edgecolor'] = 'w'
cmzplot = pcmzrect.plot(ax=ax)

cmztext = ax.text(0, 5, "Central Molecular Zone", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)
oritext = ax.text(209, -7, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_zones.png", bbox_inches='tight')

innergalplot.set_visible(False)
cmzplot.set_visible(False)
innergaltext.set_visible(False)
cmztext.set_visible(False)

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_orion.png", bbox_inches='tight')

oritext.set_visible(False)
oriplot.set_visible(False)

m31 = coordinates.SkyCoord.from_name('M31'),
andromedarect = regions.RectangleSkyRegion(
    m31,
    width=5*u.deg,
    height=5*u.deg,
)
pandromedarect = andromedarect.to_pixel(ax.wcs)
pandromedarect.visual['edgecolor'] = 'w'
andromedaplot = pandromedarect.plot(ax=ax)
andromedatext = ax.text(m31.galactic.l.deg, m31.galactic.b.deg+3,
                        "Andromeda", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_andromeda.png", bbox_inches='tight')

andromedatext.set_visible(False)
andromedaplot.set_visible(False)


taurus = coordinates.SkyCoord.from_name('taurus'),
taurusrect = regions.RectangleSkyRegion(
    taurus,
    width=15*u.deg,
    height=15*u.deg,
)
ptaurusrect = taurusrect.to_pixel(ax.wcs)
ptaurusrect.visual['edgecolor'] = 'w'
taurusplot = ptaurusrect.plot(ax=ax)
taurustext = ax.text(taurus.galactic.l.deg, taurus.galactic.b.deg+3,
                        "taurus", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_taurus.png", bbox_inches='tight')

taurustext.set_visible(False)
taurusplot.set_visible(False)
m31
#[Out]# (<SkyCoord (ICRS): (ra, dec) in deg
#[Out]#      (10.68470833, 41.26875)>,)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35', -0.35, layernames=('HI', 'CO', 'Dust'), do_layers=False)
prect = rect.to_pixel(ax.wcs)
prect.visual['edgecolor'] = 'w'
innergalplot = prect.plot(ax=ax)

pl.savefig("HI-CO-Dust_m0.35_RGB_innergal_zoombox.png", bbox_inches='tight')

innergaltext = ax.text(0, 25, "Galactic Plane", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

cmzrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(0*u.deg, 0*u.deg, frame='galactic'),
    width=12*u.deg,
    height=4.8*u.deg,
)
pcmzrect = cmzrect.to_pixel(ax.wcs)
pcmzrect.visual['edgecolor'] = 'w'
cmzplot = pcmzrect.plot(ax=ax)

cmztext = ax.text(0, 5, "Central Molecular Zone", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)
oritext = ax.text(209, -7, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_zones.png", bbox_inches='tight')

innergalplot.set_visible(False)
cmzplot.set_visible(False)
innergaltext.set_visible(False)
cmztext.set_visible(False)

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_orion.png", bbox_inches='tight')

oritext.set_visible(False)
oriplot.set_visible(False)

m31 = coordinates.SkyCoord.from_name('M31')
andromedarect = regions.RectangleSkyRegion(
    m31,
    width=5*u.deg,
    height=5*u.deg,
)
pandromedarect = andromedarect.to_pixel(ax.wcs)
pandromedarect.visual['edgecolor'] = 'w'
andromedaplot = pandromedarect.plot(ax=ax)
andromedatext = ax.text(m31.galactic.l.deg, m31.galactic.b.deg+3,
                        "Andromeda", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_andromeda.png", bbox_inches='tight')

andromedatext.set_visible(False)
andromedaplot.set_visible(False)


taurus = coordinates.SkyCoord.from_name('taurus')
taurusrect = regions.RectangleSkyRegion(
    taurus,
    width=15*u.deg,
    height=15*u.deg,
)
ptaurusrect = taurusrect.to_pixel(ax.wcs)
ptaurusrect.visual['edgecolor'] = 'w'
taurusplot = ptaurusrect.plot(ax=ax)
taurustext = ax.text(taurus.galactic.l.deg, taurus.galactic.b.deg+3,
                        "taurus", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_taurus.png", bbox_inches='tight')

taurustext.set_visible(False)
taurusplot.set_visible(False)
# different colors, overwrites previous
rgb = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
ax = make_rgb(rgb, 'HI-CO-Dust_m0.35', -0.35, layernames=('HI', 'CO', 'Dust'), do_layers=False)
prect = rect.to_pixel(ax.wcs)
prect.visual['edgecolor'] = 'w'
innergalplot = prect.plot(ax=ax)

pl.savefig("HI-CO-Dust_m0.35_RGB_innergal_zoombox.png", bbox_inches='tight')

innergaltext = ax.text(0, 25, "Galactic Plane", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

cmzrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(0*u.deg, 0*u.deg, frame='galactic'),
    width=12*u.deg,
    height=4.8*u.deg,
)
pcmzrect = cmzrect.to_pixel(ax.wcs)
pcmzrect.visual['edgecolor'] = 'w'
cmzplot = pcmzrect.plot(ax=ax)

cmztext = ax.text(0, 5, "Central Molecular Zone", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')


orionrect = regions.RectangleSkyRegion(
    coordinates.SkyCoord(209*u.deg, -19*u.deg, frame='galactic'),
    width=15*u.deg,
    height=15*u.deg,
)
porionrect = orionrect.to_pixel(ax.wcs)
porionrect.visual['edgecolor'] = 'w'
oriplot = porionrect.plot(ax=ax)
oritext = ax.text(209, -7, "Orion", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_zones.png", bbox_inches='tight')

innergalplot.set_visible(False)
cmzplot.set_visible(False)
innergaltext.set_visible(False)
cmztext.set_visible(False)

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_orion.png", bbox_inches='tight')

oritext.set_visible(False)
oriplot.set_visible(False)

m31 = coordinates.SkyCoord.from_name('M31')
andromedarect = regions.RectangleSkyRegion(
    m31,
    width=5*u.deg,
    height=5*u.deg,
)
pandromedarect = andromedarect.to_pixel(ax.wcs)
pandromedarect.visual['edgecolor'] = 'w'
andromedaplot = pandromedarect.plot(ax=ax)
andromedatext = ax.text(m31.galactic.l.deg, m31.galactic.b.deg+4,
                        "Andromeda", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_andromeda.png", bbox_inches='tight')

andromedatext.set_visible(False)
andromedaplot.set_visible(False)


taurus = coordinates.SkyCoord.from_name('taurus')
taurusrect = regions.RectangleSkyRegion(
    taurus,
    width=15*u.deg,
    height=15*u.deg,
)
ptaurusrect = taurusrect.to_pixel(ax.wcs)
ptaurusrect.visual['edgecolor'] = 'w'
taurusplot = ptaurusrect.plot(ax=ax)
taurustext = ax.text(taurus.galactic.l.deg-5, taurus.galactic.b.deg+10,
                        "Taurus", transform=ax.get_transform('world'),
        color='w', horizontalalignment='center')

pl.savefig("HI-CO-Dust_m0.35_RGB_labeled_taurus.png", bbox_inches='tight')

taurustext.set_visible(False)
taurusplot.set_visible(False)
# attempt progressive zoom


rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
ax.axis('off')

#ax.set_ylim(120*2, 360*2)
axlims = ax.axis()


import numpy as np
import matplotlib.pyplot as plt    
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
from matplotlib import cm


nframes = 63
maxzoom = 5

def animate(n, nframes):
    
    ax.axis(np.array(axlims) / (5 * n/63)) 

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=63)
anim.save('zoom_anim_HI-CO-Dust_m0.35.gif',fps=10)
# attempt progressive zoom


rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
ax.axis('off')

#ax.set_ylim(120*2, 360*2)
axlims = ax.axis()


import numpy as np
import matplotlib.pyplot as plt    
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
from matplotlib import cm


nframes = 63
maxzoom = 5

def animate(n, nframes=nframes):
    
    ax.axis(np.array(axlims) / (5 * n/63)) 
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=63)
anim.save('zoom_anim_HI-CO-Dust_m0.35.gif',fps=10)
# attempt progressive zoom


rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
ax.axis('off')

#ax.set_ylim(120*2, 360*2)
axlims = ax.axis()


import numpy as np
import matplotlib.pyplot as plt    
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
from matplotlib import cm


nframes = 63
maxzoom = 5

def animate(n, nframes=nframes):
    
    # n = 1 -> denom = 1
    # n = 63 -> denom = 5
    # y = m x + b
    # 5 = m 63 + b
    # 1 = m 1 + b
    # 5 = m 63 + 1 - m
    # m = 4/62
    # b = 58/62
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxframes)/(nframes - 1)
    ax.axis(np.array(axlims) / denom) 
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=63)
anim.save('zoom_anim_HI-CO-Dust_m0.35.gif',fps=10)
# attempt progressive zoom


rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
ax.axis('off')

#ax.set_ylim(120*2, 360*2)
axlims = ax.axis()


import numpy as np
import matplotlib.pyplot as plt    
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
from matplotlib import cm


nframes = 63
maxzoom = 5

def animate(n, nframes=nframes):
    
    # lol at math.
    # n = 1 -> denom = 1
    # n = 63 -> denom = 5
    # y = m x + b
    # 5 = m 63 + b
    # 1 = m 1 + b
    # 5 = m 63 + 1 - m
    # m = 4/62
    # b = 58/62
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    ax.axis(np.array(axlims) / denom) 
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=63)
anim.save('zoom_anim_HI-CO-Dust_m0.35.gif',fps=10)
# attempt progressive zoom


rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

fig = plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
ax.axis('off')

#ax.set_ylim(120*2, 360*2)
axlims = ax.axis()
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())
dy0 = np.abs(np.diff(ax.get_ylim())
dx0 = np.abs(np.diff(ax.get_xlim())


import numpy as np
import matplotlib.pyplot as plt    
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
from matplotlib import cm


nframes = 63
maxzoom = 5

def animate(n, nframes=nframes):
    
    # lol at math.
    # n = 1 -> denom = 1
    # n = 63 -> denom = 5
    # y = m x + b
    # 5 = m 63 + b
    # 1 = m 1 + b
    # 5 = m 63 + 1 - m
    # m = 4/62
    # b = 58/62
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom
    
    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=3)
anim.save('zoom_anim_HI-CO-Dust_m0.35.gif',fps=10)
# attempt progressive zoom


rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

fig = plt.figure(figsize=(10,5), dpi=200)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
ax.axis('off')

#ax.set_ylim(120*2, 360*2)
axlims = ax.axis()
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())
dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))


import numpy as np
import matplotlib.pyplot as plt    
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
from matplotlib import cm


nframes = 63
maxzoom = 5

def animate(n, nframes=nframes):
    
    # lol at math.
    # n = 1 -> denom = 1
    # n = 63 -> denom = 5
    # y = m x + b
    # 5 = m 63 + b
    # 1 = m 1 + b
    # 5 = m 63 + 1 - m
    # m = 4/62
    # b = 58/62
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom
    
    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=3)
anim.save('zoom_anim_HI-CO-Dust_m0.35.gif',fps=10)
# attempt progressive zoom


rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

fig = plt.figure(figsize=(10,5), dpi=200, frameon=False)
ax = plt.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
ax.axis('off')

#ax.set_ylim(120*2, 360*2)
axlims = ax.axis()
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())
dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))


import numpy as np
import matplotlib.pyplot as plt    
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
from matplotlib import cm


nframes = 15
maxzoom = 5

def animate(n, nframes=nframes):
    
    # lol at math.
    # n = 1 -> denom = 1
    # n = 63 -> denom = 5
    # y = m x + b
    # 5 = m 63 + b
    # 1 = m 1 + b
    # 5 = m 63 + 1 - m
    # m = 4/62
    # b = 58/62
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom
    
    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_HI-CO-Dust_m0.35.gif', fps=10)
# attempt progressive zoom
import numpy as np
import matplotlib.animation as animation

rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
ax.axis('off')

#ax.set_ylim(120*2, 360*2)
axlims = ax.axis()
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())
dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))

nframes = 65
maxzoom = 5

def animate(n, nframes=nframes):
    
    # lol at math.
    # n = 1 -> denom = 1
    # n = 63 -> denom = 5
    # y = m x + b
    # 5 = m 63 + b
    # 1 = m 1 + b
    # 5 = m 63 + 1 - m
    # m = 4/62
    # b = 58/62
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom
    
    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_full_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb_full(hsv)

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')

cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())
dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))

nframes = 10
maxzoom = 5

def animate(n, nframes=nframes):
    
    
    if n == nframes // 2:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
    
    if n > nframes / 2:
        denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
        dy = dy0 * 1/denom
        dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb_full(hsv)

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')

cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())
dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))

nframes = 10
maxzoom = 5

def animate(n, nframes=nframes):
    
    
    if n == nframes // 2:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
    
    if n > nframes / 2:
        denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
        dy = dy0 * 1/denom
        dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')

cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())
dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))

nframes = 10
maxzoom = 5

def animate(n, nframes=nframes):
    
    
    if n == nframes // 2:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
    
    if n > nframes / 2:
        denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
        dy = dy0 * 1/denom
        dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')

cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())
dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))

nframes = 10
maxzoom = 5

def animate(n, nframes=nframes):
    
    
    if n == nframes // 2:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
    else:
        ax = fig.gca()
    
    if n > nframes / 2:
        denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
        dy = dy0 * 1/denom
        dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 10
maxzoom = 5

def animate(n, nframes=nframes):
    if n == 0:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
    if n == nframes // 2:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
    
    if n > nframes / 2:
        denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
        dy = dy0 * 1/denom
        dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 10
maxzoom = 5

def animate(n, nframes=nframes):
    if n == 0:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
    if n == nframes // 2:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
    
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 10
maxzoom = 5

def animate(n, nframes=nframes):
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
    
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
ax.images[0].shape
ax.images[0].data
ax.images
#[Out]# <Axes.ArtistList of 0 images>
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 10
maxzoom = 5

dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
        dxdy[:] = (dx0, dy0)
    
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 10

dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
        dxdy[:] = (dx0, dy0)
    
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb_scaled
#[Out]# array([[[0.09770292, 0.03950195, 0.0518926 ],
#[Out]#         [0.09617418, 0.04054672, 0.05234537],
#[Out]#         [0.09615439, 0.04241194, 0.05296471],
#[Out]#         ...,
#[Out]#         [0.10983438, 0.14275034, 0.08626572],
#[Out]#         [0.10892132, 0.13413061, 0.08670482],
#[Out]#         [0.10890397, 0.13510137, 0.08718825]],
#[Out]# 
#[Out]#        [[0.09870678, 0.04227048, 0.05258689],
#[Out]#         [0.09581747, 0.0419343 , 0.05302311],
#[Out]#         [0.09669664, 0.04174596, 0.05397213],
#[Out]#         ...,
#[Out]#         [0.10401951, 0.12874659, 0.08668213],
#[Out]#         [0.10261399, 0.12137245, 0.08720585],
#[Out]#         [0.10457987, 0.12211816, 0.08802306]],
#[Out]# 
#[Out]#        [[0.09956501, 0.04008018, 0.05338847],
#[Out]#         [0.09805067, 0.03978163, 0.05400325],
#[Out]#         [0.09913332, 0.0397914 , 0.05483081],
#[Out]#         ...,
#[Out]#         [0.10571321, 0.12517053, 0.08762735],
#[Out]#         [0.10315513, 0.11675736, 0.08787155],
#[Out]#         [0.10299237, 0.11543316, 0.08822606]],
#[Out]# 
#[Out]#        ...,
#[Out]# 
#[Out]#        [[0.0978088 , 0.03666375, 0.04551319],
#[Out]#         [0.09896033, 0.03843609, 0.04460773],
#[Out]#         [0.09778884, 0.03820247, 0.04300104],
#[Out]#         ...,
#[Out]#         [0.09607801, 0.09270062, 0.09353797],
#[Out]#         [0.0975769 , 0.09119403, 0.09217367],
#[Out]#         [0.10101521, 0.0861214 , 0.09074794]],
#[Out]# 
#[Out]#        [[0.09563598, 0.03469633, 0.04519415],
#[Out]#         [0.09643578, 0.03625065, 0.04375105],
#[Out]#         [0.10038051, 0.03623058, 0.04346511],
#[Out]#         ...,
#[Out]#         [0.09794023, 0.08974838, 0.09290336],
#[Out]#         [0.09972324, 0.08843856, 0.09033646],
#[Out]#         [0.10158328, 0.08388048, 0.08845966]],
#[Out]# 
#[Out]#        [[0.09615658, 0.03351984, 0.04508491],
#[Out]#         [0.09685247, 0.03439735, 0.043446  ],
#[Out]#         [0.1008527 , 0.03461811, 0.04258696],
#[Out]#         ...,
#[Out]#         [0.09880597, 0.08843639, 0.09145266],
#[Out]#         [0.09725838, 0.08566693, 0.08787558],
#[Out]#         [0.10142778, 0.08186163, 0.08521634]]])
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 10

dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        n = nframes * 2
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        n = (nframes * 2) % nframes
        
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
        dxdy[:] = (dx0, dy0)
    
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 10

dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        n = n * 2
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        n = (n * 2) % nframes
        
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
        dxdy[:] = (dx0, dy0)
    
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
20 // 2
#[Out]# 10
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        n = n * 2
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        n = (n * 2) % nframes
        
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
        dxdy[:] = (dx0, dy0)
    
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        n = n * 2
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        n = (n * 2) % nframes
        
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
        dxdy[:] = (dx0, dy0)
    
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{denom}.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        n = n * 2
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
        n = (n * 2) % nframes
        
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
        dxdy[:] = (dx0, dy0)
    
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{denom:5.2f}.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
zoomfac = np.hstack([np.linspace(1, 5, nframes//2)
                     np.linspace(1, 5, nframes//2)])
zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])
zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])
zoomfac
#[Out]# array([1.        , 1.44444444, 1.88888889, 2.33333333, 2.77777778,
#[Out]#        3.22222222, 3.66666667, 4.11111111, 4.55555556, 5.        ,
#[Out]#        1.        , 1.44444444, 1.88888889, 2.33333333, 2.77777778,
#[Out]#        3.22222222, 3.66666667, 4.11111111, 4.55555556, 5.        ])
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])

dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
        dxdy[:] = (dx0, dy0)
    
    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{denom:5.2f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])

dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
        dxdy[:] = (dx0, dy0)
    
    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])

dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))
        dx0 = np.abs(np.diff(ax.get_xlim()))
        dxdy[:] = (dx0, dy0)
    
    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))/2
        dx0 = np.abs(np.diff(ax.get_xlim()))/2
        dxdy[:] = (dx0, dy0)
    
    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))/2
        dx0 = np.abs(np.diff(ax.get_xlim()))/2
        dxdy[:] = (dx0, dy0)
        print(f"dx0,dy0: {dxdy}")
    
    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = rgb_scaled.shape[1]/2
        cy = rgb_scaled.shape[0]/2
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))/2
        dx0 = np.abs(np.diff(ax.get_xlim()))/2
        dxdy[:] = (dx0, dy0)
        print(f"\ndx0,dy0: {dxdy}")
    
    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb_scaled.shape
#[Out]# (960, 1920, 3)
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = rgb_scaled.shape[1]/2
        cy = rgb_scaled.shape[0]/2
    
    if n == nframes // 2:
        dy0 = np.abs(np.diff(ax.get_ylim()))/2
        dx0 = np.abs(np.diff(ax.get_xlim()))/2
        dxdy[:] = (dx0, dy0)
        print(f"\ndx0,dy0: {dxdy}")
    
    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
img_HI4PI_innergal.shape
#[Out]# (960, 3840)
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n <= nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = rgb_scaled.shape[1]/2
        cy = rgb_scaled.shape[0]/2
    
    if n == nframes // 2:
        dy0 = rgb_scaled.shape[0]
        dx0 = rgb_scaled.shape[1]
        dxdy[:] = (dx0, dy0)
        print(f"\ndx0,dy0: {dxdy}")
    
    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n < nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = rgb_scaled.shape[1]/2
        cy = rgb_scaled.shape[0]/2
    
    if n == nframes // 2:
        dy0 = rgb_scaled.shape[0]
        dx0 = rgb_scaled.shape[1]
        dxdy[:] = (dx0, dy0)
        print(f"\ndx0,dy0: {dxdy}")
    
    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 20
maxzoom = 2

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n < nframes // 2:
        ax = fig.gca()
        cx = np.mean(ax.get_xlim())
        cy = np.mean(ax.get_ylim())
    else:
        fig.clf()
        ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
        ax.imshow(rgb_scaled)
        ax.axis('off')
        cx = rgb_scaled.shape[1]/2
        cy = rgb_scaled.shape[0]/2
    
    if n == nframes // 2:
        dy0 = rgb_scaled.shape[0]
        dx0 = rgb_scaled.shape[1]
        dxdy[:] = (dx0, dy0)
        print(f"\ndx0,dy0: {dxdy}")
    
    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
1920*0.05
#[Out]# 96.0
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 60
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])
zoomfac = np.linspace(1, maxzoom, nframes)

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    #if n < nframes // 2:
    #    ax = fig.gca()
    #    cx = np.mean(ax.get_xlim())
    #    cy = np.mean(ax.get_ylim())
    #else:
    #    fig.clf()
    #    ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
    #    ax.imshow(rgb_scaled)
    #    ax.axis('off')
    #    cx = rgb_scaled.shape[1]/2
    #    cy = rgb_scaled.shape[0]/2
    #
    #if n == nframes // 2:
    #    dy0 = rgb_scaled.shape[0]
    #    dx0 = rgb_scaled.shape[1]
    #    dxdy[:] = (dx0, dy0)
    #    print(f"\ndx0,dy0: {dxdy}")
    
    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif', fps=10)
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 60
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])
zoomfac = np.linspace(1, maxzoom, nframes)

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    #if n < nframes // 2:
    #    ax = fig.gca()
    #    cx = np.mean(ax.get_xlim())
    #    cy = np.mean(ax.get_ylim())
    #else:
    #    fig.clf()
    #    ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
    #    ax.imshow(rgb_scaled)
    #    ax.axis('off')
    #    cx = rgb_scaled.shape[1]/2
    #    cy = rgb_scaled.shape[0]/2
    #
    #if n == nframes // 2:
    #    dy0 = rgb_scaled.shape[0]
    #    dx0 = rgb_scaled.shape[1]
    #    dxdy[:] = (dx0, dy0)
    #    print(f"\ndx0,dy0: {dxdy}")
    
    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 80
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])
zoomfac = np.linspace(1, maxzoom, nframes)

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    #if n < nframes // 2:
    #    ax = fig.gca()
    #    cx = np.mean(ax.get_xlim())
    #    cy = np.mean(ax.get_ylim())
    #else:
    #    fig.clf()
    #    ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
    #    ax.imshow(rgb_scaled)
    #    ax.axis('off')
    #    cx = rgb_scaled.shape[1]/2
    #    cy = rgb_scaled.shape[0]/2
    #
    #if n == nframes // 2:
    #    dy0 = rgb_scaled.shape[0]
    #    dx0 = rgb_scaled.shape[1]
    #    dxdy[:] = (dx0, dy0)
    #    print(f"\ndx0,dy0: {dxdy}")
    if n == nframes // 2:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)

    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5,
                               interval=50)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 80
maxzoom = 5

zoomfac = np.hstack([np.linspace(1, 5, nframes//2),
                     np.linspace(1, 5, nframes//2)])
zoomfac = np.linspace(1, maxzoom, nframes)

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    #if n < nframes // 2:
    #    ax = fig.gca()
    #    cx = np.mean(ax.get_xlim())
    #    cy = np.mean(ax.get_ylim())
    #else:
    #    fig.clf()
    #    ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
    #    ax.imshow(rgb_scaled)
    #    ax.axis('off')
    #    cx = rgb_scaled.shape[1]/2
    #    cy = rgb_scaled.shape[0]/2
    #
    #if n == nframes // 2:
    #    dy0 = rgb_scaled.shape[0]
    #    dx0 = rgb_scaled.shape[1]
    #    dxdy[:] = (dx0, dy0)
    #    print(f"\ndx0,dy0: {dxdy}")
    if n == nframes // 2:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)

    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                               interval=50)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


zoomfac = np.linspace(1, 10, 120)

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    #if n < nframes // 2:
    #    ax = fig.gca()
    #    cx = np.mean(ax.get_xlim())
    #    cy = np.mean(ax.get_ylim())
    #else:
    #    fig.clf()
    #    ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
    #    ax.imshow(rgb_scaled)
    #    ax.axis('off')
    #    cx = rgb_scaled.shape[1]/2
    #    cy = rgb_scaled.shape[0]/2
    #
    #if n == nframes // 2:
    #    dy0 = rgb_scaled.shape[0]
    #    dx0 = rgb_scaled.shape[1]
    #    dxdy[:] = (dx0, dy0)
    #    print(f"\ndx0,dy0: {dxdy}")
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        

    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                               interval=50)
anim.save('zoom_anim_cmz_HI-CO-Dust_m0.35.gif')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 80
maxzoom = 5

zoomfac = np.linspace(1, maxzoom, nframes)

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    #if n < nframes // 2:
    #    ax = fig.gca()
    #    cx = np.mean(ax.get_xlim())
    #    cy = np.mean(ax.get_ylim())
    #else:
    #    fig.clf()
    #    ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
    #    ax.imshow(rgb_scaled)
    #    ax.axis('off')
    #    cx = rgb_scaled.shape[1]/2
    #    cy = rgb_scaled.shape[0]/2
    #
    #if n == nframes // 2:
    #    dy0 = rgb_scaled.shape[0]
    #    dx0 = rgb_scaled.shape[1]
    #    dxdy[:] = (dx0, dy0)
    #    print(f"\ndx0,dy0: {dxdy}")
    if n == nframes // 2:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)

    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                               interval=50)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif')
# attempt progressive zoom
import numpy as np
import matplotlib.animation as animation

rgb = np.array([simple_norm(img_HI4PI_cmz,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_cmz),
                simple_norm(img_CO21_cmz,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_cmz),
                simple_norm(img_ThermalDust_cmz, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_cmz)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header_cmz),)
                 #frame_class=EllipticalFrame)
ax.imshow(rgb_scaled)
ax.axis('off')

#ax.set_ylim(120*2, 360*2)
axlims = ax.axis()
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())
dy0 = np.abs(np.diff(ax.get_ylim()))
dx0 = np.abs(np.diff(ax.get_xlim()))

nframes = 90
maxzoom = 5

def animate(n, nframes=nframes):
    
    # lol at math.
    # n = 1 -> denom = 1
    # n = 63 -> denom = 5
    # y = m x + b
    # 5 = m 63 + b
    # 1 = m 1 + b
    # 5 = m 63 + 1 - m
    # m = 4/62
    # b = 58/62
    denom = (maxzoom-1)/(nframes-1) * n + (nframes - maxzoom)/(nframes - 1)
    dy = dy0 * 1/denom
    dx = dx0 * 1/denom
    
    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print('.', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                              interval=50)
anim.save('zoom_anim_HI-CO-Dust_m0.35.gif')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 120
zoomfac = np.linspace(1, 10, nframes)

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    #if n < nframes // 2:
    #    ax = fig.gca()
    #    cx = np.mean(ax.get_xlim())
    #    cy = np.mean(ax.get_ylim())
    #else:
    #    fig.clf()
    #    ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
    #    ax.imshow(rgb_scaled)
    #    ax.axis('off')
    #    cx = rgb_scaled.shape[1]/2
    #    cy = rgb_scaled.shape[0]/2
    #
    #if n == nframes // 2:
    #    dy0 = rgb_scaled.shape[0]
    #    dx0 = rgb_scaled.shape[1]
    #    dxdy[:] = (dx0, dy0)
    #    print(f"\ndx0,dy0: {dxdy}")
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        

    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                               interval=50)
anim.save('zoom_anim_cmz_HI-CO-Dust_m0.35.gif')
rgb_full_scaled.shape
#[Out]# (960, 1920, 3)
360/1920
#[Out]# 0.1875
1920/2
#[Out]# 960.0
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 120
zoomfac = np.hstack([np.linspace(1, 10, 80),
                     np.linspace(10, 960, 40)])
                     

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    #if n < nframes // 2:
    #    ax = fig.gca()
    #    cx = np.mean(ax.get_xlim())
    #    cy = np.mean(ax.get_ylim())
    #else:
    #    fig.clf()
    #    ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
    #    ax.imshow(rgb_scaled)
    #    ax.axis('off')
    #    cx = rgb_scaled.shape[1]/2
    #    cy = rgb_scaled.shape[0]/2
    #
    #if n == nframes // 2:
    #    dy0 = rgb_scaled.shape[0]
    #    dx0 = rgb_scaled.shape[1]
    #    dxdy[:] = (dx0, dy0)
    #    print(f"\ndx0,dy0: {dxdy}")
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        

    dy = dy0 / zoomfac[n]
    dx = dx0 / zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                               interval=50)
anim.save('zoom_anim_cmz_HI-CO-Dust_m0.35.gif')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 120
zoomfac = np.hstack([np.linspace(1, 1/16., 80),
                     np.linspace(1/16., 1/24., 40)])
                     

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        

    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                               interval=50)
anim.save('zoom_anim_cmz_HI-CO-Dust_m0.35.gif')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 80
maxzoom = 5

zoomfac = np.linspace(1, 1/maxzoom, nframes)

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    #if n < nframes // 2:
    #    ax = fig.gca()
    #    cx = np.mean(ax.get_xlim())
    #    cy = np.mean(ax.get_ylim())
    #else:
    #    fig.clf()
    #    ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
    #    ax.imshow(rgb_scaled)
    #    ax.axis('off')
    #    cx = rgb_scaled.shape[1]/2
    #    cy = rgb_scaled.shape[0]/2
    #
    #if n == nframes // 2:
    #    dy0 = rgb_scaled.shape[0]
    #    dx0 = rgb_scaled.shape[1]
    #    dxdy[:] = (dx0, dy0)
    #    print(f"\ndx0,dy0: {dxdy}")
    if n == nframes // 2:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)

    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                               interval=50)
anim.save('zoom_anim_molltorect_HI-CO-Dust_m0.35.gif')

# convert zoom_anim_molltorect_HI-CO-Dust_m0.35.gif \( +clone -set delay 500 \) +swap +delete zoom_anim_molltorect_HI-CO-Dust_m0.35_with_pause.gif
np.linspace(1, 1/24.), 1/16.
#[Out]# (array([1.        , 0.98044218, 0.96088435, 0.94132653, 0.92176871,
#[Out]#         0.90221088, 0.88265306, 0.86309524, 0.84353741, 0.82397959,
#[Out]#         0.80442177, 0.78486395, 0.76530612, 0.7457483 , 0.72619048,
#[Out]#         0.70663265, 0.68707483, 0.66751701, 0.64795918, 0.62840136,
#[Out]#         0.60884354, 0.58928571, 0.56972789, 0.55017007, 0.53061224,
#[Out]#         0.51105442, 0.4914966 , 0.47193878, 0.45238095, 0.43282313,
#[Out]#         0.41326531, 0.39370748, 0.37414966, 0.35459184, 0.33503401,
#[Out]#         0.31547619, 0.29591837, 0.27636054, 0.25680272, 0.2372449 ,
#[Out]#         0.21768707, 0.19812925, 0.17857143, 0.15901361, 0.13945578,
#[Out]#         0.11989796, 0.10034014, 0.08078231, 0.06122449, 0.04166667]),
#[Out]#  0.0625)
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 120
zoomfac = np.hstack([np.linspace(1, 1/16., 80),
                     np.linspace(1/16., 1/24., 40)])
zoomfac = np.linspace(1, 1/90., 120)
                     

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        

    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                               interval=50)
anim.save('zoom_anim_cmz_linear_HI-CO-Dust_m0.35.gif')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 120
zoomfac = np.hstack([np.linspace(1, 1/16., 80),
                     np.linspace(1/16., 1/24., 40)])
zoomfac = np.linspace(1, 1/90., 120)
zoomfac = np.geomspace(1, 1/90., 120)


dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        

    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                               interval=50)
anim.save('zoom_anim_cmz_linear_HI-CO-Dust_m0.35.gif')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 80
maxzoom = 5

zoomfac = np.linspace(1, 1/maxzoom, nframes)
zoomfac = np.geomspace(1, 1/maxzoom, nframes)

dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim())
cy = np.mean(ax.get_ylim())

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    #if n < nframes // 2:
    #    ax = fig.gca()
    #    cx = np.mean(ax.get_xlim())
    #    cy = np.mean(ax.get_ylim())
    #else:
    #    fig.clf()
    #    ax = pl.subplot(1,1,1, projection=WCS(target_header_innergal),)
    #    ax.imshow(rgb_scaled)
    #    ax.axis('off')
    #    cx = rgb_scaled.shape[1]/2
    #    cy = rgb_scaled.shape[0]/2
    #
    #if n == nframes // 2:
    #    dy0 = rgb_scaled.shape[0]
    #    dx0 = rgb_scaled.shape[1]
    #    dxdy[:] = (dx0, dy0)
    #    print(f"\ndx0,dy0: {dxdy}")
    if n == nframes // 2:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)

    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                               interval=50)
anim.save('zoom_anim_molltorect_linear_HI-CO-Dust_m0.35.gif')

# convert zoom_anim_molltorect_HI-CO-Dust_m0.35.gif \( +clone -set delay 500 \) +swap +delete zoom_anim_molltorect_HI-CO-Dust_m0.35_with_pause.gif
0.5 / 0.1875
#[Out]# 2.6666666666666665
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 120
zoomfac = np.hstack([np.linspace(1, 1/16., 80),
                     np.linspace(1/16., 1/24., 40)])
zoomfac = np.linspace(1, 1/90., 120)
zoomfac = np.geomspace(1, 1/180., 120)


dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim()) - 2.6 # zoom in between Sgr A and Sgr B2
cy = np.mean(ax.get_ylim())

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

dy = dy0 * zoomfac[-1]
dx = dx0 * zoomfac[-1]

ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        

    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

# anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
#                                interval=50)
# anim.save('zoom_anim_cmz_linear_HI-CO-Dust_m0.35.gif')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 120
zoomfac = np.hstack([np.linspace(1, 1/16., 80),
                     np.linspace(1/16., 1/24., 40)])
zoomfac = np.linspace(1, 1/90., 120)
zoomfac = np.geomspace(1, 1/180., 120)


dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim()) - 2.6 # zoom in between Sgr A and Sgr B2
cy = np.mean(ax.get_ylim())

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

ax.imshow(rgbcmz,
  transform=ax.get_transform(wwcmz))

dy = dy0 * zoomfac[-1]
dx = dx0 * zoomfac[-1]

ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))

def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        

    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

# anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
#                                interval=50)
# anim.save('zoom_anim_cmz_linear_HI-CO-Dust_m0.35.gif')
rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 180
zoomfac = np.geomspace(1, 1/180., nframes)


dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]
cx = np.mean(ax.get_xlim()) - 2.6 # zoom in between Sgr A and Sgr B2
cy = np.mean(ax.get_ylim())

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))


def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        

    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
    print(f'{n}:{zoomfac[n]:0.1f}|', end='')

    return fig,     

anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
                               interval=50)
anim.save('zoom_anim_cmz_linear_HI-CO-Dust_m0.35.gif')
# zoom into the CMZ _even more_


rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 360
zoomfac = np.geomspace(1, 1/240., nframes)


dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

cc = SkyCoord.from_name('Sgr B2')

cx, cy = ax.wcs.world_to_pixel(cc)

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

aces7m = fits.open('/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
aces7mwcs = WCS(aces7m[0].header)
aces7mrepr,_ = reproject.reproject_interp(aces7m, ww, shape_out=rgb.shape[:2])
aces7mrepr[aces7mrepr < 0] = np.nan

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0


def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        
    if n == 180:
        ax.imshow(aces7mrepr, 
                  norm=simple_norm(aces7mrepr, stretch='log', max_percent=99.96, min_percent=1),
                  transform=ax.get_transform(aces7mwcs),
                  cmap=orange_transparent)
        
    if n == 240:
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='log',
                                      min_percent=None, max_percent=None,
                                      min_cut=-0.0005, max_cut=0.05,),
                     cmap='gray',
                  transform=ax.get_transform(aces12mwcs),
                    )
    


    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    if n <= 300:
        ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
        
    print(f'{n}|', end='')

    return fig,     

animate(300)

# anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
#                                interval=50)
# anim.save('zoom_anim_cmz_linear_withACES_HI-CO-Dust_m0.35.gif')
#[Out]# (<Figure size 2000x1000 with 1 Axes>,)
pl.imshow(rgb_full_scaled)
#[Out]# <matplotlib.image.AxesImage at 0x2b76f5f32760>
# zoom into the CMZ _even more_


rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 360
zoomfac = np.geomspace(1, 1/240., nframes)


dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

cc = SkyCoord.from_name('Sgr B2')

cx, cy = ax.wcs.world_to_pixel(cc)

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

aces7m = fits.open('/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
aces7mwcs = WCS(aces7m[0].header)
aces7mrepr,_ = reproject.reproject_interp(aces7m, ww, shape_out=rgb.shape[:2])
aces7mrepr[aces7mrepr < 0] = np.nan

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0


def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        
    if n == 180:
        ax.imshow(aces7mrepr, 
                  norm=simple_norm(aces7mrepr, stretch='log', max_percent=99.96, min_percent=1),
                  transform=ax.get_transform(aces7mwcs),
                  cmap=orange_transparent)
        
    if n == 240:
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='log',
                                      min_percent=None, max_percent=None,
                                      min_cut=-0.0005, max_cut=0.05,),
                     cmap='gray',
                  transform=ax.get_transform(aces12mwcs),
                    )
    


    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]

    if n <= 300:
        ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
        
    print(f'{n}|', end='')

    return fig,     

animate(240)

# anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
#                                interval=50)
# anim.save('zoom_anim_cmz_linear_withACES_HI-CO-Dust_m0.35.gif')
#[Out]# (<Figure size 2000x1000 with 1 Axes>,)
ax.axis()
#[Out]# (931.3366231801315, 980.5489225936637, 466.95847218962416, 491.5646218963903)
fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')

ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
          transform=ax.get_transform(aces12mwcs), )

ax.axis([940,941,466,467])
#[Out]# (940.0, 941.0, 466.0, 467.0)
ax.wcs.world_to_pixel(sgrb2m)
sgrb2 = SkyCoord.from_name('Sgr B2')
ax.wcs.world_to_pixel(sgrb2)
#[Out]# (array(955.94277289), array(479.26154704))
ax.axis([954,956,478,480])
#[Out]# (954.0, 956.0, 478.0, 480.0)
ax.axis([954,956,478,480])
ax
#[Out]# <WCSAxesSubplot:>
ax.axis([954,956,478,480])
fig
#[Out]# <Figure size 2000x1000 with 1 Axes>
ax.axis([954,957,478,480])
fig
#[Out]# <Figure size 2000x1000 with 1 Axes>
# check final zoom level
fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')

ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
          transform=ax.get_transform(aces12mwcs), )
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=0.05, max_cut=0.5,),
             cmap='Oranges',
          transform=ax.get_transform(aces12mwcs), )

ax.axis([954,957,478,480])
#[Out]# (954.0, 957.0, 478.0, 480.0)
mpl.cm.Oranges
pl.cm.Oranges
#[Out]# <matplotlib.colors.LinearSegmentedColormap at 0x2b76913be160>
pl.cm.Oranges.get_bad()
#[Out]# array([0., 0., 0., 0.])
pl.cm.Oranges(0)
#[Out]# (1.0, 0.9607843137254902, 0.9215686274509803, 1.0)
pl.cm.Oranges.get_under()
#[Out]# array([1.        , 0.96078431, 0.92156863, 1.        ])
transorange = pl.cm.Oranges.copy()
transorange.set_under((0,0,0,0))
transorange
#[Out]# <matplotlib.colors.LinearSegmentedColormap at 0x2b7705fde8b0>
# check final zoom level
fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')

ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
          transform=ax.get_transform(aces12mwcs), )
transorange = pl.cm.Oranges.copy()
transorange.set_under((0,0,0,0))
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='linear',
                              min_percent=None, max_percent=None,
                              min_cut=0.05, max_cut=0.5,),
             cmap='Oranges',
          transform=ax.get_transform(aces12mwcs), )

ax.axis([954,957,478,480])
#[Out]# (954.0, 957.0, 478.0, 480.0)
pl.cm.Oranges.get_under()
#[Out]# array([1.        , 0.96078431, 0.92156863, 1.        ])
transorange = pl.cm.Oranges.copy()
transorange.set_under((0,0,0,0))
transorange
#[Out]# <matplotlib.colors.LinearSegmentedColormap at 0x2b76d32071c0>
ax.axis([960,963,478,480])
fig
#[Out]# <Figure size 2000x1000 with 1 Axes>
# check final zoom level
fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')

ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='log',
                              min_percent=None, max_percent=None,
                              min_cut=-0.0005, max_cut=0.05,),
             cmap='gray',
          transform=ax.get_transform(aces12mwcs), )
transorange = pl.cm.Oranges.copy()
transorange.set_under((0,0,0,0))
ax.imshow(aces12m[0].data,
             norm=simple_norm(aces12m[0].data, stretch='linear',
                              min_percent=None, max_percent=None,
                              min_cut=0.05, max_cut=0.5,),
             cmap=transorange,
          transform=ax.get_transform(aces12mwcs), )

ax.axis([954,957,478,480])
#[Out]# (954.0, 957.0, 478.0, 480.0)
transorange = pl.cm.Oranges.copy()
transorange.set_under((0,0,0,0))
transorange
#[Out]# <matplotlib.colors.LinearSegmentedColormap at 0x2b76d320ec40>
ax.axis([960,963,478,480])
fig
#[Out]# <Figure size 2000x1000 with 1 Axes>
# zoom into the CMZ _even more_


rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 360
zoomfac = np.hstack([np.geomspace(1, 1/240., 300)
                     np.ones(60.)/240.])



dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

sgrb2 = SkyCoord.from_name('Sgr B2')
sgra = SkyCoord.from_name('Sgr A')

cx, cy = ax.wcs.world_to_pixel(sgrb2)
cx2, cy2 = ax.wcs.world_to_pixel(sgrb2)
cxs = np.hstack([np.ones(300)*cx, np.linspace(cx, cx2, 60)])
cys = np.hstack([np.ones(300)*cy, np.linspace(cy, cy2, 60)])
print(zoomfac, cxs, cys)
raise

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

aces7m = fits.open('/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
aces7mwcs = WCS(aces7m[0].header)
aces7mrepr,_ = reproject.reproject_interp(aces7m, ww, shape_out=rgb.shape[:2])
aces7mrepr[aces7mrepr < 0] = np.nan

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0


def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        
    if n == 180:
        ax.imshow(aces7mrepr, 
                  norm=simple_norm(aces7mrepr, stretch='log', max_percent=99.96, min_percent=1),
                  transform=ax.get_transform(aces7mwcs),
                  cmap=orange_transparent)
        
    if n == 240:
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='log',
                                      min_percent=None, max_percent=None,
                                      min_cut=-0.0005, max_cut=0.05,),
                     cmap='gray',
                  transform=ax.get_transform(aces12mwcs),
                    )
        transorange = pl.cm.Oranges.copy()
        transorange.set_under((0,0,0,0))
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='linear',
                                      min_percent=None, max_percent=None,
                                      min_cut=0.05, max_cut=0.5,),
                     cmap=transorange,
                  transform=ax.get_transform(aces12mwcs), )
    


    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]
    cx, cy = cxs[n], cys[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
        
    print(f'{n}|', end='')

    return fig,     

animate(240)

# anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
#                                interval=50)
# anim.save('zoom_anim_cmz_linear_withACES_HI-CO-Dust_m0.35.gif')
# zoom into the CMZ _even more_


rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 360
zoomfac = np.hstack([np.geomspace(1, 1/1920., 300),
                     np.ones(60.)/1920.])



dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

sgrb2 = SkyCoord.from_name('Sgr B2')
sgra = SkyCoord.from_name('Sgr A')

cx, cy = ax.wcs.world_to_pixel(sgrb2)
cx2, cy2 = ax.wcs.world_to_pixel(sgrb2)
cxs = np.hstack([np.ones(300)*cx, np.linspace(cx, cx2, 60)])
cys = np.hstack([np.ones(300)*cy, np.linspace(cy, cy2, 60)])
print(zoomfac, cxs, cys)
raise

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

aces7m = fits.open('/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
aces7mwcs = WCS(aces7m[0].header)
aces7mrepr,_ = reproject.reproject_interp(aces7m, ww, shape_out=rgb.shape[:2])
aces7mrepr[aces7mrepr < 0] = np.nan

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0


def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        
    if n == 180:
        ax.imshow(aces7mrepr, 
                  norm=simple_norm(aces7mrepr, stretch='log', max_percent=99.96, min_percent=1),
                  transform=ax.get_transform(aces7mwcs),
                  cmap=orange_transparent)
        
    if n == 240:
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='log',
                                      min_percent=None, max_percent=None,
                                      min_cut=-0.0005, max_cut=0.05,),
                     cmap='gray',
                  transform=ax.get_transform(aces12mwcs),
                    )
        transorange = pl.cm.Oranges.copy()
        transorange.set_under((0,0,0,0))
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='asinh',
                                      min_percent=None, max_percent=99.99,
                                      min_cut=0.05,),
                     cmap=transorange,
                  transform=ax.get_transform(aces12mwcs), )
    


    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]
    cx, cy = cxs[n], cys[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
        
    print(f'{n}|', end='')

    return fig,     

animate(240)

# anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
#                                interval=50)
# anim.save('zoom_anim_cmz_linear_withACES_HI-CO-Dust_m0.35.gif')
ax.wcs.world_to_pixel(sgrb2), ax.wcs.world_to_pixel(sgra)
# zoom into the CMZ _even more_


rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')


nframes = 360
zoomfac = np.hstack([np.geomspace(1, 1/1920., 300),
                     np.ones(60, dtype='float')/1920.])



dy0 = np.abs(np.diff(ax.get_ylim()))/2
dx0 = np.abs(np.diff(ax.get_xlim()))/2
dxdy = [dx0, dy0]

sgrb2 = SkyCoord.from_name('Sgr B2')
sgra = SkyCoord.from_name('Sgr A')

cx, cy = ax.wcs.world_to_pixel(sgrb2)
cx2, cy2 = ax.wcs.world_to_pixel(sgrb2)
cxs = np.hstack([np.ones(300)*cx, np.linspace(cx, cx2, 60)])
cys = np.hstack([np.ones(300)*cy, np.linspace(cy, cy2, 60)])
print(zoomfac, cxs, cys)
raise

rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

aces7m = fits.open('/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
aces7mwcs = WCS(aces7m[0].header)
aces7mrepr,_ = reproject.reproject_interp(aces7m, ww, shape_out=rgb.shape[:2])
aces7mrepr[aces7mrepr < 0] = np.nan

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0


def animate(n, nframes=nframes):
    dx0, dy0 = dxdy
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        
    if n == 180:
        ax.imshow(aces7mrepr, 
                  norm=simple_norm(aces7mrepr, stretch='log', max_percent=99.96, min_percent=1),
                  transform=ax.get_transform(aces7mwcs),
                  cmap=orange_transparent)
        
    if n == 240:
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='log',
                                      min_percent=None, max_percent=None,
                                      min_cut=-0.0005, max_cut=0.05,),
                     cmap='gray',
                  transform=ax.get_transform(aces12mwcs),
                    )
        transorange = pl.cm.Oranges.copy()
        transorange.set_under((0,0,0,0))
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='asinh',
                                      min_percent=None, max_percent=99.99,
                                      min_cut=0.05,),
                     cmap=transorange,
                  transform=ax.get_transform(aces12mwcs), )
    


    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]
    cx, cy = cxs[n], cys[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
        
    print(f'{n}|', end='')

    return fig,     

animate(240)

# anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
#                                interval=50)
# anim.save('zoom_anim_cmz_linear_withACES_HI-CO-Dust_m0.35.gif')
# zoom into the CMZ _even more_


nframes = 360
# zoom for 300 frames, then pan
zoomfac = np.hstack([np.geomspace(1, 1/1920., 300),
                     np.ones(60, dtype='float')/1920.])


sgrb2 = SkyCoord.from_name('Sgr B2')
sgra = SkyCoord.from_name('Sgr A')

# pan
cx, cy = ax.wcs.world_to_pixel(sgrb2)
cx2, cy2 = ax.wcs.world_to_pixel(sgrb2)
cxs = np.hstack([np.ones(300)*cx, np.linspace(cx, cx2, 60)])
cys = np.hstack([np.ones(300)*cy, np.linspace(cy, cy2, 60)])
print(zoomfac, cxs, cys)

rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')



rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

aces7m = fits.open('/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
aces7mwcs = WCS(aces7m[0].header)
aces7mrepr,_ = reproject.reproject_interp(aces7m, ww, shape_out=rgb.shape[:2])
aces7mrepr[aces7mrepr < 0] = np.nan

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0


def animate(n, nframes=nframes):
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        
    if n == 180:
        ax.imshow(aces7mrepr, 
                  norm=simple_norm(aces7mrepr, stretch='log', max_percent=99.96, min_percent=1),
                  transform=ax.get_transform(aces7mwcs),
                  cmap=orange_transparent)
        
    if n == 240:
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='log',
                                      min_percent=None, max_percent=None,
                                      min_cut=-0.0005, max_cut=0.05,),
                     cmap='gray',
                  transform=ax.get_transform(aces12mwcs),
                    )
        transorange = pl.cm.Oranges.copy()
        transorange.set_under((0,0,0,0))
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='asinh',
                                      min_percent=None, max_percent=99.99,
                                      min_cut=0.05,),
                     cmap=transorange,
                  transform=ax.get_transform(aces12mwcs), )
    


    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]
    cx, cy = cxs[n], cys[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
        
    print(f'{n}|', end='')

    return fig,     

animate(240)

# anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
#                                interval=50)
# anim.save('zoom_anim_cmz_linear_withACES_HI-CO-Dust_m0.35.gif')
sgrc = SkyCoord.from_name('Sgr C')
sgrc
#[Out]# <SkyCoord (ICRS): (ra, dec) in deg
#[Out]#     (266.15125, -29.47028)>
# zoom into the CMZ _even more_


nframes = 420
# zoom for 300 frames, then pan
zoomfac = np.hstack([np.geomspace(1, 1/1920., 300),
                     np.ones(120, dtype='float')/1920.])


sgrb2 = SkyCoord.from_name('Sgr B2')
sgra = SkyCoord.from_name('Sgr A')
sgrc = SkyCoord.from_name('Sgr C')

# pan
cx, cy = ax.wcs.world_to_pixel(sgrb2)
cx2, cy2 = ax.wcs.world_to_pixel(sgrc)
cxs = np.hstack([np.ones(300)*cx, np.linspace(cx, cx2, 120)])
cys = np.hstack([np.ones(300)*cy, np.linspace(cy, cy2, 120)])

rgb = np.array([simple_norm(img_HI4PI_innergal,       min_percent=0.01, max_percent=99.99, log_a=1e1, stretch='log')(img_HI4PI_innergal),
                simple_norm(img_CO21_innergal,        min_percent=0.01, max_percent=99.99, log_a=3e1, stretch='log')(img_CO21_innergal),
                simple_norm(img_ThermalDust_innergal, min_percent=0.01, max_percent=99.99, log_a=5e2, stretch='log')(img_ThermalDust_innergal)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_scaled = hsv_to_rgb(hsv)
rgb_scaled[rgb_scaled > 1] = 1
rgb_scaled[rgb_scaled < 0] = 0

rgb_full = np.array([simple_norm(img_HI4PI,       min_percent=0.01, max_percent=99.99, log_a=2e1, stretch='log')(img_HI4PI),
                     simple_norm(img_CO21,        min_percent=0.01, max_percent=99.90, log_a=2e1, stretch='log')(img_CO21),
                     simple_norm(img_ThermalDust, min_percent=0.01, max_percent=99.90, log_a=5e2, stretch='log')(img_ThermalDust)]).T.swapaxes(0,1)
hsv = rgb_to_hsv(rgb_full)
hsv[:,:,0] += -0.35  # 0.25 = 90/360
hsv[:,:,0] = hsv[:,:,0] % 1 
rgb_full_scaled = hsv_to_rgb(hsv)
rgb_full_scaled[rgb_full_scaled > 1] = 1
rgb_full_scaled[rgb_full_scaled < 0] = 0

fig = pl.figure(figsize=(10,5), dpi=200, frameon=False)
ax = pl.subplot(1,1,1, projection=WCS(target_header),
                frame_class=EllipticalFrame)
ax.imshow(rgb_full_scaled)
ax.axis('off')



rgbcmz = np.array(PIL.Image.open('gc_fullres_6.jpg'))[::-1,:,:]
wwcmz = WCS(fits.Header.fromtextfile('gc_fullres_6.wcs'))

aces7m = fits.open('/orange/adamginsburg/ACES/mosaics/7m_continuum_mosaic.fits')
aces7mwcs = WCS(aces7m[0].header)
aces7mrepr,_ = reproject.reproject_interp(aces7m, ww, shape_out=rgb.shape[:2])
aces7mrepr[aces7mrepr < 0] = np.nan

aces12m = fits.open('/orange/adamginsburg/ACES/mosaics/12m_continuum_mosaic.fits')
aces12mwcs = WCS(aces12m[0].header)
aces12m[0].data[aces12m[0].data < -0.0005] = 0


def animate(n, nframes=nframes):
    if n == 40:
        ax.imshow(atlasgal[0].data,
          norm=simple_norm(atlasgal[0].data, min_percent=5, max_percent=99.9, stretch='asinh'),
          transform=ax.get_transform(WCS(atlasgal[0].header)),
          cmap=orange_transparent)
    if n == 80:
        ax.imshow(rgbcmz,
          transform=ax.get_transform(wwcmz))
        
    if n == 180:
        ax.imshow(aces7mrepr, 
                  norm=simple_norm(aces7mrepr, stretch='log', max_percent=99.96, min_percent=1),
                  transform=ax.get_transform(aces7mwcs),
                  cmap=orange_transparent)
        
    if n == 240:
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='log',
                                      min_percent=None, max_percent=None,
                                      min_cut=-0.0005, max_cut=0.05,),
                     cmap='gray',
                  transform=ax.get_transform(aces12mwcs),
                    )
        transorange = pl.cm.Oranges.copy()
        transorange.set_under((0,0,0,0))
        ax.imshow(aces12m[0].data,
                     norm=simple_norm(aces12m[0].data, stretch='asinh',
                                      min_percent=None, max_percent=99.99,
                                      min_cut=0.05,),
                     cmap=transorange,
                  transform=ax.get_transform(aces12mwcs), )
    


    dy = dy0 * zoomfac[n]
    dx = dx0 * zoomfac[n]
    cx, cy = cxs[n], cys[n]

    ax.axis((cx-dx, cx+dx, cy-dy, cy+dy))
        
    print(f'{n}|', end='')

    return fig,     

animate(240)

# anim = animation.FuncAnimation(fig, animate, frames=nframes, repeat_delay=5000,
#                                interval=50)
# anim.save('zoom_anim_cmz_linear_withACES_HI-CO-Dust_m0.35.gif')
