Skip to content

Commit 3d0f2fd

Browse files
jishnubclaude
andauthored
Improve type-inference in adding operators (#708)
Retain the concrete operator type in PlusOperator only if space promotion preserves it, and store the operators as Operator{T} otherwise, so that the result is a small Union instead of a large one. Also avoid reconstructing a Conversion in promotedomainspace/promoterangespace if the space already matches. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 23c00d5 commit 3d0f2fd

2 files changed

Lines changed: 17 additions & 4 deletions

File tree

‎src/Operators/banded/Conversion.jl‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,10 @@ end
2727
domainspace(C::ConcreteConversion)=C.domainspace
2828
rangespace(C::ConcreteConversion)=C.rangespace
2929

30-
promotedomainspace(C::Conversion, sp::Space) = Conversion(sp, rangespace(C))
31-
promoterangespace(C::Conversion, sp::Space) = Conversion(domainspace(C), sp)
30+
promotedomainspace(C::Conversion, sp::Space) =
31+
sp == domainspace(C) ? C : Conversion(sp, rangespace(C))
32+
promoterangespace(C::Conversion, sp::Space) =
33+
sp == rangespace(C) ? C : Conversion(domainspace(C), sp)
3234

3335
function _implementconversionerror(a, b)
3436
error("Implement Conversion from ", typeof(a), " to ", typeof(b))

‎src/Operators/general/algebra.jl‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,21 @@ end
7373
function promoteplus(opsin, sz=size(first(opsin)))
7474
ops = filter(!iszeroop, opsin)
7575
ET = promote_eltypeof(opsin)
76+
O = eltype(convert_vector(_convertops(Operator{ET}, ops)))
7677
v = promotespaces(ops)
77-
PlusOperator{ET}(convert_vector(v), bandwidthsmax(v), sz,
78-
bandwidthsmax(v, blockbandwidths), bandwidthsmax(v, subblockbandwidths))
78+
w = convert_vector(v)
79+
# The types of the promoted operators may depend on the values of the spaces.
80+
# We retain the concrete type if the promotion preserves it (e.g. if the spaces agree),
81+
# and store the operators as Operator{ET} otherwise. This limits the result to a small Union
82+
if w isa Vector{O}
83+
_promoteplus(ET, w, v, sz)
84+
else
85+
_promoteplus(ET, strictconvert(Vector{Operator{ET}}, w), v, sz)
86+
end
7987
end
88+
# the bandwidths are computed from v, which may be better inferred than ops
89+
_promoteplus(::Type{ET}, ops, v, sz) where {ET} = PlusOperator{ET}(ops, bandwidthsmax(v), sz,
90+
bandwidthsmax(v, blockbandwidths), bandwidthsmax(v, subblockbandwidths))
8091

8192
domain(P::PlusOperator) = commondomain(P.ops)
8293

0 commit comments

Comments
 (0)