Skip to content

Adding json object migration script and documentation. #1009

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

Merged
merged 7 commits into from
Feb 28, 2025
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
29 changes: 29 additions & 0 deletions docs/home/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,35 @@ from bloqade.analog.atom_arrangement import Square
...
```

## Migrating old bloqade JSON files

If you have old bloqade JSON files, you will not be able to directly deserialize them anymore because of the package restructuring. However, we have provided some tools to migrate those JSON files to be compatible with `bloqade-analog`. You can do this by running the following command in the command line for a one or more files:

```sh
python -m bloqade.analog.migrate <path_to_old_json_file1> <path_to_old_json_file2> ...
```
With default arguments this will create a new file with the same name as the old file, but with `-analog` appended to the end of the filename. For example, if you have a file called `my_bloqade.json`, the new file will be called `my_bloqade-analog.json`. You can then use `load` to deserialize this file with the `bloqade-analog` package. There are other options for converting the file, such as setting the indent level for the output file or overwriting the old file. You can see all the options by running:

```sh
python -m bloqade.analog.migrate --help
```

Another option is to use the migration tool in a python script:

```python
from bloqade.analog.migrate import migrate

# set the indent level for the output file
indent: int = ...
# set to True if you want to overwrite the old file, otherwise the new file will be created with -analog appended to the end of the filename
overwrite: bool = ...
f
or filename in ["file1.json", "file2.json", ...]:
migrate(filename, indent=indent, overwrite=overwrite)
```
This will migrate all the files in the list to the new format.


## Having trouble, comments, or concerns?

Please open an issue on our [GitHub](https://github.com/QuEraComputing/bloqade-analog/issues)
79 changes: 79 additions & 0 deletions src/bloqade/analog/migrate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
from typing import IO, Any, Dict, List
from dataclasses import field, dataclass

import simplejson as json


@dataclass
class JSONWalker:
has_done_something: bool = field(init=False, default=False)

def walk_dict(self, obj: Dict[str, Any]) -> Dict[str, Any]:
new_obj = {}
for key, value in obj.items():

if key.startswith("bloqade.analog."):
new_obj[key] = self.walk(value)
elif key.startswith("bloqade."):
new_obj[key.replace("bloqade.", "bloqade.analog.")] = self.walk(value)
self.has_done_something = True
else:
new_obj[key] = self.walk(value)

return new_obj

def walk(self, obj: Dict[str, Any] | List[Any]) -> Dict[str, Any] | List[Any]:
if isinstance(obj, dict):
return self.walk_dict(obj)
elif isinstance(obj, list):
return list(map(self.walk, obj))
else:
return obj

def convert(self, obj: Dict[str, Any] | List[Any]):
self.has_done_something = False
new_obj = self.walk(obj)
return new_obj, self.has_done_something


def _migrate(input_oi: IO[str], output_oi: IO[str], indent: int | None = None):
obj = json.load(input_oi)
new_obj, has_done_something = JSONWalker().convert(obj)

if has_done_something:
json.dump(new_obj, output_oi, indent=indent)


def migrate(
filename: str,
indent: int | None = None,
overwrite: bool = False,
):
new_filename = filename if overwrite else filename.replace(".json", "-analog.json")
with open(filename, "r") as in_io, open(new_filename, "w") as out_io:
_migrate(in_io, out_io, indent)

Check warning on line 54 in src/bloqade/analog/migrate.py

View check run for this annotation

Codecov / codecov/patch

src/bloqade/analog/migrate.py#L52-L54

Added lines #L52 - L54 were not covered by tests


def _entry():
import argparse

Check warning on line 58 in src/bloqade/analog/migrate.py

View check run for this annotation

Codecov / codecov/patch

src/bloqade/analog/migrate.py#L58

Added line #L58 was not covered by tests

import tqdm

Check warning on line 60 in src/bloqade/analog/migrate.py

View check run for this annotation

Codecov / codecov/patch

src/bloqade/analog/migrate.py#L60

Added line #L60 was not covered by tests

parser = argparse.ArgumentParser()

Check warning on line 62 in src/bloqade/analog/migrate.py

View check run for this annotation

Codecov / codecov/patch

src/bloqade/analog/migrate.py#L62

Added line #L62 was not covered by tests

parser.add_argument("filenames", type=str, nargs="*")
parser.add_argument("--indent", type=int, default=None)
parser.add_argument(

Check warning on line 66 in src/bloqade/analog/migrate.py

View check run for this annotation

Codecov / codecov/patch

src/bloqade/analog/migrate.py#L64-L66

Added lines #L64 - L66 were not covered by tests
"--overwrite",
action="store_true",
help="Overwrite the original file",
default=False,
)

args = parser.parse_args()
for filename in tqdm.tqdm(args.filenames):
migrate(filename, args.indent, args.overwrite)

Check warning on line 75 in src/bloqade/analog/migrate.py

View check run for this annotation

Codecov / codecov/patch

src/bloqade/analog/migrate.py#L73-L75

Added lines #L73 - L75 were not covered by tests


if __name__ == "__main__":
_entry()

Check warning on line 79 in src/bloqade/analog/migrate.py

View check run for this annotation

Codecov / codecov/patch

src/bloqade/analog/migrate.py#L79

Added line #L79 was not covered by tests
34 changes: 34 additions & 0 deletions tests/test_migrate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import io

import simplejson as json

from bloqade.analog.migrate import _migrate


def test_walk_dict():

obj = {
"key1": "value1",
"bloqade.key2": "value2",
"bloqade.analog.key3": "value3",
"nested": {"key4": "bloqade.value4", "bloqade.key5": "value5"},
"list": [{"key6": "value6"}, {"bloqade.key7": "value7"}],
}

expected = {
"key1": "value1",
"bloqade.analog.key2": "value2",
"bloqade.analog.key3": "value3",
"nested": {"key4": "bloqade.value4", "bloqade.analog.key5": "value5"},
"list": [{"key6": "value6"}, {"bloqade.analog.key7": "value7"}],
}

obj_str = json.dumps(obj)
expected_str = json.dumps(expected)

in_io = io.StringIO(obj_str)
out_io = io.StringIO()

_migrate(in_io, out_io)

assert out_io.getvalue() == expected_str