import numpy as np
from pylab import *
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')

"""
Explanation: Plots for SFR-Stellar Mass-Size Paper
This is an outline of the results that will go into the first paper.  The first paper will focus on the $$SFR-M_{*}-Size$$ relation, where $$Size \equiv R_e(24)/R_e(r).$$
End of explanation
"""


# Now moving on to the SFR-M*-Size analysis

%run ~/Dropbox/pythonCode/LCSanalyzeblue.py

# using John Moustakas's stellar mass estimates
figure()
plot(s.s.ABSMAG[:,4][s.blueflag2],s.logstellarmass[s.blueflag2],'bo')
xlabel('$M_r$')
ylabel('$ log_{10}(M_*) $')
# r-band limit
rlim=17.7
# distance modulus to Hercules, the furthest cluster
mM=35.97
# absolute mag limit corresponding to r=17.7
Mr=rlim-mM
axvline(x=Mr,ls='--',color='r')
axis([-20,-16,8.5,10.5])
axhline(y=minmass)


"""
Explanation: As of 1/6/16, need to make one more pass through the sample and remove galaxies that are blended with nearby companion.  Not sure if people think the numbers in each panel are useful.  
Galaxies that are blended with a nearby companion are:

99056 - Hercules
103927 - Coma
103933 (AGN) - Coma
140160 - A1367
143485 - MKW11
146607 - Hercules

ALSO running this from ipython and using paperplots().
Converting SDSS Magnitude Limit to Stellar Mass Cut
End of explanation
"""


s.plotsalimcolormag()

"""
Explanation: RESULT:   SDSS mag limit corresponds to a stellar mass cut of approximately $log_{10}(M_*) > 9.5$.
Select Blue Galaxies using NUV-r Color
I have limited the sample to blue galaxies only, using a NUV-r color cut:
self.NUVr=self.s.ABSMAG[:,1] - self.s.ABSMAG[:,4]
self.blueflag2=self.NUVr &lt; 4.1

Some galaxies don't have GALEX data (JM is checking into why this is the case).  For these, I require u-r < 1.8.
We have a total of 138 blue star-forming galaxies with successful GALFIT fits.

70 cluster members
51 near-field galaxies
17 field galaxies
End of explanation
"""


# For blue galaxies only
s.plotSFRStellarmassSizeBlue(blueflag=True,plotbadfits=False)

# to compare size distributions
print 'comparing size ratios for field vs cluster'
f1=s.bluesampleflag & ~s.membflag & ~s.agnflag
m1=s.bluesampleflag & s.membflag & ~s.agnflag
t=ks(s.s.SIZE_RATIO[f1],s.s.SIZE_RATIO[m1])
print 'mean of field = %5.2f +/- %5.2f'%(mean(s.s.SIZE_RATIO[f1]),std(s.s.SIZE_RATIO[f1])/sqrt(1.*sum(f1)))
print 'mean of clust = %5.2f +/- %5.2f'%(mean(s.s.SIZE_RATIO[m1]),std(s.s.SIZE_RATIO[m1])/sqrt(1.*sum(m1)))

s.printsizeblue()

"""
Explanation: SFR-Mass-Size for Blue Galaxies only
End of explanation
"""


s.calc_size_starburst()

"""
Explanation: RESULT: 
The ratio of Re(24)/Re(r) increases as galaxy environment transitions from cluster, to near field,  and to field.  The difference in size ratios is significant at the $3\sigma$ level.
Interestingly, the cluster and field galaxies are both consistent with the star-forming main sequence, even though the star-formation is more compact on average in the cluster galaxies.  Thus, the size of the star-forming region is an important parameter to add to the SFR-Mass analysis when looking at galaxy properties as a function of environment.
Starburst Galaxies
End of explanation
"""


# comparing sizes for sample with Coma removed
nc.plotSFRStellarmassSizeBlue(blueflag=True,plotbadfits=False)
nc.printsize()
ncf1=nc.bluesampleflag & ~nc.membflag & ~nc.agnflag
ncm1=nc.bluesampleflag & nc.membflag & ~nc.agnflag
t=ks(nc.s.SIZE_RATIO[ncf1],nc.s.SIZE_RATIO[ncm1])

"""
Explanation: The Impact of Coma
End of explanation
"""


# stellar mass

print 'comparing stellar mass for field vs cluster'
f1=s.bluesampleflag & ~s.membflag & ~s.agnflag
m1=s.bluesampleflag & s.membflag & ~s.agnflag
t=ks(s.logstellarmass[f1],s.logstellarmass[m1])

# B/T

print ''
print 'comparing B/T for field vs cluster'
f1=s.bluesampleflag & ~s.membflag & ~s.agnflag & s.gim2dflag
m1=s.bluesampleflag & s.membflag & ~s.agnflag & s.gim2dflag
t=ks(s.s.B_T_r[f1],s.s.B_T_r[m1])

# ssfr

print ''
print 'comparing sSFR for field vs cluster'
f1=s.bluesampleflag & ~s.membflag & ~s.agnflag 
m1=s.bluesampleflag & s.membflag & ~s.agnflag 
t=ks(log10(s.ssfr[f1]),log10(s.ssfr[m1]))

# B/A

print ''
print 'comparing B/A for field vs cluster'
f1=s.bluesampleflag & ~s.membflag & ~s.agnflag 
m1=s.bluesampleflag & s.membflag & ~s.agnflag 
t=ks((s.s.SERSIC_BA[f1]),(s.s.SERSIC_BA[m1]))

# ir surface brightness 

print ''
print 'comparing $L{IR}/R_e(24)^2$ for field vs cluster'
f1=s.bluesampleflag & ~s.membflag & ~s.agnflag 
m1=s.bluesampleflag & s.membflag & ~s.agnflag 
t=ks(log10(s.sigma_ir[f1]),log10(s.sigma_ir[m1]))

# size

print ''
print 'comparing Re(24)/Re(r) for field vs cluster'
f1=s.bluesampleflag & ~s.membflag & ~s.agnflag 
m1=s.bluesampleflag & s.membflag & ~s.agnflag 
t=ks((s.s.SIZE_RATIO[f1]),(s.s.SIZE_RATIO[m1]))

"""
Explanation: RESULT: 
The difference in size ratios between cluster and field galaxies is not as significant once Coma is removed from the sample.  The difference between the field and cluster galaxies is at the $2\sigma$ level.  The conclusion is that Coma is important or unique among the clusters in the sample.  Perhaps environmental effects are stronger in the more X-ray luminous environment, or maybe the sample size gets too small once Coma is removed (weak, I admit).
Checking for Other Hidden Systematics
Need to make sure that we are not seeing the effect of some
parameter that is linked with environment.  For example, B/T
is strongly correlated with environments.
Check:

stellar mass
B/T
sSFR 
B/A
End of explanation
"""


figure(figsize=(12,5))
subplot(1,2,1)
subplots_adjust(wspace=.5)
pcolor=s.s.CLUSTER_LX
pcolorlabel='$log_{10}(L_X)$'
#pcolor=s.s.SIGMA_5
#pcolor=sqrt(s.s.DR_R200**2 + s.s.DELTA_V**2)
#pcolor=10.**s.logstellarmass
#pcolor=s.massdensity
#pcolor=s.s.B_T_r
#pcolorlabel='$log_{10}(B/T)$'

f=s.bluesampleflag & ~s.agnflag & s.membflag 
scatter(log10(s.sigma_ir[f]),log10(s.ssfr[f]*1.e9),c=log10(pcolor[f]),s=60)
f=s.bluesampleflag & ~s.agnflag & ~s.membflag 
scatter(log10(s.sigma_ir[f]),log10(s.ssfr[f]*1.e9),c=log10(pcolor[f]),s=60,marker='^')
#f=s.bluesampleflag & ~s.agnflag & s.fieldflag
#plot(log10(s.sigma_ir[f]),log10(s.ssfr[f]*1.e9),'ks',mfc='None',label='Field')
colorbar(fraction=.08,label=pcolorlabel)
xlabel('$log_{10}(\Sigma_{ir}) $')
ylabel('$sSFR/Gyr$')

subplot(1,2,2)
#pcolor=s.s.CLUSTER_LX
#pcolorlabel='$log_{10}(L_X)$'
#pcolor=s.s.SIGMA_5
#pcolor=sqrt(s.s.DR_R200**2 + s.s.DELTA_V**2)
#pcolor=10.**s.logstellarmass
#pcolor=s.massdensity
pcolor=s.s.B_T_r
pcolorlabel='$log_{10}(B/T)$'

f=s.bluesampleflag & ~s.agnflag & s.membflag & s.gim2dflag
scatter(log10(s.sigma_ir[f]),log10(s.ssfr[f]*1.e9),c=log10(pcolor[f]),s=60)
f=s.bluesampleflag & ~s.agnflag & ~s.membflag & s.gim2dflag
scatter(log10(s.sigma_ir[f]),log10(s.ssfr[f]*1.e9),c=log10(pcolor[f]),s=60,marker='^')
#f=s.bluesampleflag & ~s.agnflag & s.fieldflag
#plot(log10(s.sigma_ir[f]),log10(s.ssfr[f]*1.e9),'ks',mfc='None',label='Field')
colorbar(fraction=.08,label=pcolorlabel)
xlabel('$log_{10}(\Sigma_{ir}) $')
#ylabel('$sSFR/Gyr$')

figure()

#pcolor=s.s.CLUSTER_LX
#pcolorlabel='$log_{10}(L_X)$'
#pcolor=s.s.SIGMA_5
#pcolor=sqrt(s.s.DR_R200**2 + s.s.DELTA_V**2)
#pcolor=10.**s.logstellarmass
#pcolor=s.massdensity
pcolor=s.s.B_T_r
pcolorlabel='$log_{10}(B/T)$'

f=s.bluesampleflag & ~s.agnflag & s.membflag & s.gim2dflag
scatter(log10(s.sigma_ir[f]),log10(s.ssfr[f]*1.e9),c=log10(pcolor[f]),s=60,label='Cluster')
f=s.bluesampleflag & ~s.agnflag & ~s.membflag & s.gim2dflag
scatter(log10(s.sigma_ir[f]),log10(s.ssfr[f]*1.e9),c=log10(pcolor[f]),s=60,marker='^',label='Field')
#f=s.bluesampleflag & ~s.agnflag & s.fieldflag
#plot(log10(s.sigma_ir[f]),log10(s.ssfr[f]*1.e9),'ks',mfc='None',label='Field')
colorbar(fraction=.08,label=pcolorlabel)
xlabel('$log_{10}(\Sigma_{ir}) $')
ylabel('$log_{10}(sSFR/Gyr)$')
legend(scatterpoints=1,loc='upper left')

"""
Explanation: RESULT: 
Difference in size ratio between cluster and field galaxies can't be explained by systematic differences in stellar mass, B/T, sSFR, or B/A.
IR Surface Brightness
End of explanation
"""


 %run ~/github/LCS/python/Python3/LCS_MS_rf_plots.py

"""
Explanation: RESULT: 
Compactness of star-forming region is correlated with B/T.  However, you would expect the two quantities to be correlated.  The stellar mass density must increase as B/T increases, and stellar mass density is correlated with $\Sigma_{IR}$ because stellar mass correlated with SFR, and optical size correlates with IR size.
PAPER 2
Add SFRs to analysis.  Focus on size, stellar mass, SFR relation

field/cluster samples are comparable in terms of stellar mass, B/T, SFR
cluster galaxies have smaller size
cluster and field galaxies are still consistent with the SF main sequence

 RESULTS  

blue galaxies in dense environments have sSFRs that are consistent with the SF main sequence despite having more centrally-concentrated SF disks.
starburst galaxies have more centrally-concentrated SF disks when compared with galaxies on the SF main sequence, and relative size of SF disk does not appear to vary with environment for these galaxies.
Coma has an unusually high fraction of starburst galaxies

Statistics for Comparing SFR between core and external galaxies
End of explanation
"""


g.calcstats()

g.calcstats(allgals=False)

"""
Explanation: Take away
used two measures of SF: SFR-Mass (main sequence), and sSFR.
for SFR vs mass and sSFR vs mass, I fit a first order polynomial to the external galaxies with $9.5 < \log(M/M_\star) < 10.5$.  

We then calculate distance from MS (parallel to y axis) and distance perpendicular to MS
I comaparand difference in sSFR (
End of explanation
"""


 %run ~/github/LCS/python/Python3/LCS_MS_rf_plots.py

# plot distance from ms vs size
g.plotsizevsmsdist()
plt.yscale('log')
plt.legend()
plt.axvline(x=0)
plt.axhline(y=1)


"""
Explanation: where are small galaxies in SFR-M* plane
End of explanation
"""


g.s.columns

plt.figure()
plt.plot(g.s.fre1, g.s.fcre1,'k.')
plt.plot(g.s.fre1[g.sampleflag], g.s.fcre1[g.sampleflag],'bo')
plt.plot(g.s.fre1[g.agnflag], g.s.fcre1[g.agnflag],'g*')
plt.plot(g.s.fre1[~g.galfitflag], g.s.fcre1[~g.galfitflag],'co',markersize=9, mfc='None')
plt.xlabel('Re no PSF conv')
plt.ylabel('Re with PSF conv')
plt.axis([-.5,12,-.5,12])
#plt.xscale('log')
#plt.yscale('log')

plt.figure()
#plt.plot(g.s.fmag1, g.s.fcre1,'k.')
plt.plot(g.s.fmag1[g.sampleflag], g.s.fcmag1[g.sampleflag],'bo')
#plt.plot(g.s.fmag1[g.agnflag], g.s.fcmag1[g.agnflag],'g*')
plt.plot(g.s.fmag1[~g.galfitflag], g.s.fcmag1[~g.galfitflag],'co',markersize=6,alpha=.3)
plt.xlabel('mag no PSF conv')
plt.ylabel('mag with PSF conv')
#plt.axis([10,18,10,18])
#plt.xscale('log')
#plt.yscale('log')

plt.figure()
dr = g.s.fcre1 - g.s.fre1
dm = g.s.fcmag1 - g.s.fmag1
#plt.plot(g.s.fmag1, g.s.fcre1,'k.')
massflag = (g.logstellarmass > 9.7)
flag = g.lirflag & ~g.galfitflag & g.gim2dflag & massflag & ~g.agnflag & g.sizeflag
#plt.plot(g.s.fmag1[g.agnflag], g.s.fcmag1[g.agnflag],'g*')
plt.plot(dm[flag], dr[flag],'co',markersize=6,alpha=.3)
#plt.plot(dm[g.sampleflag], dr[g.sampleflag],'bo',alpha=.3)
plt.xlabel('fcmag1 - fmag1')
plt.ylabel('fcre1 - fre1')
plt.axis([-2,2,-15,15])
plt.axvline(x=0)
plt.axhline(y=0)
#plt.xscale('log')
#plt.yscale('log')

sum(flag)

"""
Explanation: constraint on disk shrinking time
use sample toy model from paper
End of explanation
"""


