Skip to content

Commit

Permalink
Enhance load_dna to, by default, load dnas in the dnalib directory of…
Browse files Browse the repository at this point in the history
… this package.

It can still load any dna if load_from_this_package == False.

PiperOrigin-RevId: 575154085
  • Loading branch information
oteret authored and Selforg Gardener committed Oct 20, 2023
1 parent cfa6441 commit 5b7a4da
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1541,7 +1541,9 @@
"load_from_out_f = True # @param [\"True\", \"False\"] {type:\"raw\"}\n",
"file_path_if_false = \"\" # @param {type:\"string\"}\n",
"\n",
"dna = load_dna(out_f if load_from_out_f else file_path_if_false)"
"# if you want to load a prepackaged dna, set load_from_this_package to True manually.\n",
"dna = load_dna(out_f if load_from_out_f else file_path_if_false,\n",
" load_from_this_package=False)"
]
},
{
Expand Down
17 changes: 14 additions & 3 deletions self_organising_systems/biomakerca/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
limitations under the License.
"""
import time
import pkg_resources

from jax import vmap
import jax.random as jr
Expand Down Expand Up @@ -112,14 +113,24 @@ def save_dna(dna, configuration_name, config, agent_logic, mutator, env_h=None,
return out_file_path


def load_dna(file):
def load_dna(file, load_from_this_package=True):
"""Load a dna from a .npy file.
If load_from_this_package is True, we load from this package's dnalib dir.
Otherwise, we load from the given file path.
This is the recommended way to load a dna, since it doesn't allow pickle,
which is a potential risk.
if the file given is without the '.npy' suffix, it will be added.
If the file given is without the '.npy' suffix, it will be added.
"""
if not file.lower().endswith(".npy"):
file = file + ".npy"
if load_from_this_package:
# extract from dnalib
resource_package = "self_organising_systems"
resource_path = '/'.join(("biomakerca", "dnalib", file))
fstream = pkg_resources.resource_stream(resource_package, resource_path)
return jp.load(fstream, allow_pickle=False)
with open(file, "rb") as f:
return jp.load(f, allow_pickle=False)

0 comments on commit 5b7a4da

Please sign in to comment.