Commit 8bda5654c02f9a660b8f9c41c8d4ac9e754aaf41

Authored by Jürgen Knödlseder
1 parent 85b55f53

Allow setting of Ndarray using single index in Python

Showing 1 changed file with 25 additions and 12 deletions
pyext/GNdarray.i
@@ -108,21 +108,34 @@ public: @@ -108,21 +108,34 @@ public:
108 return ((*self)(index)); 108 return ((*self)(index));
109 } 109 }
110 void __setitem__(int GTuple[], const double& value) { 110 void __setitem__(int GTuple[], const double& value) {
111 - if (GTuple[0] != self->dim()) {  
112 - throw GException::invalid_value("__setitem__(int)", "Invalid "  
113 - "access of "+gammalib::str(self->dim())+"-dimensional "  
114 - "array with "+gammalib::str(GTuple[0])+"-dimensional "  
115 - "access operator."); 111 + // Handle first the special case of a single index. In Python we want
  112 + // to support accessing a n-dimensional array with a single index
  113 + if (GTuple[0] == 1) {
  114 + if (GTuple[1] >= 0 && GTuple[1] < self->size()) {
  115 + (*self)(GTuple[1]) = value;
  116 + }
  117 + else {
  118 + throw GException::out_of_range("__ssetitem__(int)", "Array "
  119 + "index", GTuple[1], self->size());
  120 + }
116 } 121 }
117 - int index = 0;  
118 - for (size_t i = 0; i < self->shape().size(); ++i) {  
119 - if (GTuple[i+1] < 0 || GTuple[i+1] >= self->shape()[i]) {  
120 - throw GException::out_of_range("__setitem__(int)", "Dimension "+  
121 - gammalib::str(i)+" index", GTuple[i+1], self->shape()[i]); 122 + else {
  123 + if (GTuple[0] != self->dim()) {
  124 + throw GException::invalid_value("__setitem__(int)", "Invalid "
  125 + "access of "+gammalib::str(self->dim())+"-dimensional "
  126 + "array with "+gammalib::str(GTuple[0])+"-dimensional "
  127 + "access operator.");
122 } 128 }
123 - index += self->strides()[i] * GTuple[i+1]; 129 + int index = 0;
  130 + for (size_t i = 0; i < self->shape().size(); ++i) {
  131 + if (GTuple[i+1] < 0 || GTuple[i+1] >= self->shape()[i]) {
  132 + throw GException::out_of_range("__setitem__(int)", "Dimension "+
  133 + gammalib::str(i)+" index", GTuple[i+1], self->shape()[i]);
  134 + }
  135 + index += self->strides()[i] * GTuple[i+1];
  136 + }
  137 + (*self)(index) = value;
124 } 138 }
125 - (*self)(index) = value;  
126 } 139 }
127 GNdarray __add__(const GNdarray &a) { 140 GNdarray __add__(const GNdarray &a) {
128 return (*self) + a; 141 return (*self) + a;