Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promote initial state when converting from non-homogeneous python lists. #527

Merged
merged 4 commits into from
Oct 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions ext/SciMLBasePythonCallExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,18 @@
pyconvert(Int, length(first(inspect.getfullargspec(f2))) - inspect.ismethod(f2))
end

_pyconvert(x::Py) = pyisinstance(x, pybuiltins.list) ? [_pyconvert(x) for x in x] : pyconvert(Any, x)
_pyconvert(x::PyList) = [_pyconvert(x) for x in x]
_pyconvert(x::Py) = pyisinstance(x, pybuiltins.list) ? _promoting_collect(_pyconvert(x) for x in x) : pyconvert(Any, x)
_pyconvert(x::PyList) = _promoting_collect(_pyconvert(x) for x in x)

Check warning on line 17 in ext/SciMLBasePythonCallExt.jl

View check run for this annotation

Codecov / codecov/patch

ext/SciMLBasePythonCallExt.jl#L16-L17

Added lines #L16 - L17 were not covered by tests
_pyconvert(x) = x

# _promoting_collect might copy its input
_promoting_collect(x) = _promoting_collect(collect(x))
function _promoting_collect(x::AbstractArray)
isconcretetype(eltype(x)) && return x
T = mapreduce(typeof, promote_type, x)
T == eltype(x) ? x : T.(x)

Check warning on line 25 in ext/SciMLBasePythonCallExt.jl

View check run for this annotation

Codecov / codecov/patch

ext/SciMLBasePythonCallExt.jl#L21-L25

Added lines #L21 - L25 were not covered by tests
end

SciMLBase.prepare_initial_state(u0::Union{Py, PyList}) = _pyconvert(u0)
SciMLBase.prepare_function(f::Py) = _pyconvert ∘ f

Expand Down
5 changes: 5 additions & 0 deletions test/python/pythoncall.jl
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,8 @@ using DifferentialEquations, PythonCall
sol = de.solve(prob,reltol=1e-3,abstol=1e-3)
""", @__MODULE__)
end

@testset "promotion" begin
_u0 = pyconvert(Any, pyeval("""de.SciMLBase.prepare_initial_state([1.0, 0, 0])""", @__MODULE__))
@test _u0 isa Vector{Float64}
end
Loading