328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608 | def solve_VIE_1(*, kernel_values, g_values=None, soln_init_value=None, time_step=1.0, coll_divs=3,
coll_choices=[1,2,3], return_polys=False, force_continuous=False, show_warnings=True):
r'''
Solve a Volterra integral equation of the first kind.
Finds $y(t)$ satisfying
$$g(t) = \int_0^t K(t-s)\,y(s)\,ds$$
Parameters
----------
kernel_values : array_like of shape (N,) or (N, d, d)
Values of $K(s)$ at times $s = 0, h, 2h, \ldots, (N-1)h$, where $h$
is ``time_step``. Pass a 1-D array for scalar equations or a 3-D array
of shape ``(N, d, d)`` for $d$-dimensional vector equations.
g_values : array_like of shape (N,) or (N, d) or (N, d, m), optional
Right-hand side $g(t)$ sampled at the same times as ``kernel_values``.
For matrix-valued equations pass shape ``(N, d, m)`` to solve $m$
right-hand sides simultaneously. Defaults to zero.
soln_init_value : float or array_like of shape (d,) or (d, m), optional
Initial value $y(0)$ imposed when ``force_continuous=True``. Has no
effect when ``force_continuous=False`` (default). Required when
``force_continuous=True``.
time_step : float, optional
Spacing $h$ between consecutive sample times. Must be positive.
Default is 1.0.
coll_divs : int, optional
Number of collocation sub-intervals per mesh interval. Must be a
positive integer. Default is 3.
coll_choices : list of int, optional
Indices selecting the collocation nodes within each sub-interval.
Each entry $k$ corresponds to the node $k / c$ where $c$ =
``coll_divs``, placed in $(0, 1]$; zero is excluded. Entries must be
distinct integers in $\{1, \ldots, \text{coll\_divs}\}$.
Default is ``[1, 2, 3]``.
return_polys : bool, optional
If ``True``, also return the piecewise polynomial solution.
Default is ``False``.
force_continuous : bool, optional
If ``True``, enforce continuity of the piecewise polynomial solution
across mesh-interval boundaries, using ``soln_init_value`` as the
starting condition. The default discontinuous method is generally more
accurate for the same number of collocation nodes. Default is
``False``.
show_warnings : bool, optional
If ``True`` (default), print a warning when ``kernel_values`` is
truncated, when ``soln_init_value`` has no effect, or when the Numba
fallback is used.
Returns
-------
soln_values : ndarray of shape (N,) or (N, d) or (N, d, m)
Solution values $y(t)$ at the same times as the input arrays.
Returned when ``return_polys=False`` (default).
(soln_values, polys) : tuple
Returned when ``return_polys=True``. ``soln_values`` is as above.
For scalar equations, ``polys`` is a list of
`numpy.polynomial.Polynomial` objects, one per mesh interval, each
mapping $t$ to the polynomial approximation of $y(t)$ on that
interval. For vector equations, each element of ``polys`` is an object
array of shape ``(d,)`` (or ``(d, m)`` for matrix equations) containing
one polynomial per component.
Notes
-----
The length $N$ of the input arrays must satisfy
$N \equiv 1 \pmod{\text{coll\_divs}^2}$. If a longer array is supplied it
is truncated to the largest conforming length and a warning is printed
(unless ``show_warnings=False``).
Zero is excluded from ``coll_choices`` because the VIE-1 collocation
scheme does not place nodes at $t = 0$; doing so would require evaluating
the equation at $t = 0$ where both sides are zero by definition, giving no
information about $y(0)$.
The solver dispatches at runtime to a D-extension routine specialised for
the given collocation setting. For scalar equations, settings not compiled
into the extension fall back to a Numba-JIT implementation (requires the
``numba`` optional dependency); a warning is printed when the fallback is
used. For vector equations only the compiled settings are supported.
References
----------
.. [1] Brunner, H. *Collocation Methods for Volterra Integral and Related
Functional Differential Equations.* Cambridge University Press, 2004.
Sections 2.4.1, 2.4.3, and 2.4.5.
'''
# ------------------------------------------------------------------ complex dispatch
if _cplx.is_complex(kernel_values, g_values, soln_init_value):
K_arr = np.asarray(kernel_values)
is_scalar = (K_arr.ndim == 1)
d_orig = 0 if is_scalar else K_arr.shape[1]
K_real = _cplx._block_kernel(K_arr)
g_real = _cplx._expand_g(np.asarray(g_values)) if g_values is not None else None
init_real = _cplx._expand_init(soln_init_value) if soln_init_value is not None else None
result = solve_VIE_1(
kernel_values=K_real, g_values=g_real, soln_init_value=init_real,
time_step=time_step, coll_divs=coll_divs, coll_choices=coll_choices,
return_polys=return_polys, force_continuous=force_continuous,
show_warnings=show_warnings)
if return_polys:
soln_real, polys_real = result
return (_cplx._recombine(soln_real, d_orig),
_cplx._recombine_polys(polys_real, d_orig))
return _cplx._recombine(result, d_orig)
kernel_values_ = np.asarray(kernel_values, dtype=float)
ndim = kernel_values_.ndim
if ndim not in (1, 3):
raise ValueError(
f"kernel_values must be 1-D (scalar) or 3-D (N, d, d), got shape {kernel_values_.shape}")
N_orig = len(kernel_values_)
N, kernel_values_ = _truncate_N(kernel_values_, coll_divs, show_warnings)
# ------------------------------------------------------------------ vector path
if ndim == 3:
_, d1, d2 = kernel_values_.shape
if d1 != d2:
raise ValueError(f"kernel_values must have shape (N, d, d), got {kernel_values_.shape}")
d = d1
if g_values is not None:
g_values_ = np.asarray(g_values, dtype=float)
if g_values_.ndim == 3: # matrix case: shape (N, d, m_cols)
m_cols = g_values_.shape[2]
if g_values_.shape[1] != d:
raise ValueError(
f"g_values shape {g_values_.shape} incompatible with kernel_values shape {kernel_values_.shape}")
if soln_init_value is not None:
init_cols = np.asarray(soln_init_value, dtype=float)
if init_cols.shape != (d, m_cols):
raise ValueError(
f"soln_init_value must have shape ({d}, {m_cols}) for matrix-valued g_values")
else:
init_cols = np.zeros((d, m_cols))
g_cols = g_values_[:N]
def _col_vie1(j):
return solve_VIE_1(kernel_values=kernel_values_,
g_values=g_cols[:, :, j],
soln_init_value=init_cols[:, j],
time_step=time_step, coll_divs=coll_divs,
coll_choices=coll_choices,
return_polys=return_polys,
force_continuous=force_continuous,
show_warnings=show_warnings)
with ThreadPoolExecutor(max_workers=m_cols) as ex:
results = list(ex.map(_col_vie1, range(m_cols)))
if return_polys:
col_solns = [r[0] for r in results]
col_polys = [r[1] for r in results]
soln = np.stack(col_solns, axis=2)
mesh_divs = len(col_polys[0])
mat_polys = []
for n in range(mesh_divs):
arr = np.empty((d, m_cols), dtype=object)
for j in range(m_cols):
arr[:, j] = col_polys[j][n]
mat_polys.append(arr)
return (soln, mat_polys)
return np.stack(results, axis=2)
else:
if g_values_.shape != (N_orig, d):
raise ValueError(
f"g_values shape {g_values_.shape} incompatible with kernel_values shape {kernel_values_.shape}")
g_values_ = g_values_[:N]
else:
g_values_ = np.zeros((N, d), dtype=float)
assert time_step > 0.0, "time_step must be positive"
if soln_init_value is not None:
if (not force_continuous) and show_warnings:
print("warning: setting soln_init_value has no effect when force_continuous=False.")
soln_init_value_ = np.asarray(soln_init_value, dtype=float)
if soln_init_value_.shape != (d,):
raise ValueError(
f"soln_init_value must have shape ({d},) for d={d}")
else:
assert not force_continuous, "must specify soln_init_value for continuous solutions"
soln_init_value_ = np.zeros(d)
assert 0 not in coll_choices, "zero cannot be a collocation parameter"
assert coll_divs > 0, "coll_divs must be a positive integer"
assert all(isinstance(c, int) for c in coll_choices), "coll_choices must be a list of integers"
assert all(coll_choices.count(c) <= 1 for c in coll_choices), "coll_choices must be distinct"
for choice in coll_choices:
assert 1 <= choice <= coll_divs, "coll_choices must contain only integers from 1 to coll_divs"
coll_choices = sorted(coll_choices)
if (coll_divs, tuple(coll_choices)) in _VIE1_NONCONVERGENT:
raise ValueError(
f"Collocation setting (coll_divs={coll_divs}, coll_choices={coll_choices}) "
f"does not produce a convergent VIE-1 solver and is not supported. "
f"Use a setting from fast_coll_settings_VIE_1.")
if (coll_divs, coll_choices) not in _fast_settings_VIE_1:
raise RuntimeError(
f"Collocation setting (coll_divs={coll_divs}, coll_choices={coll_choices}) "
f"not supported by D extension.")
# kernel must be C-contiguous (N, d, d) and g (N, d)
k_c = np.ascontiguousarray(kernel_values_, dtype=np.float64)
g_c = np.ascontiguousarray(g_values_, dtype=np.float64)
N_used = len(k_c)
mesh_divs = (N_used - 1) // coll_divs**2
soln_vals, poly_coefs = _dlang_module.solve_vie1_vec_d(
g_c, k_c, soln_init_value_, time_step,
coll_divs, coll_choices, return_polys, force_continuous)
if return_polys:
return (soln_vals, _build_vec_polys(poly_coefs, mesh_divs, coll_divs, time_step))
return soln_vals
# ------------------------------------------------------------------ scalar path
assert len(kernel_values_.shape) == 1, "kernel_values must be a 1-dim array"
if g_values is not None:
g_values_ = np.asarray(g_values, dtype=float)
assert len(g_values_.shape) == 1, "g_values must be a 1-dim array"
assert len(g_values_) == N_orig, "kernel_values and g_values must have the same length"
g_values_ = g_values_[:N]
else:
g_values_ = np.zeros(N)
assert time_step > 0.0, "time_step must be positive"
if soln_init_value is None:
assert not force_continuous, \
"must specify an initial value for continuous solutions"
# We still need a value to pass into the JIT version. It shouldn't be used!
soln_init_value_ = 0.0
else:
if (not force_continuous) and show_warnings:
print("warning: setting soln_init_value has no effect, since "
"force_continuous is set to false.")
soln_init_value_ = 0.0
else:
soln_init_value_ = float(soln_init_value)
assert 0 not in coll_choices, "zero cannot be a collocation parameter"
assert coll_divs > 0, "coll_divs must be a positive integer"
assert all([isinstance(choice, int) for choice in coll_choices]), \
"coll_choices must be a list of integers"
assert all([coll_choices.count(c) <= 1 for c in coll_choices]), \
"all integers in coll_choices must be distinct"
for choice in coll_choices:
assert 1 <= choice <= coll_divs, \
"coll_choices must contain only integers from 1 to coll_divs"
coll_choices = sorted(coll_choices)
if (coll_divs, tuple(coll_choices)) in _VIE1_NONCONVERGENT:
raise ValueError(
f"Collocation setting (coll_divs={coll_divs}, coll_choices={coll_choices}) "
f"does not produce a convergent VIE-1 solver and is not supported. "
f"Use a setting from fast_coll_settings_VIE_1.")
if (coll_divs, coll_choices) in _fast_settings_VIE_1:
soln_vals, poly_coefs = _dlang_module.solve_vie1_d(
g_values_, kernel_values_, soln_init_value_, time_step,
coll_divs, coll_choices, return_polys, force_continuous)
elif _numba_available:
if show_warnings:
print("warning: falling back to slower python/numba code")
soln_vals, poly_coefs = _numba_solvers.solve_VIE_1_jit(
g_values_, kernel_values_, soln_init_value_, time_step,
coll_divs, coll_choices, return_polys, force_continuous)
else:
raise NotImplementedError(
f"Collocation setting (coll_divs={coll_divs}, coll_choices={coll_choices}) is not "
f"supported by the D extension. Install numba to enable the fallback solver, or "
f"use a supported setting (see fast_coll_settings_VIE_1)."
)
if return_polys:
polys = []
for i, coefs in enumerate(poly_coefs):
domain = (i * coll_divs**2 * time_step, (i+1) * coll_divs**2 * time_step)
poly = np.polynomial.Polynomial(coefs, domain=domain, window=(0.0, 1.0), symbol='t')
poly = poly.convert(domain=domain, window=domain)
polys.append(poly.trim())
return (soln_vals, polys)
else:
return soln_vals
|