source: python/lib/gen_code.py @ f633b90

feature/constantq
Last change on this file since f633b90 was f633b90, checked in by Paul Brossier <piem@piem.org>, 6 years ago

python/lib/gen_code.py: add default for constantq

  • Property mode set to 100644
File size: 17.3 KB
RevLine 
[ccb9fb5]1aubiodefvalue = {
2    # we have some clean up to do
3    'buf_size': 'Py_default_vector_length',
4    'win_s': 'Py_default_vector_length',
[f633b90]5    'size': 'Py_default_vector_length',
[ccb9fb5]6    # and here too
7    'hop_size': 'Py_default_vector_length / 2',
8    'hop_s': 'Py_default_vector_length / 2',
9    # these should be alright
10    'samplerate': 'Py_aubio_default_samplerate',
11    # now for the non obvious ones
12    'n_filters': '40',
13    'n_coeffs': '13',
14    'nelems': '10',
15    'flow': '0.',
16    'fhig': '1.',
17    'ilow': '0.',
18    'ihig': '1.',
19    'thrs': '0.5',
20    'ratio': '0.5',
21    'method': '"default"',
22    'uri': '"none"',
[f633b90]23    'bins_per_octave': 24,
[ccb9fb5]24    }
25
26member_types = {
27        'name': 'type',
28        'char_t*': 'T_STRING',
29        'uint_t': 'T_INT',
[c6388f4]30        'smpl_t': 'AUBIO_NPY_SMPL',
[ccb9fb5]31        }
32
33pyfromtype_fn = {
34        'smpl_t': 'PyFloat_FromDouble',
35        'uint_t': 'PyLong_FromLong', # was: 'PyInt_FromLong',
36        'fvec_t*': 'PyAubio_CFvecToArray',
37        'fmat_t*': 'PyAubio_CFmatToArray',
38        }
39
40pytoaubio_fn = {
41        'fvec_t*': 'PyAubio_ArrayToCFvec',
[92a8800]42        'cvec_t*': 'PyAubio_PyCvecToCCvec',
[a7f398d]43        #'fmat_t*': 'PyAubio_ArrayToCFmat',
[ccb9fb5]44        }
45
46newfromtype_fn = {
[21e8408]47        'fvec_t*': 'new_py_fvec',
48        'fmat_t*': 'new_py_fmat',
49        'cvec_t*': 'new_py_cvec',
[ccb9fb5]50        }
51
52delfromtype_fn = {
[21e8408]53        'fvec_t*': 'Py_DECREF',
54        'fmat_t*': 'Py_DECREF',
55        'cvec_t*': 'Py_DECREF',
[ccb9fb5]56        }
57
58param_init = {
59        'char_t*': 'NULL',
60        'uint_t': '0',
61        'sint_t': 0,
62        'smpl_t': 0.,
63        'lsmp_t': 0.,
64        }
65
66pyargparse_chars = {
[fbcee4f]67        'smpl_t': 'f', # if not usedouble else 'd',
[ccb9fb5]68        'uint_t': 'I',
69        'sint_t': 'I',
70        'char_t*': 's',
71        'fmat_t*': 'O',
72        'fvec_t*': 'O',
[a7f398d]73        'cvec_t*': 'O',
[ccb9fb5]74        }
75
76objoutsize = {
77        'onset': '1',
78        'pitch': '1',
[8470144]79        'notes': '3',
[ccb9fb5]80        'wavetable': 'self->hop_size',
81        'sampler': 'self->hop_size',
82        'mfcc': 'self->n_coeffs',
83        'specdesc': '1',
[de63017]84        'tempo': '1',
[ccb9fb5]85        'filterbank': 'self->n_filters',
[73e068d]86        'tss': 'self->buf_size',
[f633b90]87        'constantq': 'aubio_constantq_get_numbins (self->o)',
[ccb9fb5]88        }
89
[bf54364]90objinputsize = {
91        'mfcc': 'self->buf_size / 2 + 1',
92        'notes': 'self->hop_size',
93        'onset': 'self->hop_size',
94        'pitch': 'self->hop_size',
95        'sampler': 'self->hop_size',
96        'specdesc': 'self->buf_size / 2 + 1',
97        'tempo': 'self->hop_size',
98        'wavetable': 'self->hop_size',
[73e068d]99        'tss': 'self->buf_size / 2 + 1',
[bf54364]100        }
101
[ccb9fb5]102def get_name(proto):
103    name = proto.replace(' *', '* ').split()[1].split('(')[0]
104    name = name.replace('*','')
105    if name == '': raise ValueError(proto + "gave empty name")
106    return name
107
108def get_return_type(proto):
109    import re
110    paramregex = re.compile('(\w+ ?\*?).*')
111    outputs = paramregex.findall(proto)
112    assert len(outputs) == 1
113    return outputs[0].replace(' ', '')
114
115def split_type(arg):
116    """ arg = 'foo *name'
117        return ['foo*', 'name'] """
118    l = arg.split()
[a7f398d]119    type_arg = {} #'type': l[0], 'name': l[1]}
120    type_arg['type'] = " ".join(l[:-1])
121    type_arg['name'] = l[-1]
122    # fix up type / name
123    if type_arg['name'].startswith('*'):
124        # ['foo', '*name'] -> ['foo*', 'name']
125        type_arg['type'] += '*'
126        type_arg['name'] = type_arg['name'][1:]
127    if type_arg['type'].endswith(' *'):
128        # ['foo *', 'name'] -> ['foo*', 'name']
129        type_arg['type'] = type_arg['type'].replace(' *','*')
130    if type_arg['type'].startswith('const '):
131        # ['foo *', 'name'] -> ['foo*', 'name']
132        type_arg['type'] = type_arg['type'].replace('const ','')
[ccb9fb5]133    return type_arg
134
135def get_params(proto):
136    """ get the list of parameters from a function prototype
137    example: proto = "int main (int argc, char ** argv)"
138    returns: ['int argc', 'char ** argv']
139    """
140    import re
[a7f398d]141    paramregex = re.compile('.*\((.*)\);')
142    a = paramregex.findall(proto)[0].split(', ')
143    #a = [i.replace('const ', '') for i in a]
144    return a
145
146def get_input_params(proto):
147    a = get_params(proto)
148    return [i.replace('const ', '') for i in a if (i.startswith('const ') or i.startswith('uint_t ') or i.startswith('smpl_t '))]
149
150def get_output_params(proto):
151    a = get_params(proto)
152    return [i for i in a if not i.startswith('const ')][1:]
[ccb9fb5]153
154def get_params_types_names(proto):
155    """ get the list of parameters from a function prototype
156    example: proto = "int main (int argc, char ** argv)"
157    returns: [['int', 'argc'], ['char **','argv']]
158    """
[a7f398d]159    a = list(map(split_type, get_params(proto)))
160    #print proto, a
161    #import sys; sys.exit(1)
162    return a
[ccb9fb5]163
164class MappedObject(object):
165
[fbcee4f]166    def __init__(self, prototypes, usedouble = False):
167        if usedouble:
168            pyargparse_chars['smpl_t'] = 'd'
[ccb9fb5]169        self.prototypes = prototypes
170
171        self.shortname = prototypes['shortname']
172        self.longname = prototypes['longname']
173        self.new_proto = prototypes['new'][0]
174        self.del_proto = prototypes['del'][0]
175        self.do_proto = prototypes['do'][0]
176        self.input_params = get_params_types_names(self.new_proto)
[a7f398d]177        self.input_params_list = "; ".join(get_input_params(self.new_proto))
[ccb9fb5]178        self.outputs = get_params_types_names(self.do_proto)[2:]
[a7f398d]179        self.do_inputs = [get_params_types_names(self.do_proto)[1]]
180        self.do_outputs = get_params_types_names(self.do_proto)[2:]
[21e8408]181        struct_output_str = ["PyObject *{0[name]}; {1} c_{0[name]}".format(i, i['type'][:-1]) for i in self.do_outputs]
182        self.struct_outputs = ";\n    ".join(struct_output_str)
[a7f398d]183
[950a80c]184        #print ("input_params: ", map(split_type, get_input_params(self.do_proto)))
185        #print ("output_params", map(split_type, get_output_params(self.do_proto)))
[ccb9fb5]186
187    def gen_code(self):
188        out = ""
[ce79a9e]189        try:
190            out += self.gen_struct()
191            out += self.gen_doc()
192            out += self.gen_new()
193            out += self.gen_init()
194            out += self.gen_del()
195            out += self.gen_do()
196            out += self.gen_memberdef()
197            out += self.gen_set()
198            out += self.gen_get()
199            out += self.gen_methodef()
200            out += self.gen_typeobject()
201        except Exception as e:
202            print ("Failed generating code for", self.shortname)
203            raise
[ccb9fb5]204        return out
205
206    def gen_struct(self):
207        out = """
208// {shortname} structure
209typedef struct{{
210    PyObject_HEAD
211    // pointer to aubio object
212    {longname} *o;
213    // input parameters
214    {input_params_list};
[a7f398d]215    // do input vectors
216    {do_inputs_list};
[ccb9fb5]217    // output results
[21e8408]218    {struct_outputs};
[ccb9fb5]219}} Py_{shortname};
220"""
[569b363]221        # fmat_t* / fvec_t* / cvec_t* inputs -> full fvec_t /.. struct in Py_{shortname}
222        do_inputs_list = "; ".join(get_input_params(self.do_proto)).replace('fvec_t *','fvec_t').replace('fmat_t *', 'fmat_t').replace('cvec_t *', 'cvec_t')
223        return out.format(do_inputs_list = do_inputs_list, **self.__dict__)
[ccb9fb5]224
225    def gen_doc(self):
226        out = """
227// TODO: add documentation
228static char Py_{shortname}_doc[] = \"undefined\";
[a7f398d]229"""
[ccb9fb5]230        return out.format(**self.__dict__)
231
232    def gen_new(self):
233        out = """
234// new {shortname}
235static PyObject *
236Py_{shortname}_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
237{{
238    Py_{shortname} *self;
239""".format(**self.__dict__)
240        params = self.input_params
241        for p in params:
242            out += """
243    {type} {name} = {defval};""".format(defval = param_init[p['type']], **p)
244        plist = ", ".join(["\"%s\"" % p['name'] for p in params])
245        out += """
246    static char *kwlist[] = {{ {plist}, NULL }};""".format(plist = plist)
247        argchars = "".join([pyargparse_chars[p['type']] for p in params])
248        arglist = ", ".join(["&%s" % p['name'] for p in params])
249        out += """
250    if (!PyArg_ParseTupleAndKeywords (args, kwds, "|{argchars}", kwlist,
251              {arglist})) {{
252        return NULL;
253    }}
254""".format(argchars = argchars, arglist = arglist)
255        out += """
256    self = (Py_{shortname} *) pytype->tp_alloc (pytype, 0);
257    if (self == NULL) {{
258        return NULL;
259    }}
260""".format(**self.__dict__)
261        params = self.input_params
262        for p in params:
[a7f398d]263            out += self.check_valid(p)
[ccb9fb5]264        out += """
265    return (PyObject *)self;
266}
267"""
268        return out
269
270    def check_valid(self, p):
271        if p['type'] == 'uint_t':
272            return self.check_valid_uint(p)
273        if p['type'] == 'char_t*':
274            return self.check_valid_char(p)
275        else:
276            print ("ERROR, no idea how to check %s for validity" % p['type'])
277
278    def check_valid_uint(self, p):
279        name = p['name']
280        return """
281    self->{name} = {defval};
282    if ((sint_t){name} > 0) {{
283        self->{name} = {name};
284    }} else if ((sint_t){name} < 0) {{
285        PyErr_SetString (PyExc_ValueError, "can not use negative value for {name}");
286        return NULL;
287    }}
288""".format(defval = aubiodefvalue[name], name = name)
289
290    def check_valid_char(self, p):
291        name = p['name']
292        return """
293    self->{name} = {defval};
294    if ({name} != NULL) {{
295        self->{name} = {name};
296    }}
297""".format(defval = aubiodefvalue[name], name = name)
298
299    def gen_init(self):
300        out = """
301// init {shortname}
302static int
303Py_{shortname}_init (Py_{shortname} * self, PyObject * args, PyObject * kwds)
304{{
305""".format(**self.__dict__)
306        new_name = get_name(self.new_proto)
307        new_params = ", ".join(["self->%s" % s['name'] for s in self.input_params])
308        out += """
309  self->o = {new_name}({new_params});
310""".format(new_name = new_name, new_params = new_params)
311        paramchars = "%s"
312        paramvals = "self->method"
313        out += """
314  // return -1 and set error string on failure
315  if (self->o == NULL) {{
[6a72ff0]316    PyErr_Format (PyExc_RuntimeError, "failed creating {shortname}");
[ccb9fb5]317    return -1;
318  }}
319""".format(paramchars = paramchars, paramvals = paramvals, **self.__dict__)
320        output_create = ""
321        for o in self.outputs:
322            output_create += """
323  self->{name} = {create_fn}({output_size});""".format(name = o['name'], create_fn = newfromtype_fn[o['type']], output_size = objoutsize[self.shortname])
324        out += """
325  // TODO get internal params after actual object creation?
326"""
327        out += """
328  // create outputs{output_create}
329""".format(output_create = output_create)
330        out += """
331  return 0;
332}
333"""
334        return out
335
336    def gen_memberdef(self):
337        out = """
338static PyMemberDef Py_{shortname}_members[] = {{
339""".format(**self.__dict__)
340        for p in get_params_types_names(self.new_proto):
341            tmp = "  {{\"{name}\", {ttype}, offsetof (Py_{shortname}, {name}), READONLY, \"TODO documentation\"}},\n"
342            pytype = member_types[p['type']]
343            out += tmp.format(name = p['name'], ttype = pytype, shortname = self.shortname)
344        out += """  {NULL}, // sentinel
345};
346"""
347        return out
348
349    def gen_del(self):
350        out = """
351// del {shortname}
352static void
353Py_{shortname}_del  (Py_{shortname} * self, PyObject * unused)
354{{""".format(**self.__dict__)
[a7f398d]355        for input_param in self.do_inputs:
[569b363]356            if input_param['type'] == 'fmat_t *':
357                out += """
[6a72ff0]358  free(self->{0[name]}.data);""".format(input_param)
[ccb9fb5]359        for o in self.outputs:
360            name = o['name']
361            del_out = delfromtype_fn[o['type']]
362            out += """
[6a72ff0]363  if (self->{name}) {{
364    {del_out}(self->{name});
365  }}""".format(del_out = del_out, name = name)
[ccb9fb5]366        del_fn = get_name(self.del_proto)
367        out += """
[6a72ff0]368  if (self->o) {{
369    {del_fn}(self->o);
370  }}
371  Py_TYPE(self)->tp_free((PyObject *) self);
[ccb9fb5]372}}
373""".format(del_fn = del_fn)
374        return out
375
376    def gen_do(self):
377        out = """
378// do {shortname}
379static PyObject*
380Py_{shortname}_do  (Py_{shortname} * self, PyObject * args)
[a7f398d]381{{""".format(**self.__dict__)
382        input_params = self.do_inputs
383        output_params = self.do_outputs
384        #print input_params
385        #print output_params
[73e068d]386        out += """
387    PyObject *outputs;"""
[a7f398d]388        for input_param in input_params:
389            out += """
[bbc62b5]390    PyObject *py_{0};""".format(input_param['name'])
[a7f398d]391        refs = ", ".join(["&py_%s" % p['name'] for p in input_params])
392        pyparamtypes = "".join([pyargparse_chars[p['type']] for p in input_params])
393        out += """
394    if (!PyArg_ParseTuple (args, "{pyparamtypes}", {refs})) {{
[ccb9fb5]395        return NULL;
[a7f398d]396    }}""".format(refs = refs, pyparamtypes = pyparamtypes, **self.__dict__)
[21e8408]397        for input_param in input_params:
[a7f398d]398            out += """
[21e8408]399
[569b363]400    if (!{pytoaubio}(py_{0[name]}, &(self->{0[name]}))) {{
[ccb9fb5]401        return NULL;
[a7f398d]402    }}""".format(input_param, pytoaubio = pytoaubio_fn[input_param['type']])
[bf54364]403        if self.shortname in objinputsize:
404            out += """
405
406    if (self->{0[name]}.length != {expected_size}) {{
407        PyErr_Format (PyExc_ValueError,
408            "input size of {shortname} should be %d, not %d",
409            {expected_size}, self->{0[name]}.length);
410        return NULL;
411    }}""".format(input_param, expected_size = objinputsize[self.shortname], **self.__dict__)
412        else:
413            out += """
[21e8408]414
415    // TODO: check input sizes"""
416        for output_param in output_params:
417            out += """
418
419    Py_INCREF(self->{0[name]});
420    if (!{pytoaubio}(self->{0[name]}, &(self->c_{0[name]}))) {{
421        return NULL;
422    }}""".format(output_param, pytoaubio = pytoaubio_fn[output_param['type']])
[a7f398d]423        do_fn = get_name(self.do_proto)
[569b363]424        inputs = ", ".join(['&(self->'+p['name']+')' for p in input_params])
[21e8408]425        c_outputs = ", ".join(["&(self->c_%s)" % p['name'] for p in self.do_outputs])
[a7f398d]426        outputs = ", ".join(["self->%s" % p['name'] for p in self.do_outputs])
427        out += """
[ccb9fb5]428
[21e8408]429    {do_fn}(self->o, {inputs}, {c_outputs});
[73e068d]430""".format(
431        do_fn = do_fn,
432        inputs = inputs, c_outputs = c_outputs,
433        )
434        if len(self.do_outputs) > 1:
435            out += """
[31c6010]436    outputs = PyTuple_New({:d});""".format(len(self.do_outputs))
[73e068d]437            for i, p in enumerate(self.do_outputs):
438                out += """
439    PyTuple_SetItem( outputs, {i}, self->{p[name]});""".format(i = i, p = p)
440        else:
441            out += """
442    outputs = self->{p[name]};""".format(p = self.do_outputs[0])
443        out += """
[ccb9fb5]444
[73e068d]445    return outputs;
[ccb9fb5]446}}
[a7f398d]447""".format(
[73e068d]448        outputs = outputs,
[a7f398d]449        )
450        return out
[ccb9fb5]451
452    def gen_set(self):
453        out = """
454// {shortname} setters
455""".format(**self.__dict__)
456        for set_param in self.prototypes['set']:
457            params = get_params_types_names(set_param)[1]
458            paramtype = params['type']
459            method_name = get_name(set_param)
460            param = method_name.split('aubio_'+self.shortname+'_set_')[-1]
461            pyparamtype = pyargparse_chars[paramtype]
462            out += """
463static PyObject *
464Pyaubio_{shortname}_set_{param} (Py_{shortname} *self, PyObject *args)
465{{
466  uint_t err = 0;
467  {paramtype} {param};
468
469  if (!PyArg_ParseTuple (args, "{pyparamtype}", &{param})) {{
470    return NULL;
471  }}
472  err = aubio_{shortname}_set_{param} (self->o, {param});
473
474  if (err > 0) {{
475    PyErr_SetString (PyExc_ValueError, "error running aubio_{shortname}_set_{param}");
476    return NULL;
477  }}
478  Py_RETURN_NONE;
479}}
480""".format(param = param, paramtype = paramtype, pyparamtype = pyparamtype, **self.__dict__)
481        return out
482
483    def gen_get(self):
484        out = """
485// {shortname} getters
486""".format(**self.__dict__)
487        for method in self.prototypes['get']:
488            params = get_params_types_names(method)
489            method_name = get_name(method)
490            assert len(params) == 1, \
491                "get method has more than one parameter %s" % params
492            param = method_name.split('aubio_'+self.shortname+'_get_')[-1]
493            paramtype = get_return_type(method)
494            ptypeconv = pyfromtype_fn[paramtype]
495            out += """
496static PyObject *
497Pyaubio_{shortname}_get_{param} (Py_{shortname} *self, PyObject *unused)
498{{
499  {ptype} {param} = aubio_{shortname}_get_{param} (self->o);
500  return (PyObject *){ptypeconv} ({param});
501}}
502""".format(param = param, ptype = paramtype, ptypeconv = ptypeconv,
503        **self.__dict__)
504        return out
505
506    def gen_methodef(self):
507        out = """
508static PyMethodDef Py_{shortname}_methods[] = {{""".format(**self.__dict__)
509        for m in self.prototypes['set']:
510            name = get_name(m)
511            shortname = name.replace('aubio_%s_' % self.shortname, '')
512            out += """
513  {{"{shortname}", (PyCFunction) Py{name},
514    METH_VARARGS, ""}},""".format(name = name, shortname = shortname)
515        for m in self.prototypes['get']:
516            name = get_name(m)
517            shortname = name.replace('aubio_%s_' % self.shortname, '')
518            out += """
519  {{"{shortname}", (PyCFunction) Py{name},
520    METH_NOARGS, ""}},""".format(name = name, shortname = shortname)
521        out += """
522  {NULL} /* sentinel */
523};
524"""
525        return out
526
527    def gen_typeobject(self):
528        return """
529PyTypeObject Py_{shortname}Type = {{
530  //PyObject_HEAD_INIT (NULL)
531  //0,
532  PyVarObject_HEAD_INIT (NULL, 0)
533  "aubio.{shortname}",
534  sizeof (Py_{shortname}),
535  0,
536  (destructor) Py_{shortname}_del,
537  0,
538  0,
539  0,
540  0,
541  0,
542  0,
543  0,
544  0,
545  0,
546  (ternaryfunc)Py_{shortname}_do,
547  0,
548  0,
549  0,
550  0,
551  Py_TPFLAGS_DEFAULT,
552  Py_{shortname}_doc,
553  0,
554  0,
555  0,
556  0,
557  0,
558  0,
559  Py_{shortname}_methods,
560  Py_{shortname}_members,
561  0,
562  0,
563  0,
564  0,
565  0,
566  0,
567  (initproc) Py_{shortname}_init,
568  0,
569  Py_{shortname}_new,
[0e70ef9]570  0,
571  0,
572  0,
573  0,
574  0,
575  0,
576  0,
577  0,
578  0,
[ccb9fb5]579}};
580""".format(**self.__dict__)
Note: See TracBrowser for help on using the repository browser.