# -*- coding: utf-8 -*-
"""
Created on Fri Nov 22 08:11:58 2024

@author: chuffard
"""
# og atn def

# def measure_atn(mask, photo_max,files, f):
#     photo=cv2.imread(files[f])
#     photo_red=photo[:,:,2] ##cv2 reads images as BGR, so red is the third channel
#     attenuation=np.mean(-np.log(photo_red[mask==255]/photo_max[mask==255]))
#     file_name=os.path.basename(files[f])
#     data=pd.DataFrame([[file_name,attenuation]],columns=['file_name','atn'])
#     return(data)


#fix atn def- fixes inf values

# def measure_atn(maskedphotomax, files, f, masked_img):
#     """Measure attenuation based on the ratio of red pixel values."""
#     # Small epsilon to avoid division by zero
#     epsilon = 1e-10
    
#     # Ensure the values are non-zero to avoid NaN results in the calculation
#     photo_red = masked_img[:, :, 2]  # OpenCV uses BGR, so red is the third channel
#     valid_pixels = (maskedphotomax > 0) & (photo_red > 0)  # Filter out invalid pixels

#     # Calculate attenuation safely
#     attenuation = np.mean(-np.log(photo_red[valid_pixels] / (maskedphotomax[valid_pixels] + epsilon)))

#     file_name = os.path.basename(files[f])
#     data = pd.DataFrame([[file_name, attenuation]], columns=['file_name', 'atn'])
    
#     return data

#but we want to adjust back to the old scale, so this file adjusts the new values to the old scale using the linear relationship between the two

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
import numpy as np

atn_OG = pd.read_csv('G:/Deployments/MARS2024B-2025/atn_inf_fix/SES_out_atn_og.csv')
atn_fix = pd.read_csv('G:/Deployments/MARS2024B-2025/atn_inf_fix/SES_out_atn_fix.csv')

#merge the two
atn_adjust= pd.merge(atn_OG, atn_fix, on='file_name')

atn_adjustnoinf= atn_adjust.replace([np.inf, -np.inf], np.nan).dropna(subset=['atn_og'])


atn_adjust.dtypes
# file_name     object
# atn_og       float64
# atn          float64
plt.scatter(atn_adjust['atn'], atn_adjust['atn_og'])

from sklearn.metrics import r2_score
x =atn_adjustnoinf['atn']
y =atn_adjustnoinf['atn_og']

plt.plot(x,y,"+", ms=10, mec="k")
z = np.polyfit(x, y, 1)
y_hat = np.poly1d(z)(x)

plt.plot(x, y_hat, "r--", lw=1)
text = f"$y={z[0]:0.3f}\;x{z[1]:+0.3f}$\n$R^2 = {r2_score(y,y_hat):0.3f}$"
plt.gca().text(0.05, 0.95, text,transform=plt.gca().transAxes,
     fontsize=14, verticalalignment='top')
plt.xlabel('atn fix')
plt.ylabel('atn og')


atn_adjust = atn_adjust.rename(columns={'atn': 'new_atn'})
atncompile= pd.merge(atn_adjust, all_atn_data, on='file_name')



plt.scatter(atncompile['atn_og'], atncompile['atn_og'], label='atn og vs atn og',facecolors='none', edgecolors='k', alpha = 0.5)
#ax1.plot(atncompile['atn_og'], atncompile['new_atn'], label='atn og vs new_atn')
#ax1.plot(atncompile['atn_og'], atncompile['atn_fix'], label='atn og vs atn fix')
plt.scatter(atncompile['atn_og'], atncompile['atn'], label='atn og vs atn', facecolors='orange', edgecolors='none', alpha = 0.5)
plt.ylabel('atn fix')
plt.xlabel('atn og')

plt.legend(loc='best')

plt.show()