Create two pieces envelope

The following python script allows to create a two pieces envelope (the first for rise and the second for fall) stored in a text file. This file can be read inside Pure Data in order to create an envelope table.

To change the shape of the envelope there are some important parameters that have to be set:

  • TableSize defines the size of the envelope table you want to create
  • MaxPosition defines the position of the maximum (the maximun is reached when the the table index is equal to  1/MaxPosition)
  • ExpUp defines the exponent that will be used for the raise piece of the envelope
  • ExpDown defines the exponent that will be used for the fall piece of the envelope
  • out_file defines the name of the text file where the result will be written.
import matplotlib.pyplot as plt

TableSize=1024 #The size of the table 
MaxPosition=2 #The Maximun value(1) is reached at 1/2 of the table
UpNum=(TableSize/MaxPosition)-1.0
DownNum=TableSize-2.0-UpNum
ExpUp=2 #The Exponent for the raise
ExpDown=2 #The Exponent for the fall
Table0=range(0,1024)
Table1=[]
#Insert here the name of the file to store the table
out_file=open("Inviluppo-Max1_"+str(MaxPosition)+"-"+str(ExpUp)+"-"+str(ExpDown)+".txt","w")

#The table is created with the first two and the last two numbers equal to 0. 
#This is usefull to use 4 point interpolation to read the table
#For more information see the Pd object tabread4~
out_file.write("0\n")
out_file.write("0\n")
Table1.append(0)
Table1.append(0)

for i in range(1,TableSize-3):
    if i<=UpNum:
		value=pow(i/UpNum,ExpUp)
		out_file.write(str(value)+"\n")
		Table1.append(value)
	else:
		value=pow(1.0-(i-UpNum)/DownNum,ExpDown)
		out_file.write(str(value)+"\n")
		Table1.append(value)

out_file.write("0\n")
out_file.write("0\n")	
Table1.append(0)
Table1.append(0)	
out_file.close()

plt.plot(Table0,Table1)
plt.ylabel('Inviluppo')
plt.show()

Some envelopes generated with the code.

Inviluppi1_2-ENG

Contact me for help, comments and suggestions.