# vim: set fileencoding=utf-8 :
from math import log,fabs,pi,floor,ceil
def parse_index():
  index = []
  section = {}
  f = open('index.txt')
  for line in f:
    
    if line[0] == '[':
      if section.has_key('Messung'):
        index.append(section)
      section = {}
    
    if ':' in line:
      key, value = line.split(':', 1)
      section[key.strip()] = value.strip()
    
  if section.has_key('Messung'):
    index.append(section)
  return index
def find_extrema(measurement):
  extrema    = []
  zero = 0
  phase = 0
  phasecount = 0
  if float(measurement['Anregungsfrequenz']) > 0:
    timescale = 1000/float(measurement['Anregungsfrequenz'])
  else:
    timescale = 1
  datapoints = [(0,0,0),(0,0,0),(0,0,0),(0,0,0)]
  f = open(measurement['Dateiname'])
  for line in f:
    line.strip()
    time, amplitude, velocity = map(float, line.split(' '))
    amplitude = amplitude + 7 
    datapoints.append((time, amplitude, velocity))
    l = len(datapoints)
    # Simple approach to find extrema, works like a charm
    if datapoints[l-5][1] < datapoints[l-3][1] and datapoints[l-4][1] < datapoints[l-3][1] and datapoints[l-2][1] < datapoints[l-3][1] and datapoints[l-1][1] < datapoints[l-3][1]:
      extrema.append(datapoints[l-3])

    if datapoints[l-5][1] > datapoints[l-3][1] and datapoints[l-4][1] > datapoints[l-3][1] and datapoints[l-2][1] > datapoints[l-3][1] and datapoints[l-1][1] > datapoints[l-3][1]:
      extrema.append(datapoints[l-3])
    if  (fabs(amplitude) < 0.5) and datapoints[l-2][1] > 0.0:
      if int(measurement['Anregungsfrequenz']) > 0:
        difference = zero - float(measurement['Nullpunkt Erreger [ms]'])
        _phase = 360.0*(difference % timescale)/timescale
        
        # Crap values in the first seconds.
        if time < 10000.0:
          # Use adaptive Timescale, the Frequency given by the Computer is completely inaccurate
          timescale = (zero - time)
          zero = time
          continue
        timescale = (zero - time)
        # Average over the phase angles
        phase = phase * float(phasecount)/float(phasecount + 1)
        phasecount = phasecount + 1
        phase = phase + _phase/float(phasecount)
        zero = time
      else:
        timescale = (zero - time)
        zero = time
  return extrema, (180 - phase)

def main():
  index = parse_index()
  f  = open('auswertung.txt', 'w')
  f2 = open('auswertung2.txt', 'w')
  f3 = open('auswertung3.txt', 'w')
  f4 = open('auswertung4.txt', 'w')
  f5 = open('auswertung5.txt', 'w')
  amplitudes = {}
  phases = {}
  for measurement in index:
    for key in measurement.iterkeys():
      f.write('# ' + key + ' ' + measurement[key] + '\n')
      f2.write('# ' + key + ' ' + measurement[key] + '\n')
      f3.write('# ' + key + ' ' + measurement[key] + '\n')
    
    f.write('# Amplituden\n')
    f2.write('# Zeitpunkte der Extrema\n')
    f3.write('# Logarithmisches Dekrement\n')
    extrema,phase = find_extrema(measurement)
    i = 0
    last_max = 0
    last_min = 0
    list_extrema = []
    for extremum in extrema:
      f.write(str(extremum[0]) + ' ' + str(extremum[1]) + '\n')
      f2.write(str(i)+ ' ' + str(extremum[0]) + '\n')
      list_extrema.append(extremum[1])
      if extremum[1] > 7.01:
        if last_max != 0:
          f3.write(str(i)+ ' ' + str(log(last_max / fabs(extremum[1]))) + '\n')
        last_max = fabs(extremum[1])
      if extremum[1] < -7.01:
        if last_min != 0:
          f3.write(str(i)+ ' ' + str(log(last_min / fabs(extremum[1]))) + '\n')
        last_min = fabs(extremum[1])
      i = i + 1
    f.write('\n\n')
    f2.write('\n\n')
    f3.write('\n\n')
    list_extrema.sort()
    if int(measurement['Anregungsfrequenz']) > 0:
      if measurement['Dämpfung'] not in amplitudes:
        amplitudes[measurement['Dämpfung']] = '# Amplituden für Dämpfung ' + measurement['Dämpfung'] + '\n'
      amplitudes[measurement['Dämpfung']] = amplitudes[measurement['Dämpfung']] + measurement['Anregungsfrequenz'] + ' ' + str((list_extrema[-1] - list_extrema[0])/2.0) + '\n'
  
      if measurement['Dämpfung'] not in phases:
        phases[measurement['Dämpfung']] = '# Phasenverschiebung für Dämpfung ' + measurement['Dämpfung'] + '\n'
      phases[measurement['Dämpfung']] = phases[measurement['Dämpfung']] + measurement['Anregungsfrequenz'] + ' ' + str(phase) + '\n'
  for daempf in amplitudes.iterkeys():
    f4.write(amplitudes[daempf])
    f4.write('\n\n')
  for daempf in phases.iterkeys():
    f5.write(phases[daempf])
    f5.write('\n\n')

if __name__ == '__main__': 
  main() 
