# --------------------------------------------------------------
# Python script for the analysis of FEA results
# 
#
#
# Ronald Wagner
# DLR Braunschweig
# 30.11.2018
# --------------------------------------------------------------

# Import the required libraries

#---------------------------------------------------------------

import pandas as pd
import xlsxwriter
import numpy as np
import matplotlib.pyplot as plt

 # define functions

def createDataColumn(row,col,data,data_modification):
    """
    This function creates excel columns from data
    Input:
        row - number of the row in excel
        col - number of the column in excel
        data - input data for the excel sheet
        data_modification - modifyer for the input data
    """
    for i in (data):
        worksheet.write_number  (row,col,i/data_modification)
        row += 1
        
def createInput(input_string):
    """
    This function read the input data of the FEA from a text file
    Input:
        input_string - name of the input data
    Output: 
        values - the input data 
    """
    data = np.loadtxt(input_string)
    values = data[:]
    return values
        

#------------------------------------------------------------------------------   
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
#
# Name of the Finite Element Analysis Modell    
#
#------------------------------------------------------------------------------   
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------ 


myName = ['C30_Z_1333_ß_30']

# define axis title 

x_axis = ['Rotation [rad]']
y_axis = ['Reaction Moment M [kNmm]']
max_load = ['Numerical Collapse Load [kNmm]']

# method which is evaluated

method = ['LRSM']

# axis of perturbation approach

pert_axis = ['LRSM radius-to-shell radius ratio, Rs/R']

# limits for the perturbation iteration

Pert_START = 1
Pert_END = 21

for jc in range(0,1,1):
    filename = 'Design_'+str(myName[jc])+'_003.xlsx'
    workbook = xlsxwriter.Workbook(filename)
    workbook = xlsxwriter.Workbook(filename, {'nan_inf_to_errors': True})
    worksheet = []
    for ic in range(Pert_START,Pert_END,1):
        
        # define strings for excel sheet tabs
        
        myString = str(myName[jc])+'_LRSM_FC_Loop-'+str(ic)
        myString2 = str(myName[jc])+'-'+str(ic)
        worksheet =  workbook.add_worksheet(myString2)
        
        # read data
        
        values_N = createInput('Rf_'+str(myString)+'.txt')
        values_w = createInput('u_'+str(myString)+'.txt')
        values_N3y = createInput('v_'+str(myName[jc])+'.txt')

        # bold letter definition
        
        bold = workbook.add_format({'bold': 1})        
        
        # Adjust the column width.
        
        worksheet.set_column(0, 0, 20)
        worksheet.set_column(1, 1, 20)
        worksheet.set_column(2, 2, 20)
        worksheet.set_column(3, 3, 20)
        worksheet.set_column(5, 5, 20)
        
        # define title for columns in excel
        
        worksheet.write('A1', y_axis[0], bold)
        worksheet.write('D1', 'Relative Stiffness [N/mm^2]', bold)
        worksheet.write('C1', 'Strain Energy S [Nmm]', bold)
        worksheet.write('B1', x_axis[0], bold)
        worksheet.write('G1', myString2, bold)
        
        # create Datas in Excel (columns)
        
        createDataColumn(3,0,abs(values_N),1000)
        createDataColumn(3,1,abs(values_w),1)
        
        # create xy - chart from Data
        
        chart = workbook.add_chart({'type': 'scatter'})
        
        # Limits for xy chart
        
        max_row=len(values_N)
        for i in range(0,1,1):
            col = i 
            chart.add_series({
                'name':       [myString2, 0, 6],
                'categories': [myString2, 3, col+1, max_row+3, col+1],
                'values':     [myString2, 3, col, max_row+3, col],
                'marker':   {'type': 'none'},
                'line':     {'color': 'red', 'width': 0.5},})
    
        # Configure the chart axes.
        chart.set_y_axis({'num_font':  {'name': 'Times New Roman'}, })
        chart.set_x_axis({'num_font':  {'name': 'Times New Roman'}, })
        chart.set_x_axis({'name': str(x_axis[0]),'min': 0.0,'major_gridlines': {'visible': True,'line':{'color': 'white'}}})
        chart.set_y_axis({'name': str(y_axis[0]),'min': 0.0,'major_gridlines': {'visible': True,'line':{'color': 'white'}}})
        chart.set_legend({'none': True})
        
        # define equation for determination of stiffness and derivative

        worksheet.write_formula('C5', '=(B5-B4)*((A5+A4)/2)+C4')
        worksheet.write_formula('D4', '=(A5-A4)/(B5-B4)')
        worksheet.write_formula('M5', '=MAX(A4:A154)')
        
        # define max. Load

        worksheet.write('M4', max_load[0], bold)
        
        # insert diagramm
        
        worksheet.insert_chart('K10', chart)
        
        # define load vs. perturbation load diagramm
        
        if ic == Pert_END-1:
            myString3 = method[0]
            worksheet =  workbook.add_worksheet(myString3)
            worksheet.write('A1',myString , bold)  
            
            # define input for perturbation diagramm
            
            values_N1 = createInput('N_'+str(myName[jc])+'.txt')
            values_N2 = createInput('u_'+str(myName[jc])+'.txt')
            values_N3 = createInput('v_'+str(myName[jc])+'.txt')
            worksheet.write('G1', myString3, bold)
            
            # define title for columns in excel
            
            worksheet.write('A1', str(y_axis[0]), bold)  
            worksheet.write('B1', str(x_axis[0]), bold)  
            worksheet.write('C1', str(pert_axis[0]), bold) 
            
            # create Datas in Excel (columns)
            
            createDataColumn(3,0,abs(values_N1),1000)
            createDataColumn(3,1,abs(values_N2),1)
            createDataColumn(3,2,abs(values_N3),1)
            
            # create xy - chart from Data
                
            chart = workbook.add_chart({'type': 'scatter'})
    
            # Configure the series of the chart from the dataframe data.
            max_row = len(values_N1)
            for i in range(0,1,1):
                col = i 
                chart.add_series({
                    'name':       [myString3, 0, 6],
                    'categories': [myString3, 3, col+2, max_row+3, col+2],
                    'values':     [myString3, 3, col, max_row+3, col],
                    'marker':     {'type': 'triangle', 'size': 3},})
    
            chart.set_plotarea({'fill':   {'color': '#CAE1FF'}})
    
            # Configure the chart axes.
            chart.set_y_axis({'num_font':  {'name': 'Times New Roman'}})
            chart.set_x_axis({'num_font':  {'name': 'Times New Roman'}})
            chart.set_x_axis({'name': str(pert_axis[0]), 'min': 0.0, 'max': max(values_N3),'major_gridlines': {'visible': True,'line':{'color': 'white'}}})
            chart.set_y_axis({'name': str(y_axis[0]), 'min': 0.0, 'max': max(values_N1/1000),'major_gridlines': {'visible': True,'line':{'color': 'white'}}})
            chart.set_legend({'none': True})
    
            # Insert the chart into the worksheet.
            worksheet.insert_chart('P2', chart)
            chart = workbook.add_chart({'type': 'scatter'})
           
    workbook.close()
        
            
        

