complex.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package R
  2. /*
  3. #cgo LDFLAGS: -lm -lR
  4. #cgo CFLAGS: -I /usr/share/R/include/
  5. #include <stdlib.h>
  6. #include <R.h>
  7. #include <Rinternals.h>
  8. #include <Rdefines.h>
  9. #include <R_ext/Parse.h>
  10. #include <Rembedded.h>
  11. Rcomplex ComplexVectorElt(SEXP vec, int i) {
  12. return COMPLEX(vec)[i];
  13. }
  14. void SetComplexVectorElt(SEXP vec, int i, Rcomplex val) {
  15. COMPLEX(vec)[i] = val;
  16. }
  17. */
  18. import "C"
  19. type ComplexVector struct {
  20. expression
  21. }
  22. func NewComplexVector(vector []complex128) *ComplexVector {
  23. length := len(vector)
  24. v := ComplexVector{}
  25. //v.expr = C.allocVector(C.CPLXSXP, C.R_len_t(length))
  26. v.expr = C.allocVector(C.CPLXSXP, C.R_xlen_t(length))
  27. v.length = length
  28. v.CopyFrom(vector)
  29. return &v
  30. }
  31. func (this *ComplexVector) Get(i int) complex128 {
  32. this.boundsCheck(i)
  33. C.Rf_protect(this.expr)
  34. defer C.Rf_unprotect(1)
  35. c := C.ComplexVectorElt(this.expr, C.int(i))
  36. return complex(float64(c.r), float64(c.i))
  37. }
  38. func (this *ComplexVector) Set(i int, val complex128) {
  39. this.boundsCheck(i)
  40. C.Rf_protect(this.expr)
  41. defer C.Rf_unprotect(1)
  42. var c C.Rcomplex
  43. c.r = C.double(real(val))
  44. c.i = C.double(imag(val))
  45. C.SetComplexVectorElt(this.expr, C.int(i), c)
  46. }
  47. func (this *ComplexVector) CopyFrom(src []complex128) {
  48. C.Rf_protect(this.expr)
  49. defer C.Rf_unprotect(1)
  50. for i := 0; i < this.length; i++ {
  51. var c C.Rcomplex
  52. c.r = C.double(real(src[i]))
  53. c.i = C.double(imag(src[i]))
  54. C.SetComplexVectorElt(this.expr, C.int(i), c)
  55. }
  56. }
  57. func (this *ComplexVector) ToArray() []complex128 {
  58. C.Rf_protect(this.expr)
  59. defer C.Rf_unprotect(1)
  60. array := make([]complex128, this.length)
  61. for i := 0; i < this.length; i++ {
  62. c := C.ComplexVectorElt(this.expr, C.int(i))
  63. array[i] = complex(float64(c.r), float64(c.i))
  64. }
  65. return array
  66. }