# WeightsDOEcaseReader.py - from http://openmdao.org/twodocs/versions/latest/basic_guide/basic_recording.html
# Reads cases.sql files generated by an OpenMDAO case recorder in WeightsDOEtest.py

import openmdao.api as om
import csv
import matplotlib.pyplot as plt

# open database of previously saved cases
cr = om.CaseReader("WeightsDOEcases.sql")

# get a list of cases that were recorded by the driver
cases = cr.list_cases('driver')

# report number of cases
print(len(cases))

# setup write to CSV with outputs
with open('WeightsDOE.csv', mode='w') as csv_file:
    #set up CSV file to use DictWriter
    fieldnames = ['Cb','L','B','T','GMT','Wt','Disp','Excess']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()

    # set up lists for data
    values = []
    L = []
    Wt = []
    Disp = []
    Excess = []
    for case in cases:
        #read outputs from data file
        outputs = cr.get_case(case).outputs
        #create list with values of interest for printing
        values.append((outputs['indeps.Cb'], outputs['indeps.L'], outputs['indeps.B'], outputs['indeps.T'], outputs['stab.GMT'], outputs['wts.Wt'], outputs['const.Disp']))
        #write data in a csv (human readable)
        writer.writerow({'Cb': outputs['indeps.Cb'],'L': outputs['indeps.L'],'B': outputs['indeps.B'],'T': outputs['indeps.T'],'GMT': outputs['stab.GMT'],'Wt': outputs['wts.Wt'],'Disp': outputs['const.Disp'],'Excess': (outputs['const.Disp']-outputs['wts.Wt'])})

        #read into lists
        L.append(outputs['indeps.L'])
        Wt.append(outputs['wts.Wt'])
        Disp.append(outputs['const.Disp'])
        #this is the "excess" displacement of the design
        Excess.append(outputs['const.Disp']-outputs['wts.Wt'])

    # print results
    print("\n".join(["Cb: %5.2f, L: %5.2f, B: %5.2f, T: %5.2f, GMT: %5.2f, Wt: %6.2f, Disp: %6.2f" % xyf for xyf in values]))


#---- SOME PLOTTING TESTS
# plot weight and displacement
plt.plot(Wt, Disp, color='blue', marker='o', linewidth=0, markersize=2, label='Designs')
plt.plot(Wt, Wt, label='Equal', color='red', linewidth=2)

# Create legend, labels
plt.legend(loc='upper left')
plt.xlim(100, 600)
plt.ylim(100, 600)
plt.xlabel('Weight [MT]')
plt.ylabel('Displacement [MT]')

# Save and close figure
plt.savefig('Wt_Disp.png')
plt.clf()

# plot length and "excess" displacement
plt.plot(L, Excess, color='blue', marker='o', linewidth=0, markersize=2, label='Designs')
plt.axhline(y=0, color='red', linewidth=2)
plt.axhline(y=-50, color='red', linewidth=1, linestyle='dashed')
plt.axhline(y=50, color='red', linewidth=1, linestyle='dashed')


# Create legend, labels
plt.legend(loc='upper left')
plt.xlim(20, 55)
plt.ylim(-100, 300)
plt.xlabel('Length [m]')
plt.ylabel('Excess Displacement [MT]')

# Save and close figure
plt.savefig('L_Excess.png')
plt.clf()
