Skip to content

Instantly share code, notes, and snippets.

@carmichaelalonso
Created October 4, 2016 09:03
Show Gist options
  • Save carmichaelalonso/467823ed22acf075b9dcac6adc816681 to your computer and use it in GitHub Desktop.
Save carmichaelalonso/467823ed22acf075b9dcac6adc816681 to your computer and use it in GitHub Desktop.
Script that finds positive maxima values for data points representing a sine function.
"""
Script to find the maximum of each wave in a period for a given dataset
Cameron Carmichael Alonso, 2016
"""
import os
def calculateMaxPoints(file, fileName):
# we'll want to fill these variables later
lastAmplitude = 0.0
total = 0
greater = 0
maximums = []
fileContents = file.read().splitlines()
# Iterate
for lineX in range(0, len(fileContents)):
# Only lines greater than 1 (i.e. avoid headers)
# Lines less than total length of file - 1 (to avoid "next"-effect)
if lineX > 1 and lineX < (len(fileContents) - 1):
# Get line at index
line = fileContents[lineX]
# Split second tuple index
content = line.rstrip().split(",")
# Get values
time = content[0]
amplitude = content[1]
# Increment total
total += 1
# Check if greater than last amplitude
if amplitude > lastAmplitude:
# Get next line
lineNext = fileContents[lineX + 1]
# Split second tuple index
contentNext = lineNext.rstrip().split(",")
# Get values
amplitudeNext = contentNext[1]
# Check that value is greater than next
if amplitude > amplitudeNext:
# Finally, check this is positive
# We only want to analyse the y > 0 range
print amplitude
if float(amplitude) > 0:
print amplitude
# We have a maximum!
greater += 1
# Store in array
maximums.append([time, amplitude])
# Set last amplitude
lastAmplitude = amplitude
# print statistics
print "Total data points is " + str(total)
print "Total number of maximums is " + str(greater)
# write to .max.csv
strToWrite = ""
for maxima in maximums:
# Join into string
value = ",".join(maxima)
# Add newline
value += "\n"
# Append
strToWrite += value
# Construct new file name
newFileName = fileName.replace(".csv", ".max.csv")
# Delete file if it already existws
try:
os.remove(newFileName)
except OSError:
pass
# Write
with open (newFileName, 'a') as f: f.write (strToWrite)
# Show status
print "Written to file " + newFileName
# Main entry point
if __name__ == "__main__":
# Get name of file to read
fileName = raw_input("Relative file path: ")
# Try to open file
try:
with open(fileName, 'r') as file:
# Run method
calculateMaxPoints(file)
except Exception, e:
print str(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment