changeset 628:356d7b319ae8

tightened the inline docs in pyadbmodule.c a first pass at a query implementation in pyadb.py that allows for query parameters to be defined via a class attribute dict, configQuery and an accompanying dict specifying the expected keywords and types. Barely tested, be gentle.
author map01bf
date Wed, 23 Sep 2009 14:38:02 +0000
parents a6fc780678a8
children e2af7d01c7a8
files bindings/python/pyadb.py bindings/python/pyadbmodule.c
diffstat 2 files changed, 75 insertions(+), 12 deletions(-) [+]
line wrap: on
line diff
--- a/bindings/python/pyadb.py	Tue Sep 22 16:40:57 2009 +0000
+++ b/bindings/python/pyadb.py	Wed Sep 23 14:38:02 2009 +0000
@@ -5,6 +5,8 @@
 
 public access and class structure for python audioDb api bindings.
 
+
+
 Created by Benjamin Fields on 2009-09-22.
 Copyright (c) 2009 Goldsmith University of London.
 """
@@ -20,13 +22,22 @@
 ADB_HEADER_FLAG_REFERENCES = 0x40#api, so this is the only way to get them.
 
 class Usage(Exception):
+	"""error to indicate that a method has been called with incorrect args"""
+	def __init__(self, msg):
+		self.msg = msg
+class ConfigWarning(Warning):
 	def __init__(self, msg):
 		self.msg = msg
 
-class Pyadb:
-	
+class Pyadb(object):
+	"""Pyadb class.  Allows for creation, access, insertion and query of an audioDB vector matching database."""
+	validConfigTerms = {"seqLength":int, "seqStart":int, "exhaustive":bool, 
+		"falsePositives":bool, "accumulation":str, "distance":str, "npoints":int,
+		"ntracks":int, "includeKeys":list, "excludeKeys":list, "radius":float, "absThres":float,
+		"relThres":float, "durRatio":float, "hopSize":int, "resFmt":str}
 	def __init__(self, path, mode='w'):
 		self.path = path
+		self.configQuery = {}
 		if not (mode=='w' or mode =='r'):
 			raise(ValueError, "if specified, mode must be either\'r\' or \'w\'.")
 		if os.path.exists(path):
@@ -38,7 +49,7 @@
 	
 	def insert(self, featFile=None, powerFile=None, timesFile=None, featData=None, powerData=None, timesData=None, key=None):
 		"""Insert features into database.  Can be done with data provided directly or by giving a path to a binary fftExtract style feature file.  If power and/or timing is engaged in the database header, it must be provided (via the same means as the feature) or a Usage exception will be raised. Power files should be of the same binary type as features.  Times files should be the ascii number length of time in seconds from the begining of the file to segment start, one per line.\n---Note that direct data insertion is not yet implemented.---"""
-		#While python normally advocates leaping before looking, these check are nessecary as 
+		#While python style normally advocates leaping before looking, these check are nessecary as 
 		#it is very difficult to assertain why the insertion failed once it has been called.
 		if (self.hasPower and (((featFile) and powerFile==None) or ((featData) and powerData==None))):
 			raise(Usage, "The db you are attempting an insert on (%s) expects power and you either\
@@ -73,7 +84,53 @@
 				return
 		elif featData:
 			raise(NotImplementedError, "direct data insertion not yet implemented")
-			
+	
+	def configCheck(self, scrub=False):
+		"""examine self.configQuery dict.  For each key encouters confirm it is in the validConfigTerms list and if appropriate, type check.  If scrub is False, leave unexpected keys and values alone and return False, if scrub  try to correct errors (attempt type casts and remove unexpected entries) and continue.  If self.configQuery only contains expected keys with correctly typed values, return True.  See Pyadb.validConfigTerms for allowed keys and types.  Note also that include/exclude key lists memebers or string switched are not verified here, but rather when they are converted to const char * in the C api call and if malformed, an error will be rasied from there.  Valid keys and values in  queryconfig:
+		{seqLength    : Int Sequence Length, \n\
+		seqStart      : Int offset from start for key, \n\
+		exhaustive    : boolean - True for exhaustive (false by default),\n\
+		falsePositives: boolean - True to keep fps (false by defaults),\n\
+		accumulation  : [\"db\"|\"track\"|\"one2one\"] (\"db\" by default),\n\
+		distance      : [\"dot\"|\"eucNorm\"|\"euclidean\"] (\"dot\" by default),\n\
+		npoints       : int number of points per track,\n\
+		ntracks       : max number of results returned in db accu mode,\n\
+		includeKeys   : list of strings to include (use all by default),\n\
+		excludeKeys   : list of strings to exclude (none by default),\n\
+		radius        : double of nnRadius (1.0 default, overrides npoints if specified),\n\
+		absThres      : double absolute power threshold (db must have power),\n\
+		relThres      : double relative power threshold (db must have power),\n\
+		durRatio      : double time expansion/compresion ratio,\n\
+		hopSize       : int hopsize (1 by default)])->resultDict\n\
+		resFmt        : [\"list\"|\"dict\"](\"dict\" by default)}"""
+		for key in self.queryConfig.keys():
+			if key not in Pyadb.validConfigTerms.keys():
+				if not scrub:return False
+				del self.queryConfig[key]
+			if not isinstance(Pyadb.validConfigTerms[key], self.queryConfig[key]):
+				if not scrub:return False
+				self.queryConfig[key] = Pyadb.validConfigTerms[key](self.queryConfig[key])#hrm, syntax?
+		
+				
+				# 
+	
+	def query(self, key=None, featData=None, strictConfig=False):
+		"""query the database.  Query parameters as defined in self.configQuery. For details on this consult the doc string in the configCheck method."""
+		if not self.configCheck():
+			if strictConfig:
+				raise ValueError("configQuery dict contains unsupported terms and strict configure mode is on.\n\
+Only keys found in Pyadb.validConfigTerms may be defined")
+			else:
+				raise ConfigWarning("configQuery dict contains unsupported terms and strict configure mode is off.\n\
+Only keys found in Pyadb.validConfigTerms should be defined.  Removing invalid terms and proceeding...")
+				self.configCheck(scrub=True)
+		if ((not key and not featData) or (key and featData)):
+			raise Usage("query require either key or featData to be defined, you have defined both or neither.")
+		if key:
+			result = _pyadb._pyadb_queryFromKey(self._db, key, **self.configQuery)
+		elif featData:
+			raise NotImplementedError("direct data query not yet implemented.  Sorry.")
+		return Result(result, self.queryConfig)
 	
 	###internal methods###
 	def _updateDBAttributes(self):
@@ -92,12 +149,17 @@
 		self.usesRefs = bool(rawFlags & ADB_HEADER_FLAG_REFERENCES)
 		return
 		
-	
-		
-		
-	class Result:
-		def __init__(self):
-			pass
+	class Result(object):
+		def __init__(self, rawData, currentConfig):
+			self.rawData = rawData
+			if "resFmt" in currentConfig:
+				self.type = currentConfig["resFmt"]
+			else:
+				self.type = "dict"
+		def __str__(self):
+			str(self.rawData)
+		def __repr__(self):
+			repr(self.rawData)
 
 class untitledTests(unittest.TestCase):
 	def setUp(self):
--- a/bindings/python/pyadbmodule.c	Tue Sep 22 16:40:57 2009 +0000
+++ b/bindings/python/pyadbmodule.c	Wed Sep 23 14:38:02 2009 +0000
@@ -407,7 +407,7 @@
 			"Poorly specified result mode. Result must be either \'dist\' or \'list\'.\n");
 		return NULL;
 	}
-	if (!audiodb_query_free_results(current_db, spec, result)){
+	if (audiodb_query_free_results(current_db, spec, result)){
 		printf("bit of trouble freeing the result and spec...\ncheck for leaks.");
 	}
 	
@@ -471,7 +471,8 @@
 					absThres      = double absolute power threshold (db must have power),\n\
 					relThres      = double relative power threshold (db must have power),\n\
 					durRatio      = double time expansion/compresion ratio,\n\
-					hopSize       = int hopsize (1 by default)])->resultDict\n"},
+					hopSize       = int hopsize (1 by default)])->resultDict\n\
+					resFmt        = [\"list\"|\"dict\"](\"dict\" by default)"},
 	{NULL,NULL, 0, NULL}
 };