# -*- coding: utf-8 -*-
"""
Created on Thu Jul 22 11:35:43 2021

@author: csag4207
"""

import sys
sys.path.append('C:/Users/csag4207/Documents/forschung/python/scripts')
import vibrodyn500

from os import listdir
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

filenames = []
for file in listdir('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/data/tensile_2'):
    if file.endswith(".txt"):
        filenames.append(file)

#%% extract the data
data = {}

for i in filenames:
    if 'curve' not in i:
        data[i[:-4]] = {}

for i in filenames:
    if 'curve' not in i:
        data[i[:-4]]['meta'] = vibrodyn500.extract_meta('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/data/tensile_2/'+ i, '/t', 2300) # luckily seems that 2300 is the exact file length at (somehow a factor of 10 is somewhere as the original file is 24 kB???)
    if 'curve' in i:
        data['_'.join(i[:-4].split('_')[:-2])]['curve_' + i[:-4].split('_')[-1]] = vibrodyn500.extract_vd('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/data/tensile_2/'+ i, '/t')

data['Viskose_KF_28dtex_80'] = {}

data['Viskose_KF_28dtex_80']['meta'] = vibrodyn500.extract_meta('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/data/Viskose_KF_28dtex_80.txt', '/t', 2300)
# data['_'.join(i[:-4].split('_')[:-2])]['curve_' + i[:-4].split('_')[-1]] = vibrodyn500.extract_vd('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/data/'+ i, '/t')

#%%  extract the information from the arrays

header = data['05pc_NaOH_29_9dt_107']['meta'][2]
units = data['05pc_NaOH_29_9dt_107']['meta'][3]

for i in data:
    data[i]['mean'] = np.array([np.mean(np.array(data[i]['meta'][4:14]).astype('float'), axis=0), np.std(np.array(data[i]['meta'][4:14]).astype('float'), axis=0)])

#%% extract the prefactor from the deterimine initial fineness of the fibers

data['05pc_NaOH_29_9dt_107']['init'] = np.array([29.9])
data['10pc_CA_25pc_NaOH_27_3dt_100']['init'] = np.array([27.3])
data['1pc_NaOH_27_15dt_108']['init'] = np.array([27.15])
data['25pc_NaOH_28_7dt_109']['init'] = np.array([28.7])
data['2pc_CA_25pc_NaOH_29_8dt_104']['init'] = np.array([29.8])
data['4pc_CA_25pc_NaOH_30_2dt_103']['init'] = np.array([30.2])
data['6pc_CA_05pc_NaOH_27_8dt_105']['init'] = np.array([27.8])
data['6pc_CA_1pc_NaOH_29_8dt_106']['init'] = np.array([29.8])
data['6pc_CA_25pc_NaOH_26_9dt_102']['init'] = np.array([26.9])
data['8pc_CA_25pc_NaOH_26_3dt_101']['init'] = np.array([26.3])
data['2pc_CA_25pc_NaOH_27.2_dtex_144']['init'] = np.array([27.2])
#from the determination on the 21.10.2022
data['1pc_NaOH_viscose_320']['init'] = np.array([29.04])
data['25pc_NaOH_viscose_319']['init'] = np.array([28.83])
data['2pc_CA_viscose_318']['init'] = np.array([32.05])
data['6pc_CA_twice_viscose_317']['init'] = np.array([28.05])
data['8pc_CA_twice_viscose_316']['init'] = np.array([29.34])

data['Viskose_KF_28dtex_80']['init'] = np.array([data['Viskose_KF_28dtex_80']['mean'][0,0]]) # per definition

err_fine = 0.2 # dtex

special = {}
special['2pc_CA_25pc_NaOH_29_8dt_104'] = data.pop('2pc_CA_25pc_NaOH_29_8dt_104')
special['2pc_CA_viscose_318'] = data.pop('2pc_CA_viscose_318')

#%% calculate what has been added on the fibers

titer_addition = []

for i in data:
    titer_addition.append([i, np.subtract(np.divide(data[i]['mean'][0,0], data[i]['init'][0]), 1), np.divide(data[i]['mean'][0,0], data[i]['init'][0])*np.sqrt((data[i]['mean'][1,0]/data[i]['mean'][0,0])**2 + (err_fine/data[i]['init'][0])**2)])

#%% show the data in a plot with error

plt.figure()
for i in data:
    if 'CA_25pc' in i:
        plt.bar(i, data[i]['mean'][0,0], yerr = data[i]['mean'][1,0], label='_'.join(i.split('_')[:2]))
plt.bar('Viskose_KF_28dtex_80', data['Viskose_KF_28dtex_80']['mean'][0,0], yerr = data['Viskose_KF_28dtex_80']['mean'][1,0])
plt.xticks(rotation=30)
plt.ylim([25,40])
plt.legend()
plt.title('absolute titer of the treated samples')
plt.show()


#%% divide by the initial fineness to see the relative change

sorting = ['25pc_NaOH_viscose_319', '2pc_CA_25pc_NaOH_27.2_dtex_144', '4pc_CA_25pc_NaOH_30_2dt_103', '6pc_CA_25pc_NaOH_26_9dt_102', '8pc_CA_25pc_NaOH_26_3dt_101', '10pc_CA_25pc_NaOH_27_3dt_100']
twice = ['6pc_CA_twice_viscose_317', '8pc_CA_twice_viscose_316']

plt.rcParams.update({'font.size': 18})

plt.figure(figsize=(10,6))
for i in sorting:
    plt.bar(i, np.divide(data[i]['mean'][0,0], data[i]['init'][0]), yerr = np.divide(data[i]['mean'][0,0], data[i]['init'][0])*np.sqrt((data[i]['mean'][1,0]/data[i]['mean'][0,0])**2 + (err_fine/data[i]['init'][0])**2))
for i in twice:
    plt.bar(i, np.divide(data[i]['mean'][0,0], data[i]['init'][0]), yerr = np.divide(data[i]['mean'][0,0], data[i]['init'][0])*np.sqrt((data[i]['mean'][1,0]/data[i]['mean'][0,0])**2 + (err_fine/data[i]['init'][0])**2), alpha=0.3, color='r')

plt.xticks([i for i in sorting] + [i for i in twice], ['_'.join(i.split('_')[:2]) for i in sorting] + ['twice_' + '_'.join(i.split('_')[:1]) for i in twice], rotation=20)
plt.ylim([0.9,1.4])
plt.ylabel(r'$\frac{titer_{CA}}{titer_{0}}$')

plt.title('relative change titer')
plt.show()

# plt.savefig('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/pic/CA_coating_titer_change.png', dpi=500)

#%% plot the influence of the NaOH on the fiber titer

sorting_2= ['05pc_NaOH_29_9dt_107', '1pc_NaOH_27_15dt_108', '25pc_NaOH_28_7dt_109']
corrected=['0.5pc NaOH', '1pc NaOH', '2.5pc NaOH']

naoh_addition = []

reference = plt.figure()
for i in sorting_2:
    plt.bar(i, np.divide(data[i]['mean'][0,0], data[i]['init'][0]), yerr = np.divide(data[i]['mean'][0,0], data[i]['init'][0])*np.sqrt((data[i]['mean'][1,0]/data[i]['mean'][0,0])**2 + (err_fine/data[i]['init'][0])**2))
    naoh_addition.append([i, np.divide(data[i]['mean'][0,0], data[i]['init'][0]), np.divide(data[i]['mean'][0,0], data[i]['init'][0])*np.sqrt((data[i]['mean'][1,0]/data[i]['mean'][0,0])**2 + (err_fine/data[i]['init'][0])**2)])
plt.xticks([i for i in sorting_2], corrected, rotation=20)
plt.ylim([0.95, 1.15])
plt.title('fiber change NaOH swelling')
plt.show()

# it seems there is some randomness in the titer calculation which bases on different fibers, possibly there is some dispersion in the initial diameter of the fibers
# probably there is a difference in the diameter. There were some monofibers that actually fusioned, so the problem seems valid
# so if the titer is higher it means there is more mass to vibrate and swing
# so if it comes from the swelling, tha 4pc should also have a higher titer than the 6 or 8 pc ? 

#%% plot the influence on the 6pc from different NaOH concentrations


plt.figure()
for i in data:
    if '6pc_CA' in i:
        plt.bar(i, np.divide(data[i]['mean'][0,0], data[i]['init'][0]), yerr = np.divide(data[i]['mean'][0,0], data[i]['init'][0])*np.sqrt((data[i]['mean'][1,0]/data[i]['mean'][0,0])**2 + (err_fine/data[i]['init'][0])**2))
# plt.bar('Viskose_KF_28dtex_80', data['Viskose_KF_28dtex_80']['mean'][0,0], yerr = data['Viskose_KF_28dtex_80']['mean'][1,0])
plt.title('change of titer 6pc CA sample')
plt.xticks([i for i in data if '6pc_CA' in i], corrected+['CA twice'], rotation=10)
plt.ylim([0.95, 1.15])
plt.show()

# plt.savefig('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/pic/CA_coating_naoh-change_titer.png', dpi=500)


#%% check the influence on the tenacity

plt.figure()
for i in sorting:
    plt.bar(i, data[i]['mean'][0, 3], yerr = data[i]['mean'][1,3])
for i in twice:
    plt.bar(i, data[i]['mean'][0, 3], yerr = data[i]['mean'][1,3])
plt.xticks([i for i in data if 'CA_25pc' in i] + [i for i in twice], ['_'.join(i.split('_')[:1]) for i in data if 'CA_25pc' in i] + ['twice_' + '_'.join(i.split('_')[:1]) for i in twice], rotation=30)
# plt.title('tenacity')
plt.ylabel('tenacity /cN/tex')
plt.subplots_adjust(bottom=0.2)
plt.ylim([7.5,15])
plt.show()


#%% check the influence on the tenacity

plt.figure()
for i in sorting_2:
    plt.bar(i, data[i]['mean'][0, 3], yerr = data[i]['mean'][1,3])
# for i in twice:
#     plt.bar(i, data[i]['mean'][0, 3], yerr = data[i]['mean'][1,3])
# plt.xticks([i for i in data if 'CA_25pc' in i] + [i for i in twice], ['_'.join(i.split('_')[:1]) for i in data if 'CA_25pc' in i] + ['twice_' + '_'.join(i.split('_')[:1]) for i in twice], rotation=30)
# plt.title('tenacity')
plt.xticks(rotation=25)
plt.ylabel('tenacity /cN/tex')
plt.subplots_adjust(bottom=0.2)
plt.ylim([7.5,15])
plt.show()
#%% check the influence on absolute force

plt.figure()
for i in data:
    if 'CA_25pc' in i:
        plt.bar(i, data[i]['mean'][0, 1], yerr = data[i]['mean'][1,1])
plt.bar('Viskose_KF_28dtex_80', data['Viskose_KF_28dtex_80']['mean'][0,1], yerr = data['Viskose_KF_28dtex_80']['mean'][1,1])
plt.xticks([i for i in data if 'CA_25pc' in i], ['_'.join(i.split('_')[:2]) for i in data if 'CA_25pc' in i], rotation=30)
plt.title('change in force required for break')
# plt.ylim([25,40])
plt.show()


#%% check the change in elongation

plt.figure()
for i in data:
    if 'CA_25pc' in i:
        plt.bar(i, data[i]['mean'][0, 2], yerr = data[i]['mean'][1,2])
plt.bar('Viskose_KF_28dtex_80', data['Viskose_KF_28dtex_80']['mean'][0,2], yerr = data['Viskose_KF_28dtex_80']['mean'][1,2])
plt.xticks([i for i in data if 'CA_25pc' in i], ['_'.join(i.split('_')[:2]) for i in data if 'CA_25pc' in i], rotation=30)
# plt.ylim([25,40])
plt.title('change in elongation')
plt.show()

#%%make neat for a possible publication

cmap=plt.get_cmap('PuRd')

sorting = ['25pc_NaOH_viscose_319', '2pc_CA_25pc_NaOH_27.2_dtex_144', '4pc_CA_25pc_NaOH_30_2dt_103', '6pc_CA_25pc_NaOH_26_9dt_102', '6pc_CA_twice_viscose_317', '8pc_CA_25pc_NaOH_26_3dt_101', '8pc_CA_twice_viscose_316', '10pc_CA_25pc_NaOH_27_3dt_100']

labels=['0%', '2%', '4%', '6%', '8%', '10%']

colors=[cmap(i) for i in np.array([0.29375, 0.3875 , 0.48125, 0.575  , 0.66875, 0.7625 , 0.85625, 0.95])] #from 2021/cerdia/221005_dvs_ca-viscose (l.277 f) selection_3

plt.rcParams.update({'font.size': 18})

fig, axs = plt.subplots(figsize=(10,6))
k=0
for i in sorting:
    if '6pc' not in i and '8pc' not in i:
        axs.bar(i, np.divide(data[i]['mean'][0,0], data[i]['init'][0]), color=colors[k], yerr = np.divide(data[i]['mean'][0,0], data[i]['init'][0])*np.sqrt((data[i]['mean'][1,0]/data[i]['mean'][0,0])**2 + (err_fine/data[i]['init'][0])**2))
    else:
        if 'twice' not in i:
            axs.bar('_'.join(i.split('_')[:2]), np.divide(data[i]['mean'][0,0], data[i]['init'][0]), color=colors[k], align='edge', width=-0.4, yerr = np.divide(data[i]['mean'][0,0], data[i]['init'][0])*np.sqrt((data[i]['mean'][1,0]/data[i]['mean'][0,0])**2 + (err_fine/data[i]['init'][0])**2))
        if 'twice' in i:
            axs.bar('_'.join(i.split('_')[:2]), np.divide(data[i]['mean'][0,0], data[i]['init'][0]), color='k', alpha=0.5, align='edge', width=0.4, yerr = np.divide(data[i]['mean'][0,0], data[i]['init'][0])*np.sqrt((data[i]['mean'][1,0]/data[i]['mean'][0,0])**2 + (err_fine/data[i]['init'][0])**2) )
    k=k+1

axs.set_xticklabels(labels, rotation=20)

plt.ylim([0.9,1.4])
plt.ylabel(r'$\frac{titer_{CA}}{titer_{0}}$')
plt.axhline(1, 0, 1)

# plt.title('relative change titer')
plt.show()

# plt.savefig('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/pic/ca-visc/CA_coating_titer_change.png', dpi=500)
# to_save= Image.open('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/pic/ca-visc/CA_coating_titer_change.png').convert('RGB')
# to_save.save('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/pic/ca-visc/CA_coating_titer_change.jpg')

#%% replot

fig, axs = plt.subplots()
k=0
for i in sorting:
    if '6pc' not in i and '8pc' not in i:
        axs.bar(i, data[i]['mean'][0, 3], color=colors[k], yerr = data[i]['mean'][1,3])
    else:
        if 'twice' not in i:
            axs.bar('_'.join(i.split('_')[:2]), data[i]['mean'][0, 3], color=colors[k], align='edge', width=-0.4, yerr = data[i]['mean'][1,3])
        if 'twice' in i:
            axs.bar('_'.join(i.split('_')[:2]), data[i]['mean'][0, 3], color='k', alpha=0.3, align='edge', width=0.4, yerr = data[i]['mean'][1,3])
    k=k+1

axs.set_xticklabels(labels, rotation=30)
# plt.title('tenacity')
plt.ylabel('tenacity /cN/tex')
plt.subplots_adjust(bottom=0.15)
plt.ylim([7.5,15])
plt.show()

# plt.savefig('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/pic/ca-visc/CA_coating_tenacity_change.png', dpi=500)
# to_save= Image.open('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/pic/ca-visc/CA_coating_tenacity_change.png').convert('RGB')
# to_save.save('C:/Users/csag4207/Documents/forschung/arbeit/2021/cerdia/pic/ca-visc/CA_coating_tenacity_change.jpg')
