Skip to content

Commit 93c2192

Browse files
committed
Add GA.push_to_vilvik() convenience wrapper for the Vilvik SDK
1 parent 0b027b7 commit 93c2192

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

pygad/pygad.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,38 @@ def save(self, filename):
188188
file.write(cloudpickle_serialized_object)
189189
cloudpickle.dump(self, file)
190190

191+
def push_to_vilvik(self, *, api_key=None, **overrides):
192+
"""Import this run into Vilvik (https://vilvik.com) as an editable,
193+
continuable cloud record.
194+
195+
This is a thin convenience wrapper over the Vilvik SDK, which must be
196+
installed separately::
197+
198+
pip install vilvik
199+
200+
After ``ga.run()``, call ``ga.push_to_vilvik()`` (sign in first with the
201+
``vilvik login`` command or set the ``VILVIK_API_KEY`` environment
202+
variable). All keyword arguments are forwarded to ``vilvik.push`` (for
203+
example ``name=``, ``fitness_source=``, ``callbacks=``, ``preamble=``,
204+
``dry_run=True``). Returns the created record, or a capture report when
205+
``dry_run=True``.
206+
"""
207+
try:
208+
import vilvik
209+
except ImportError as exc:
210+
raise ImportError(
211+
"push_to_vilvik requires the Vilvik SDK. Install it with: "
212+
"pip install vilvik"
213+
) from exc
214+
215+
import pygad
216+
return vilvik.push(
217+
self,
218+
api_key=api_key,
219+
origin_overrides={"client": "pygad_wrapper", "pygad_version": pygad.__version__},
220+
**overrides,
221+
)
222+
191223
def load(filename):
192224
"""
193225
Reads a saved instance of the genetic algorithm:

tests/test_push_to_vilvik.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import sys
2+
import types
3+
import pytest
4+
import pygad
5+
6+
7+
def _ga():
8+
return pygad.GA(
9+
num_generations=1, num_parents_mating=2, sol_per_pop=4, num_genes=3,
10+
fitness_func=lambda ga_instance, solution, solution_idx: 0.0)
11+
12+
13+
def test_push_to_vilvik_forwards_to_sdk(monkeypatch):
14+
calls = {}
15+
fake = types.ModuleType("vilvik")
16+
17+
def fake_push(ga, **kw):
18+
calls["ga"] = ga
19+
calls["kw"] = kw
20+
return "RECORD"
21+
22+
fake.push = fake_push
23+
monkeypatch.setitem(sys.modules, "vilvik", fake)
24+
25+
ga = _ga()
26+
out = ga.push_to_vilvik(name="local run")
27+
assert out == "RECORD"
28+
assert calls["ga"] is ga
29+
assert calls["kw"]["name"] == "local run"
30+
assert calls["kw"]["origin_overrides"]["client"] == "pygad_wrapper"
31+
assert calls["kw"]["origin_overrides"]["pygad_version"] == pygad.__version__
32+
33+
34+
def test_push_to_vilvik_missing_sdk(monkeypatch):
35+
monkeypatch.setitem(sys.modules, "vilvik", None) # forces `import vilvik` to raise ImportError
36+
ga = _ga()
37+
with pytest.raises(ImportError, match="pip install vilvik"):
38+
ga.push_to_vilvik()

0 commit comments

Comments
 (0)