# %%

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Load the dataset
data = pd.read_csv('C:/Users/M.Lindner_Lokal/GitLab/diss_software/data/data_system/Data310823_merge_complete.csv', low_memory=False)
# Retrieve and print column names
column_names = data.columns.tolist()
print(column_names)

data['Pges_kW'] = data['Pges'] / 1000
# Compute correlations

correlations = data[['Pges_kW','WKM_eCH45150Leistung_elek_aktuell']].corr()
print(correlations)

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(10, 7))

# Generate a custom colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)

# Draw the heatmap
sns.heatmap(correlations, cmap=cmap, annot=True, vmax=1, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5})

plt.title('Correlation Heatmap between Machine Operations')
plt.show()


# %%
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots(figsize=(10, 6))

# Twin the axes for two different y-axes
ax2 = ax1.twinx()
# ax3 = ax1.twinx()
# Plot data
ln1 = ax1.plot(data['Pges_kW'], label='Electric Power EMAG GT', color='lightgray')
ln2 = ax1.plot(data['WKM_eCH45150Leistung_elek_aktuell'], label='Electric Power eChiller45', color='black',linestyle='dotted')
ln3 = ax2.plot(data['HKK_KWV100ThHy_intPU100'], label='Cooling temperature EMAG GT', color='black')

# Set y-axis labels
ax1.set_ylabel('Power in kW', fontsize=16)
ax2.set_ylabel('Cooling temperature in °C', color='black',fontsize=16)

# Set the x-axis label
ax1.set_xlabel('Time in s', fontsize=16)
ax1.tick_params(axis='both', which='major', labelsize=16)  # Schriftgröße für Haupt-Ticks
# Combine legends
lns = ln1 + ln2 + ln3
labs = [l.get_label() for l in lns]
ax1.legend(lns, labs, loc='upper center', bbox_to_anchor=(0.5, -0.1), ncol=3, fontsize=16)
# plt.grid(True, which='major', linestyle='-', linewidth=0.5, color='grey', alpha=0.5)  # Hauptgitterlinien
# plt.title('Machine Operations Over Time')
#plt.savefig('dependency_power_vs_time.png')
plt.tight_layout()
plt.savefig('dependency_power_vs_time.svg', format='svg')
# Display the plot
plt.show()


# %%
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Load the data
data = pd.read_csv('Data_140823.csv')

def compute_lagged_correlation(series1, series2, max_lag=1800): #1800 = 30min
    """
    Compute lagged correlations between two series.
    """
    correlations = []
    lags = list(range(-max_lag, max_lag + 1))
    for lag in lags:
        if lag < 0:
            correlations.append(series1[:lag].corr(series2[-lag:]))
        elif lag == 0:
            correlations.append(series1.corr(series2))
        else:
            correlations.append(series1[lag:].corr(series2[:-lag]))
    return lags, correlations

# Compute lagged correlations for all combinations
lags_m1_m2, corr_m1_m2 = compute_lagged_correlation(data["Pges"], data["WKM_eCH45150Leistung_elek_aktuell"])
#lags_m1_m3, corr_m1_m3 = compute_lagged_correlation(data["Pges"], data["ThSp_VC100E195ThHy_T_mi"])
#lags_m2_m3, corr_m2_m3 = compute_lagged_correlation(data["WKM_eCH45150Leistung_elek_aktuell"], data["ThSp_VC100E195ThHy_T_mi"])



# Plotting the lagged correlations
plt.figure(figsize=(10,6))
plt.plot(lags_m1_m2, corr_m1_m2, color='black')
# plt.title('Lagged Correlation: EMAG GT vs eChiller45')
plt.xlabel('Lags', fontsize=16)
plt.ylabel('Correlation coefficient', fontsize=16)
plt.grid(True, which='major', linestyle='-', linewidth=0.5, color='grey', alpha=0.5)  # Hauptgitterlinien
#plt.legend()
ax = plt.gca()  # Greift auf das aktuelle Achsen-Objekt zu
ax.tick_params(axis='both', which='major', labelsize=16)  # Schriftgröße für Haupt-Ticks
# plt.subplot(3, 1, 2)
# plt.plot(lags_m1_m3, corr_m1_m3, color="green")
# plt.title('Lagged Correlation: EMAG GT vs Cold Storage')
# plt.xlabel('Lags')
# plt.ylabel('Correlation')
# plt.legend()

# plt.subplot(3, 1, 3)
# plt.plot(lags_m2_m3, corr_m2_m3, color="red")
# plt.title('Lagged Correlation: eChiller45 vs cold Storage')
# plt.xlabel('Lags')
# plt.ylabel('Correlation')
# plt.legend()

plt.tight_layout()
# plt.savefig('laggedcorrelation.png')
plt.savefig('laggedcorrelation.svg', format='svg')
plt.show()




# %%
# Logical Boolean Analyse
import pandas as pd

# Load your data

# Load your data
data = pd.read_csv('Data310823_merge_complete.csv', low_memory=False)

# Convert both columns to boolean type
# Invert the boolean value for Machine A, since True means it's disabled (not operating)
data['WZM_VLC100GT972Zust_NCEE_Mode_3'] = ~data['WZM_VLC100GT972Zust_NCEE_Mode_3'].astype(bool)
data['WKM_eCH45150Zust_B'] = data['WKM_eCH45150Zust_B'].astype(bool)

WZM = data['WZM_VLC100GT972Zust_NCEE_Mode_3']
Chiller = data['WKM_eCH45150Zust_B']

# Mutual Exclusion
mutual_exclusion = (WZM  ^ Chiller).all()  # XOR operation, .all() checks if all values are True

# Concurrent Operation
concurrent_operation = (WZM & Chiller).any()  # AND operation, .any() checks if any value is True

# Conditional Dependency
WZM_implies_Chiller = (~WZM  | Chiller).all()  # NOT A OR B, .all() checks if all values are True
Chiller_implies_WZM = (~Chiller | WZM ).all()

# Print the results
print(f"Mutual Exclusion: {mutual_exclusion}")
print(f"Concurrent Operation: {concurrent_operation}")
print(f"Machine WZM operation implies Machine Chiller operation: {WZM_implies_Chiller}")
print(f"Machine Chiller operation implies Machine WZM operation: {Chiller_implies_WZM}")


# Nur Flexible Lasten
abhaengigkeits_matrix = np.array([
    [0, 1],  # Maschine 1 'EMAGT' ist abhängig von Maschine 2
    [0, 0],  # Maschine 2 'Chiller' ist abhängig von keiner Maschine

])



# Berechnung des Grades der Abhängigkeit für jede Maschine
grad_abhaengigkeit = []

for i in range(abhaengigkeits_matrix.shape[0]):
    # Berechne den Grad der Abhängigkeit als Verhältnis der abhängigen Maschinen zu allen anderen Maschinen
    abhaengig = np.count_nonzero(abhaengigkeits_matrix[i] == 1)
    gesamt = abhaengigkeits_matrix.shape[0] - 1  # Anzahl der anderen Maschinen
    grad = abhaengig / gesamt
    grad_abhaengigkeit.append(grad)

# Ausgabe des Grades der Abhängigkeit für jede Maschine
for i, grad in enumerate(grad_abhaengigkeit, start=1):
    print(f"Maschine {i}: Grad der Abhängigkeit = {grad:.2f}")
# %%
#  Create Flex Space of EMAG GT und Chiller und Speicher

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.colors import LinearSegmentedColormap
colors = ["black", (0.8, 0.8, 0.8)]  # Schwarz bis helles Grau, kein reines Weiß
cmap = LinearSegmentedColormap.from_list("custom_gray", colors, N=500)

######
def plot_machine(ax, leistung, dauer, aenderungsrate, unabhaengigkeit, cmap, norm):
    heat = cmap(norm(unabhaengigkeit))
    #heat = plt.cm.plasma(unabhaengigkeit)
    
    # Plot the top surface
    Z = aenderungsrate * np.ones_like(leistung)
    ax.plot_surface(leistung, dauer, Z, color=heat,shade=False)#, alpha=1)
    
    # Plot the bottom surface
    Z = np.zeros_like(leistung)
    ax.plot_surface(leistung, dauer, Z, color=heat,shade=False, alpha=0.5)
    
    # Plot vertical edges to create a 3D volume
    for i in [0, 1]:
        for j in [0, 1]:
            ax.plot([leistung[i, j], leistung[i, j]], 
                    [dauer[i, j], dauer[i, j]], 
                    [0, aenderungsrate], 
                    color=heat)

# Daten berechnet aus EFDM 1 
leistung3 = np.array([[0.2, 2.289], [0.2, 2.289]]) # Power state max von WZM GT
dauer3 = np.array([[8, 8], [0, 0]]) # Holding Duration max / min in h 
aenderungsrate3 = 0.320 # Gradienten eintragen
abhaengigkeit3 = 1 #


# Daten für Chiller + Kältemaschine
leistung4 = np.array([[0.3, 14.5], [0.3, 14.5]])  # Power State Chiller min max aus handbuch
dauer4 = np.array([[3, 3], [0.5, 0.5]])  # Dauer 
aenderungsrate4 = 0.005  # Änderungsrate in kW/s
abhaengigkeit4 = 0 # 

# %%
# Erstellen des kombinierten Plots
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')

# Norm und Colormap für beide Maschinen gleich setzen
# cmap = plt.cm.gray
norm = mcolors.Normalize(vmin=0, vmax=1)

# Plot für Maschine 3
plot_machine(ax, leistung3, dauer3, aenderungsrate3, abhaengigkeit3, cmap, norm)

# Plot für Maschine 4
plot_machine(ax, leistung4, dauer4, aenderungsrate4, abhaengigkeit4, cmap, norm)

# Setzen der Achsenbeschriftungen
# ax.set_xlabel('Power in kW')
# ax.set_ylabel('Duration in h')
# ax.set_zlabel('Rate of Change in kW/s')

ax.set_xlabel('Power in kW', fontsize=16)
ax.set_ylabel('Duration in h',fontsize=16)
ax.set_zlabel(r'$\nabla$P in kW/s',fontsize=16)
ax.tick_params(axis='both', labelsize=16) 
plt.tight_layout(pad=0.1)

# Setze den gleichen Wertebereich für beide Datenpunkte
ax.set_xlim([0, max(leistung3.max(), leistung4.max())])
ax.set_ylim([0, max(dauer3.max(), dauer4.max())])
ax.set_zlim([0, max(aenderungsrate3, aenderungsrate4)])

# Erstelle ein ScalarMappable-Objekt mit der zuvor definierten Colormap und Normalisierung
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])

# Erstelle die Farblegende mit der gleichen Colormap und Normalisierung
cbar = plt.colorbar(sm, orientation='horizontal', fraction=0.05, pad=0.1, label='Degree of dependency', alpha=0.5)
cbar.set_ticks(np.linspace(0, 1, 11))
cbar.solids.set_edgecolor("face")  # Setze die Kantenfarbe der Farbflächen in der Legende
# Setze die Tick-Größe der Farbskala
cbar.ax.tick_params(labelsize=16)  # Passe die Zahl entsprechend an
cbar.set_label('Degree of dependency',fontsize=16)
# Anpassen der Position der Farblegende
#cbar.ax.set_position([0.15, -0.05, 0.7, 0.02])

# Anzeigen des Plots
#plt.tight_layout(pad=0.1)
#plt.savefig('flexspace_emag_chiller.png')
plt.savefig('flexspace_emag_chiller.svg', format='svg')
plt.show()

