#!/usr/bin/python
import sys, math
import binhex
import string
import os.path
from abaqus import *
from abaqusConstants import *
from visualization import *
from odbAccess import *
from abaqus import getInput

# get current directory for path names
current_directory=os.getcwd()
job_name=getInput('Enter the name of the job you are analyzing')
basename=job_name
# use j integral file to see if the job has been analyzed
j_filename=str(job_name)+'_j_integral.dat'
#if so
if os.path.exists(j_filename):
    yourAnswer=getWarningReply('This job has been analyzed!\n Delete results and continue with this name?', (YES,NO))
    if yourAnswer==YES:
        #delete associated j integral and path text files
        os.remove(j_filename)
        all_files=os.listdir(current_directory)
        for jobfile in all_files:
            if string.find(jobfile, str(job_name)+'_frame')!=-1 and string.find(jobfile, 'rpt')!=-1:
                os.remove(jobfile)
            elif string.find(jobfile, str(job_name)+'_MATLAB_PARAMS')!=-1:
                os.remove(jobfile)
    elif yourAnswer==NO:
        #or pick a different way to save the analysis
        basename=getInput('Pick a different name.')
        j_filename=str(basename)+'_j_integral.dat'

#open the database
working_odb=openOdb(path=str(job_name)+'.odb')

import __main__
import section
import regionToolset
import displayGroupMdbToolset as dgm
import part
import material
import assembly
import step
import interaction
import load
import mesh
import optimization
import job
import sketch
import visualization
import xyPlot
import displayGroupOdbToolset as dgo
import connectorBehavior

#Format output
session.xyReportOptions.setValues(numberFormat=AUTOMATIC)

##The following commented-out section was used to parse the input text file.
##The information isn't needed for an analysis, but the code will read the .inp file and find the part
##and model names. This could be useful if you wanted more detailed or different outputs.

##in_fname=str(job_name)+'.inp'
##inpt_file=open(in_fname,"r")
##all_lines=[]
##for line in inpt_file:
##    all_lines.append(line)
##
##msearch="Model name: "
##psearch="Part, name="
##modelname=[]
##j_integral_name=[]
##for textrow in all_lines:
##    if string.find(textrow, msearch)!=-1:
##        modelrow=textrow
##        sind=string.find(modelrow,msearch)
##        eind=string.find(modelrow,"\n")
##        modelrow=modelrow[sind:eind]
##        modelname=string.replace(modelrow,msearch,"")
##    if string.find(textrow, psearch)!=-1 and string.find(textrow,"specimen")!=-1:
##        pname=string.replace(textrow,"*Part, name=","")
##        pname=string.replace(textrow,"\n","")

all_steps=working_odb.steps.keys()
# assumes last step is the loading step
load_step=all_steps[-1]
loading=working_odb.steps[load_step]
# default set is all elements
histRegion=loading.historyRegions['ElementSet  ALL ELEMENTS']
# make a list of all possible history outputs
all_outputs=histRegion.historyOutputs.keys()

# IF USING A DIFFERENT # OF CONTOURS, CHANGE THIS PIECE
# You can also get different history outputs this way. Print all_outputs to see what you can choose from
for output in all_outputs:
    if string.find(output, 'Contour_30')!=-1 and string.find(output, 'J at')!=-1:
        j_int=output
    
j_data=histRegion.historyOutputs[j_int].data
# makes a .dat file for matlab to read
dispFile = open(j_filename,'w')
for time, j_val in j_data:
    dispFile.write('%8.3f   %10.4E\n' % (time, j_val))
dispFile.close()

## How many time points were used in abaqus
num_frames=len(j_data)



## Start about halfway through loading process 
st_frame=math.floor(num_frames/2)
## Get reasonable increments
frame_inc=3
## Initialize
dat_frames = [st_frame]
indx=st_frame

## This makes a list of frames to use. You can also just hard-code one, but you may have to remember to change it in some cases.
while indx<num_frames-frame_inc:
    indx=indx+frame_inc
    dat_frames.append(indx)

dat_frames.append(num_frames)
    

c_path=getInput('Enter Name of Defined Path.')

## gets S11 data along path
for timept in dat_frames:
    timept=int(timept)
    session.viewports['Viewport: 1'].odbDisplay.setFrame(step=1, frame=timept)
    pth = session.paths[c_path]
    session.XYDataFromPath(name=str(c_path)+'_'+str(timept), path=pth, includeIntersections=False, 
    pathStyle=PATH_POINTS, numIntervals=10, shape=UNDEFORMED, labelType=TRUE_DISTANCE, variable=('S',INTEGRATION_POINT,((COMPONENT,'S11'), ), ))
    x0 = session.xyDataObjects[str(c_path)+'_'+str(timept)]
    session.writeXYReport(fileName=str(basename)+'_frame'+str(timept)+'rpt.txt', xyData=(x0, ),appendMode=OFF)

##Information for Matlab to avoid user pain and suffering
matlab_file=open(str(basename)+'_MATLAB_PARAMS.txt','w')
##Tells matlab job name (more for the user) and which frames got written
matlab_file.write(job_name + '\n')
for timept in dat_frames:
    matlab_file.write(str(int(timept)) +',')
    matlab_file.write('0')
matlab_file.close()


