+ // Find dummy symbols that occur twice in the same indexed object.
+ exvector local_var_dummies;
+ local_var_dummies.reserve(e.nops()/2);
+ for (size_t i=1; i<e.nops(); ++i) {
+ if (!is_a<varidx>(e.op(i)))
+ continue;
+ for (size_t j=i+1; j<e.nops(); ++j) {
+ if (is_dummy_pair(e.op(i), e.op(j))) {
+ local_var_dummies.push_back(e.op(i));
+ for (auto k = variant_dummy_indices.begin(); k!=variant_dummy_indices.end(); ++k) {
+ if (e.op(i).op(0) == k->op(0)) {
+ variant_dummy_indices.erase(k);
+ break;
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ // In the case where a dummy symbol occurs twice in the same indexed object
+ // we try all possibilities of raising/lowering and keep the least one in
+ // the sense of ex_is_less.
+ ex optimal_e = e;
+ size_t numpossibs = 1 << local_var_dummies.size();
+ for (size_t i=0; i<numpossibs; ++i) {
+ ex try_e = e;
+ for (size_t j=0; j<local_var_dummies.size(); ++j) {
+ exmap m;
+ if (1<<j & i) {
+ ex curr_idx = local_var_dummies[j];
+ ex curr_toggle = ex_to<varidx>(curr_idx).toggle_variance();
+ m[curr_idx] = curr_toggle;
+ m[curr_toggle] = curr_idx;
+ }
+ try_e = e.subs(m, subs_options::no_pattern);
+ }
+ if(ex_is_less()(try_e, optimal_e))
+ { optimal_e = try_e;
+ something_changed = true;
+ }
+ }
+ e = optimal_e;
+
+ if (!is_a<indexed>(e))
+ return true;
+
+ exvector seq = ex_to<indexed>(e).seq;
+