@@ -209,22 +209,47 @@ size_t Circuit::max_layer_width() const {
209209void Circuit::remove_unused_nodes () {
210210 // Should be run before adding a final root layer;
211211 // because it might change ix's.
212- std::vector<std::vector<bool >> used;
213- used.reserve (nb_layers ());
214- for (const auto & layer : layers)
215- used.emplace_back (layer.size (), false );
212+ if (nb_layers () == 1 )
213+ return ;
214+
215+ // we determine useless nodes.
216+ // first layer we skip because they
217+ // are not removed and their ix is
218+ // not consecutive [0..n] such that the
219+ // first `used` vector would be more
220+ // annoying to create the proper size of.
221+
222+ std::vector<std::vector<bool >> used (nb_layers ());
223+ for (std::size_t i = 1 ; i < nb_layers (); ++i)
224+ used[i].resize (layers[i].size (), false );
216225
217226 // set roots as used
218- for (auto &root : roots)
219- used[root->layer ][root->ix ] = true ;
227+ for (auto &root : roots) {
228+ if (root->layer != 0 ) {
229+ // assert(root->layer < used.size());
230+ // assert(root->ix < used[root->layer].size());
231+ used[root->layer ][root->ix ] = true ;
232+ }
233+ }
220234
221235 // iterate backwards over layers
222236 // tag children of useful nodes
223237 for (auto it = layers.rbegin (); it != layers.rend (); ++it) {
224238 for (auto &node : *it) {
225- if (used[node->layer ][node->ix ])
226- for (auto child: node->children )
239+ if (node->layer == 0 )
240+ continue ; // skip input layer, idx error otherwise
241+
242+ assert (node->layer < used.size ());
243+ assert (node->ix < used[node->layer ].size ());
244+ if (used[node->layer ][node->ix ]) {
245+ for (auto child: node->children ) {
246+ if (child->layer == 0 )
247+ continue ; // skip input layer, idx error otherwise
248+ // assert(child->layer < used.size());
249+ // assert(child->ix < used[child->layer].size());
227250 used[child->layer ][child->ix ] = true ;
251+ }
252+ }
228253 }
229254 }
230255
0 commit comments