PythonAvg.yqls 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. (
  2. (let config (DataSource 'config))
  3. # prepare python udf
  4. (let ui32 (DataType 'Uint32))
  5. (let dbl (DataType 'Double))
  6. (let rt (ResourceType 'Python2))
  7. (let udfScript (String '@@
  8. class AvgCalc:
  9. def __init__(self):
  10. self.__count = 0
  11. self.__sum = 0
  12. def add(self, value):
  13. self.__sum = self.__sum + value
  14. self.__count = self.__count + 1
  15. def result(self):
  16. return self.__sum / float(self.__count)
  17. def avg_create():
  18. return AvgCalc()
  19. def avg_add(avg, value):
  20. avg.add(value)
  21. return avg
  22. def avg_result(avg):
  23. return avg.result()
  24. @@))
  25. (let avgCreate (ScriptUdf 'Python3 'avg_create (CallableType '() '(rt)) udfScript))
  26. (let avgAdd (ScriptUdf 'Python3 'avg_add (CallableType '() '(rt) '(rt) '(ui32)) udfScript))
  27. (let avgResult (ScriptUdf 'Python3 'avg_result (CallableType '() '(dbl) '(rt)) udfScript))
  28. # data
  29. (let x (Uint32 '10))
  30. (let y (Uint32 '30))
  31. (let z (Uint32 '5))
  32. # call udfs
  33. (let avg (Apply avgCreate))
  34. (let avg (Apply avgAdd avg x))
  35. (let avg (Apply avgAdd avg y))
  36. (let avg (Apply avgAdd avg z))
  37. (let result (Apply avgResult avg))
  38. # output result with type
  39. (let res_sink (DataSink 'result))
  40. (let world (Write! world res_sink (Key) result '( '('type) )))
  41. # finish
  42. (return (Commit! world res_sink))
  43. )