Python Parameter-Tupel-Class

This simple piece of software is able to generate and iterate over a set of parameter-tuples. You specify the lower and upper bounces, the step width and the type (linear or logarithmic) for each parameter, then this class generate all combinations of parameters and saves it in tuples. You can consume each tuple with a simple while-loop.

Here is a simple example:

You need two parameter. The first is a binary one with {0,1} and the second is out of {-1, 0, 1}. The class would generate you 6 two-tuples with:
(0.0, -1.0), (0.0, 0.0), (0.0, 1.0),
(1.0, -1.0), (1.0, 0.0), (1.0, 1.0)
ParamTuple
ParamTuple
ParamTuple.txt
1.9 KiB
199 Downloads
Details
'''
Created on 06.06.2013

@author: ize
'''

import numpy as np

class ParamTuple:

	lastTuple = ()
	tupl = ()
	actualTuplePointer = 0

	def next(self):
		self.lastTuple = self.tupl
		self.tupl = self.tuplesArray[self.actualTuplePointer]
		if len(self.tupl)!=0:
			self.actualTuplePointer+=1
			return self.tupl
		else:
			return ()

	def hasMoreTuples(self):
		return self.actualTuplePointer<len(self.tuplesArray)

	def size(self):
		return len(self.tuplesArray)

	def getLastTuple(self):
		return self.lastTuple

	def __init__(self, *tuples):
		spacesArray = []

		for tup in tuples:
			if type(tup) != tuple:
				raise BaseException("Parameters are not only tuples")
			if len(tup) != 4:
				raise BaseException("All tuples must have length 4")
			if type(tup[0]) != str or (tup[0] != 'log' and tup[0]!='lin'):
				raise BaseException("First tuple-entry is not a string of log or lin")
			if type(tup[1]) != float or type(tup[2]) != float or type(tup[2]) != float:
				raise BaseException("Last three tuple-enties are not float-numbers")

			# ok this tuple is valid:
			if tup[0] == 'log':
				tmpSpace = np.logspace(tup[1], tup[2],tup[3])
			else:
				 tmpSpace = np.linspace(tup[1],tup[2],tup[3])
			spacesArray.append(tmpSpace)

		#generate code and execute it: 
		execstr = "tuplesArray = []\n"
		for i in range(0,len(spacesArray)):
			execstr += "for var" + str(i) + " in spacesArray["+str(i)+"]:\n\t"
			execstr += ("\t"*i)

		#tabs = "\t"*(len(spacesArray)-1)
		#execstr += tabs
		execstr += "tuplesArray.append(("
		for i in range(0,len(spacesArray)):
			execstr += "var"+str(i)+","	 # this last , is a "must have" ^^ for tuples with only one entry 
		execstr+= "))"

		#print execstr
		exec(execstr)
		self.tuplesArray = tuplesArray

if __name__ == '__main__':
	print 'ParamTuple.py:'
	g = ParamTuple(('log',-3.0,0.0,4.0), ('log',-2.0,2.0,5.0))
	print g.size()
	while(g.hasMoreTuples()):
		print g.next()
ParamTuple
ParamTuple
ParamTuple.txt
1.9 KiB
199 Downloads
Details

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.