Skip to content

Commit

Permalink
Bloqade Emulator Integration. (#549)
Browse files Browse the repository at this point in the history
* chore: Update pdm.lock (#276)

* Braket submit bug (#277)

* Fixing enum value for Braket SDK site type.

* adding integration test.

* removing indent that is cutting defect density generation short (#278)

* implemented ability to skip invalid tasks for submission (#279)

* implemented ability to skip invalid tasks for submission

* Update src/bloqade/submission/braket.py

Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

---------

Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* add more tests and enhance cast
1) add tests for scales
2) add tests for bravais
3) to do 2) this commit add cast for tuple type

* add some basic docstring to builder methods (#269)

* 280 some of bravias lattices lattice spacing are not properly set (#281)

* chore: Update pdm.lock (#282)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* tmp

* add more testing cases, bumping to 71%

* 267 Pages fix (#284)

* fixing example + adding examples to CI.

* updating example to work with doc build.

* fixing bug in adiabatic example.

* fix baravias bugs and more test
1) fix bugs on wrong index*elementary vectors
2) bump testing cases on bravias to 96
3) fix bugs on Rectangular when spacing_y dose not specify

* update to comply ruff

* modify to comply ruff

* add test for double parallel

* modify to comply black

* modify format

* try

* test pre-compile

* pre-commit linter fix

* chore: Update pdm.lock (#286)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* Fix bugs on bravais, add more tests, and bump up coverages (#285)

* add more tests and enhance cast
1) add tests for scales
2) add tests for bravais
3) to do 2) this commit add cast for tuple type

* tmp

* add more testing cases, bumping to 71%

* fix baravias bugs and more test
1) fix bugs on wrong index*elementary vectors
2) bump testing cases on bravias to 96
3) fix bugs on Rectangular when spacing_y dose not specify

* update to comply ruff

* modify to comply ruff

* modify to comply black

* modify format

* try

* test pre-compile

* pre-commit linter fix

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* waveform visitors
1) add more testing
2) fix waveform visitors Error types inconsistent bug
3) fix waveform visitors not waveform ast error bug
4) fix GaussianKernel typo

* Fix bugs for Waveform visitor and more tests (#287)

* add more tests and enhance cast
1) add tests for scales
2) add tests for bravais
3) to do 2) this commit add cast for tuple type

* tmp

* add more testing cases, bumping to 71%

* fix baravias bugs and more test
1) fix bugs on wrong index*elementary vectors
2) bump testing cases on bravias to 96
3) fix bugs on Rectangular when spacing_y dose not specify

* update to comply ruff

* modify to comply ruff

* add test for double parallel

* modify to comply black

* modify format

* try

* test pre-compile

* pre-commit linter fix

* waveform visitors
1) add more testing
2) fix waveform visitors Error types inconsistent bug
3) fix waveform visitors not waveform ast error bug
4) fix GaussianKernel typo

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* add more tests

* fix bug in Scalar.canonicalize matching duplicate / missing Negative on rhs/lhs side bug

* fix test does not trigger

* more cases

* Adding integration test with Quera internal API (#289)

* Squashed commit of the following:

commit cf0587f2a6d21399a3a2e332bea07d0e95e7381b
Author: Phillip Weinberg <weinbe58@gmail.com>
Date:   Thu Jul 13 15:15:36 2023 -0400

    Removing references to access keys

commit c56be286850f215f30caef7c3e935e19b71017da
Author: Phillip Weinberg <weinbe58@gmail.com>
Date:   Thu Jul 13 14:23:58 2023 -0400

    updating future

commit cf4f307422819e7a266e17ea42fb34a0c4e3432c
Author: Phillip Weinberg <weinbe58@gmail.com>
Date:   Thu Jul 13 14:22:18 2023 -0400

    removing token json.

commit a8c8e43530cc84aee653c0e1490fa8e8756442e9
Author: Phillip Weinberg <weinbe58@gmail.com>
Date:   Thu Jul 13 13:47:46 2023 -0400

    Adding mock for internal API submission and fetching task results.

commit a7ab7ee9d8768500f153a3771300b5c4ca4e2b64
Author: Phillip Weinberg <weinbe58@gmail.com>
Date:   Thu Jul 13 13:05:34 2023 -0400

    updating annotation.

commit 67f01db76a581af44ef886358fdcaf5469d7ec7e
Author: Phillip Weinberg <weinbe58@gmail.com>
Date:   Thu Jul 13 13:05:15 2023 -0400

    switching to queue api for fetching task status.

commit 8efa19dd0d71b02070b7049ef107da6afe3d6649
Author: Phillip Weinberg <weinbe58@gmail.com>
Date:   Thu Jul 13 13:04:42 2023 -0400

    adding stricter argument initialization on SubmissionBackend.

commit d92e275c2420aa23cc8d3c3fb865512b8fcaced7
Author: Phillip Weinberg <weinbe58@gmail.com>
Date:   Thu Jul 13 13:04:03 2023 -0400

    fixing issue with path.

commit 0654029ba21086443c12b3a7183a48304a48a20e
Author: Phillip Weinberg <weinbe58@gmail.com>
Date:   Thu Jul 13 13:03:36 2023 -0400

    updating api config for integration.

* adding vcrpy to dependencies.

* updating ci test.

* using pytest plugin for `vcrpy`

* updating how the requests are recorded

* updating retreival cassette to fetch results.

* removing tokens.

* adding check for if arguments are being used in quera.

* fix logistickernel bug and more test
1) fix logistickernel didnt return bug
2) add more tests

* fix missing return for RabiRouter

* tmp

* Refactor submission code to call `task.result()` Braket API to block fetching tasks. (#291)

* refactor code to call braket results() API to block report.

* removing sorting of tasks to preserve the polling order for tasks.

* finished merge master

* fix bug in var(Scalar), and remove redundant printing

* chore: Update pdm.lock (#293)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* Fix bug and more tests on codegen (#295)

* add more tests

* add more integration tests for codegen

* fix bug when ConstantCodeGen hit Negative wvfm node.

* fix bug when slice produce duplicate time points

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* Mocking braket API for submission tests.  (#294)

* updating braket submission examples and mocking submission api

* removing double test.

* adding rc file for coverage.

* chore: Update pdm.lock (#301)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* Fix Sample bugs for eval_decimal and add more tests (#300)

* add more tests

* add more integration tests for codegen

* fix bug when ConstantCodeGen hit Negative wvfm node.

* tmp

* fix bug when slice produce duplicate time points

* tmp

* tmp

* adding fix for Sample interpolation.

* tmp

* add framework for pretty print testing and fix bugs #297

* fix bug in print with children

* remove [html] from .coveragerc and fix bugs in print testing

* add checking for default filling of global term

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>

* making `Append` give correct value for `eval_decimal(duration)`. (#306)

* Fix bugs in Piecewise (Linear/Constant)Codegen slice node bug (#305)

* chore: Update pdm.lock (#310)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* chore: Update pdm.lock (#316)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* chore: Update pdm.lock (#319)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* Fix bug related to codegen for sample python functions  (#307)

* add more tests

* add more integration tests for codegen

* fix bug when ConstantCodeGen hit Negative wvfm node.

* tmp

* fix bug when slice produce duplicate time points

* tmp

* tmp

* adding fix for Sample interpolation.

* tmp

* add framework for pretty print testing and fix bugs #297

* fix bug in print with children

* remove [html] from .coveragerc and fix bugs in print testing

* finished assignment scan tests

* fix bug in codegen slice

* making `Append` give correct value for `eval_decimal(duration)`.

* add more tests for batch_assign

* add more testing cases

* add more tests and fix bugs related to fn() sampling

* fixing `samples` of `Sample` + adding example of using codegen directly.

* fix bug in matching of namedpulese

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Xiu-zhe (Roger) Luo <rogerluo.rl18@gmail.com>

* fix mkdocs cannot correctly processing docstrings. (#318)

* add more tests

* add more integration tests for codegen

* fix bug when ConstantCodeGen hit Negative wvfm node.

* tmp

* fix bug when slice produce duplicate time points

* tmp

* tmp

* adding fix for Sample interpolation.

* tmp

* add framework for pretty print testing and fix bugs #297

* fix bug in print with children

* remove [html] from .coveragerc and fix bugs in print testing

* finished assignment scan tests

* fix bug in codegen slice

* making `Append` give correct value for `eval_decimal(duration)`.

* add more tests for batch_assign

* add more testing cases

* add more tests and fix bugs related to fn() sampling

* fixing `samples` of `Sample` + adding example of using codegen directly.

* fix bug in matching of namedpulese

* finalize

* fix docstrings cannot properly display and parsing issue

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>

* CI for docs (#320)

* add more tests

* add more integration tests for codegen

* fix bug when ConstantCodeGen hit Negative wvfm node.

* tmp

* fix bug when slice produce duplicate time points

* tmp

* tmp

* adding fix for Sample interpolation.

* tmp

* add framework for pretty print testing and fix bugs #297

* fix bug in print with children

* remove [html] from .coveragerc and fix bugs in print testing

* finished assignment scan tests

* fix bug in codegen slice

* making `Append` give correct value for `eval_decimal(duration)`.

* add more tests for batch_assign

* add more testing cases

* add more tests and fix bugs related to fn() sampling

* fixing `samples` of `Sample` + adding example of using codegen directly.

* fix bug in matching of namedpulese

* finalize

* fix docstrings cannot properly display and parsing issue

* tempo update

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>

* Update mkdocs.yml

* chore: Update pdm.lock (#322)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* chore: Update pdm.lock (#324)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* Task module Refactor.  (#304)

* changing low-level task interface and renaming task classes

* fixing tests with new Task internal API.

* adding missing interface.

* updating `init_from_dict` to be a private method.

* adding interfaces for braket local simulator.

* updating `__init__` for classes to support specific kwargs.

* updating interface to reflect intent.

* fixing `removing_futures_with_task_id`

* dump future to file upon failure.

* add `rm .mock_state.txt` in test scripts.

* removing `name` from base API.

* fixing test/coverage scripts to not error.

* fixing typo in `tasks` property

* renaming json file.

* adding some comments.

* fixing annotations for SubmissionBackend

* adding tqdm

* big refactor of task submodule.

* adding type annotations.

* fixing annotation.

* renaming CloudTaskResults.

* fixing Annotation.

* fixing tests.

* fixing tests.

* fixing another test.

* updating testing scripts.

* removing old api.

* fixing wrong method name.

* removing potential circular imports.

* adding full stack trace to error output.

* Fixing bugs in QueueApi + upping test coverage.  (#323)

* fixing bug in `is_task_stopped`

* fixing bug in polling task results endpoint.

* untracking all files in

* add missing exception.

* upping coverage of QuEra API client

* removing path to fix integration test.

* removing path.

* fixing bug in unit test.

* Fix cast issue related to #326 (#327)

* enhance error msg of cast() and adding matching of abstract type Real() for numpy dtype/pytorch dtype

* change Numbers to Real

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* Test coverage for `QuEraBackend` (#328)

* changing name of test file, creating test file for `QuEraBackend` class

* fixing more tests.

* chore: Update pdm.lock (#332)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* [Stage-1] Docs for builder  (#331)

* add more tests

* add more integration tests for codegen

* fix bug when ConstantCodeGen hit Negative wvfm node.

* tmp

* fix bug when slice produce duplicate time points

* tmp

* tmp

* adding fix for Sample interpolation.

* tmp

* add framework for pretty print testing and fix bugs #297

* fix bug in print with children

* remove [html] from .coveragerc and fix bugs in print testing

* finished assignment scan tests

* fix bug in codegen slice

* making `Append` give correct value for `eval_decimal(duration)`.

* add more tests for batch_assign

* add more testing cases

* add more tests and fix bugs related to fn() sampling

* fixing `samples` of `Sample` + adding example of using codegen directly.

* fix bug in matching of namedpulese

* finalize

* fix docstrings cannot properly display and parsing issue

* tempo update

* add tree and builder docs

* update doc

* add docs for waveform

* finished documenting builder part, and hiding non-user parts

* update, fix builder linking, and add some doc for task/

* tmp

* change node to Compile instead of codegen

* hide parts that are internal from users

* add documentations for ir

* add more docstrings

* start adding prompt for IDE

* update

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Kai-Hsin Wu <khwu@31-36-24.wireless.csail.mit.edu>
Co-authored-by: Xiu-zhe (Roger) Luo <rogerluo.rl18@gmail.com>

* chore: Update pdm.lock (#339)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* Enhance docstring IDE experience  (#341)

* address #244, improving IDE hint experience up to waveform

* address #244, improving IDE hint experience up to waveform

* update, finished IDE enhance doc for waveform

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* chore: Update pdm.lock (#342)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* fix issues #336, and related examples (#343)

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>

* Test cases for #336 (#344)

* fix issues #336, and related examples

* add test case for #336

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>

* fix filling does not fragmented  for each cluster (#347)

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* chore: Update pdm.lock (#345)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* fix test

* ignore the bad test for now (#348)

* ignore the bad test for now

* ignore json in root

* Example 1: Rabi Oscillations (#163)

* Added Rabi example

* running linter

* Use lower case for variable names

* work in progress local emulation

* removed Variable import as well as explicit Variable initialization

* Added attempt to submit to hardware

* now runnable as standalone script, remove HW pipeline due to bug

* rename file with more standard convention

* Improved interactivity of plot, testing Braket submission capability

* remove hardware testing for now, bug found

* added hardware submission pipeline

* Complete end to end code added with improved Bokeh plot

* testing docs integration with whitepaper example

* forgot to add actual files in docs

* Final version of notebook, more text desirable, can be added later

* fix formatting issues

* Fixed lint issue with black

* Fixed JSON format and refactor to HardwareBatchResult

* temp fix on parallel decoder on this branch

---------

Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Xiu-zhe (Roger) Luo <rogerluo.rl18@gmail.com>

* rm old examples dir (#350)

* ignore generated json

* clean up json

* update emulator test for getbitstring (#351)

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* clean up json (#352)

* This PR address the issue with printing (#338)

* add more tests

* add more integration tests for codegen

* fix bug when ConstantCodeGen hit Negative wvfm node.

* tmp

* fix bug when slice produce duplicate time points

* tmp

* tmp

* adding fix for Sample interpolation.

* tmp

* add framework for pretty print testing and fix bugs #297

* fix bug in print with children

* remove [html] from .coveragerc and fix bugs in print testing

* finished assignment scan tests

* fix bug in codegen slice

* making `Append` give correct value for `eval_decimal(duration)`.

* add more tests for batch_assign

* add more testing cases

* add more tests and fix bugs related to fn() sampling

* fixing `samples` of `Sample` + adding example of using codegen directly.

* fix bug in matching of namedpulese

* finalize

* fix docstrings cannot properly display and parsing issue

* tempo update

* add tree and builder docs

* update doc

* add docs for waveform

* finished documenting builder part, and hiding non-user parts

* update, fix builder linking, and add some doc for task/

* tmp

* change node to Compile instead of codegen

* hide parts that are internal from users

* add documentations for ir

* add more docstrings

* start adding prompt for IDE

* compress the printing layout

* tmp

* auto detect if terminal support unicode

* make all default printing pretty print. and move old __repr__ to __str__ with proper changes

* finished pretty printing

* mod str

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Kai-Hsin Wu <khwu@31-36-24.wireless.csail.mit.edu>

* add Bloqade radius interactive indicator (#340)

* add Bloqade radius interactive plot

* add default values, invisible for radius

* remove return type for now

* fix hover info display issue and make index directly map to the location index in IR

* remove future

* fix (x,y) should be the atom pos not curser pos

* remove redundant testing

* tmp merge from main

* change default toggle to true

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>

* fix printing (#353)

* Update pyproject.toml (#358)

* chore: Update pdm.lock (#359)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* Fix improper printing on ScaledLocations (#361)

* add more tests

* add more integration tests for codegen

* fix bug when ConstantCodeGen hit Negative wvfm node.

* tmp

* fix bug when slice produce duplicate time points

* tmp

* tmp

* adding fix for Sample interpolation.

* tmp

* add framework for pretty print testing and fix bugs #297

* fix bug in print with children

* remove [html] from .coveragerc and fix bugs in print testing

* finished assignment scan tests

* fix bug in codegen slice

* making `Append` give correct value for `eval_decimal(duration)`.

* add more tests for batch_assign

* add more testing cases

* add more tests and fix bugs related to fn() sampling

* fixing `samples` of `Sample` + adding example of using codegen directly.

* fix bug in matching of namedpulese

* finalize

* fix docstrings cannot properly display and parsing issue

* tempo update

* add tree and builder docs

* update doc

* add docs for waveform

* finished documenting builder part, and hiding non-user parts

* update, fix builder linking, and add some doc for task/

* tmp

* change node to Compile instead of codegen

* hide parts that are internal from users

* add documentations for ir

* add more docstrings

* start adding prompt for IDE

* compress the printing layout

* tmp

* auto detect if terminal support unicode

* make all default printing pretty print. and move old __repr__ to __str__ with proper changes

* finished pretty printing

* mod str

* move all printing to base

* fix MockPrinter instances got instantiate upon import

* fix bug in ScaledLocations not properly printed

* fix testing cases

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Kai-Hsin Wu <khwu@31-36-24.wireless.csail.mit.edu>

* make docstring hint more explicit for spacial modulation and duplicate waveform (#362)

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* Fixing Builder API with multiple Spatial modulations.  (#360)

* adding termation function for spatial modulation.

* changing from terminate field build from appending waveforms to add waveforms.

* removing print statement.

* update, add testing cases

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* make ListOfLoc and BoundedLattice iterable (#363)

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* chore: Update pdm.lock (#365)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* moving emulator module.

* removing braket validaiton functionality. (#369)

* Task visualization (#366)

* chore: Update pdm.lock (#367)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* skipping test that was broken by removing validation implementaiton. (#371)

* stach changes.

* chore: Update pdm.lock (#374)

* chore: Update pdm.lock (#378)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* replace invalid characters for time-stamps in  windows. (#379)

* replace invalid characters for time-stamps in  windows.

* fixing ruff issue.

* add missing `not`

* adding file path to error message for clearity. (#380)

* fix print() issues with both Field and SpatialModulation (#377)

* fix print() issues with both Field and SpatialModulation

* fix lint

* fix bug in tree_print isinsance

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* chore: Update pdm.lock (#384)

* fix repr does not print tree for waveform (#383)

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* removing show from test_task

* Fixed non-existent get_cwd (#385)

* chore: Update pdm.lock (#386)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* chore: Update pdm.lock (#390)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* chore: Update pdm.lock (#393)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* chore: Update pdm.lock (#394)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* chore: Update pdm.lock (#395)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* Full IR visualization and Pulse canonicalize (#376)

* finish the field IR for uniform and runtimevec.

* update, add canonicalize for pulses

* enhance display

* comply lint

* add visualization for IRs

* merge main, and remove plotting from task_test

* fixing linter

* fixing linter

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>
Co-authored-by: Phillip Weinberg <phillipweinberg@Phillips-MacBook-Pro.local>

* Added pretty printing for registers/Bravais Lattices (#373)

* chore: Update pdm.lock (#398)

* Make sure the Rectangular plot follows the same format other Bravais lattices do (#403)

* chore: Update pdm.lock (#401)

* refactor builder (#364)

* refactor builder

* keep refactoring

* flatten works

* cleanup

* add a sketch of compile pipeline

* support device fn

* setup a basic lexer like codegen for builder

* waveform and address is working

* reexporting objects to `bloqade.ir` and `bloqade`

* adding `BoundedBravais` and `ParallelRegister` to imports.

* adding `create`/`copy` interface to `BuilderStream`

* wrap up whatever I have

* docstring.

* renambing fields of pulse and sequence

* implmenting compiler for pulse sequence.

* fix routing.

* adding better error messages for not implemented backends.

* stashing changes.

* adding `static_assign` functionality to scalars

* moving from just kargs to storing parameters as Scalar variables.

* stash

* rename

* fixing typo

* adding unit tests for

* rename class.

* moving visitor methods for primatives.

* update dev

* new compiler for sequence.

* removing main2.py

* rename modules.

* creating visitor for scalar AST, removing `static_assign` implement assign visitor for bloqade AST.

* adding canonicalization

* reorder imports.

* adding match arguments and serializers

* adding JSON serialization for Scalar IR.

* moving ir compiler into compiler subpackage

* creating stream submodule and json submodule.

* adding Sample node for builder.

* rename `checkpoint` to `coeff`

* adding json compiler for waveforms.

* adding json encoder for builder.

* task sketch.

* adding `apply` builder method for sequence objects.

* adding explicit check for `Waveform` type.

* adding serialization for builder + BloqadeIR

* fixing parallelize option for submit/flatten routes.

* commenting out old compiler. Adding register compiler

* setting up compiler trait.

* fixing compiler after refactoring circular imports

* fixing imports

* adding JSON compiler to builder.

* adding compiler traits.

* compiler pipeline

* adding ir caching option.

* updating caching to happen at all levels of bloqade-IR

* adding deserialization for bloqade-IR

* refactor base backend.

* finished draft implementation of serializer/deserializer

* Khwu/refactor task (#391)

* update, finished hardware tasl

* relocate Geometry, isolcate deps

* fix bug on Report

* update, change status behavior to request call. fix submit order does not shuffle in OrderDict

* add repr for Batch

* rename submit as resubmit

* finished restructure of Task/Batch

* update, finished bridge for task<->builder v2

* update, add simple docs

* fix namespace conflict in backend

* fix bug in RemoteBackend

* adding option for caching compiled programs in backends.

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* removing shots from options for backends.

* keyword arg for `parent`

* missing impl for static assignment on register IR objects.

* sketching bug fix.

* fix static assign, and visit_register issue

* fixing builder compiler to blqoade IR

* tm

* fixing another bug in builder compiler.

* remove redundant print

* fix bugs for batches

* update, fix bugs for report()

* fix bugs in waveform builder

* fix bugs with PythonFn waveform default kwargs. fix most of the testing

* Khwu/rename (#399)

* rename

* remove factory

* temporary add assert to make test_quera_internal_api fail

* fixing bugs in test.

* fix bugs in incomplete LocalTask/ LocalBatch. Fix report for LocalBatch

* change constrain of scale to Union[Real,str,Scalar].
2. compile visiting of record node, replace Variable(name) with cast(name)
3. fix tests cases for test_program_visitor.
4. add location method for scale

* more testing case

* mask coverage for deprecated codes builder_old/ task_old/

* add get_tasks/remove_tasks with status codes

* merging on github.  (#396)

* updating program definition. refactor compiler

* going back to old arg parser.

* adding error messages for flatten.

* refactor builder.

* moving builder to builder_old

* moving builder2 to builder

* moving task to task_old

* moving task2 to task

* fixing directory

* tmp save

* commented cache_compiled_program

* finished refactor on bridge using schemaCompiler

* starting serialization of task

* finished serialization

* fixing bugs.

* fixing braket local emulator.

* removing test call

* fixing some tests

* fixing interface for backends.

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* adding serialization for batch. (#400)

* adding serialization for batch.

* adding missing object ot serialization.

* update, fix bugs in naming _compile_taskdata, recover more tests

* add load_batch + doc for tree_depth()

* fix bugs in DefaultVariable should be Scalar not real, and member should be Literal instead of Decimal.
2) Fix PythonFn kwargs does not properly processed

* fix backend api_config need to pass in with dereferences

* Phil/save load batch (#404)

* adding serialization for batch.

* adding missing object ot serialization.

* adding save and load functions for batch objects.

* removing dict dispatching.

* fix bug in static_assign visit Negative waveform feed in wrong ast

* fixing tests

* fixing issue with pattern matching with `Poly`

* Khwu/testing v3 (#408)

* test +6

* 1) add checking for batch_assign lengths. 2) more tests recover,

* update, add trait BatchAssignable

* test +1, fix bug in load_batch

* adding fix to parser to account for `Sample` builder node.

* fix test case for mod/ DefaultVariable

* fix covergerc wrong format

* ocmply ruff

* fixing last tests.

---------

CI is now passing for builder refactor

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>

* Khwu/testing v4 (#409)

* test +6

* 1) add checking for batch_assign lengths. 2) more tests recover,

* update, add trait BatchAssignable

* test +1, fix bug in load_batch

* adding fix to parser to account for `Sample` builder node.

* fix test case for mod/ DefaultVariable

* fix covergerc wrong format

* ocmply ruff

* add more tests

* add missing __init__.py for builder/compile to comply with doc builder

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

---------

Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>
Co-authored-by: Kai-Hsin Wu <kaihsinwu@gmail.com>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>

* new design for lowering.

* chore: Update pdm.lock (#412)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* adding checks for scalar in assign

* Force plots to always be 80x24 (#415)

Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* adding tests.

* add shot info (total_nshots) for Batch and (nshots) for Task (#418)

* add shot info (total_nshots) for Batch and (nshots) for Task

* remove redundant print() in codegen. Add more info in repr/get_metric for batch.

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* Phil/adding constants module (#419)

* adding c6

* adding test

* stash

* adding sorting to counts. (#420)

* Recover docs for builder and IDE hint (#422)

* update, docs

* recover doc for builder coupling, field

* finished waveform doc

* update, finished recover IDE hint and docs for builder

* remove ParallelizeFlatten

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>

* Flatten bug invalid check (#426)

* fixing issue with check for trying to flatten vector arguments.

* adding test.

* run black.

* fixing ruff

* adding another test for flattened error.

* run black

* completing implementation for rabi

* fix negative scalar misleading ppring (#430)

* fix negative scalar misleading ppring

* update test

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* fixing bug. (#436)

* Add unicode autodetection, fallback to period as substitute for unicode dot (#431)

Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* Khwu/vis report#417 (#432)

* tmp

* finish visualize report

* update, finished metadata

* finished visual with hovertools and indicators

* add box_zoom

* fix bug in rydberg density

* fix metadata + add panx/zoomz options for plots.

* adding method to get a list of parameters from metadata.

* fixing annotation.

* x axis label 45 deg

* add name for report

* update

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* Khwu/vis geo#433 (#443)

* try logo

* add register

* add heatmap for rydberg density

* add heatmap, fix bugs for Decimal/float

* remove bar chart for ryd density

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>

* chore: Update pdm.lock (#445)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* chore: Update pdm.lock (#446)

* refactoring modules adding visitor for lowerfrom from emulator program to AnalogGate.

* adding duration to emulator program.

* adding features for waveforns,

* remove pydantic

* changing order of arguments.

* debugging lowering from bloqade-IR to emulator IR.

* changing order of args.

* adding helper functions for calculating matrix elements.

* chore: Update pdm.lock (#448)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* added unit tests for lattice terminal pretty printing (#402)

* added unit tests for lattice terminal pretty printing

* revised unit tests with main merged in, fixed 80 x 24 dimensions

* us os instead of pathlib

---------

Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* removing validation for reserved tokens (#452)

* removing validation for reserved tokens

* skipping test.

* add natoms from builder (#451)

* add natoms from builder

* rename natom -> n_atoms

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* Bokeh test and remove redundant __main__ in visualization/ (#450)

* explicit import

* fix testing import

* change show to save for tests

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* add terminal color support for Variable (#449)

* add color support

* fix test

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* updating pdm lock (#458)

* bug: swapped order in constructor. (#465)

* bug: swapped order in constructor.

* adding integration test.

* re-exporting objects into module just under bloqade. (#460)

* add icons for bloqade and QuEra (#462)

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* updating names of parameters for clarity

* adding matrix element calculation methods to space and adding AtomType objects.

* adding space atom types.

* stash for later

* chore: Update pdm.lock (#468)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* enhance batch behavior (#467)

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* renaming modules

* fixing implementation for two and three level system.

* renaming function (#471)

* 441 reorganize the program lowering pass (#444)

* updating to absolute paths.

* linter

* renaming modules.

* removing compiler, not needed

* adding parallel_decoder as return value from schema generator.

* adding sketch of compiler in program.

* removing TaskData like objects.

* adding compiler objects.

* adding parser.

* refactor compiler.

* fixing unit tests.

* adding check to make sure the serializer saves tasks properly.

* add newline

* adding builder as parent node to Program.

* renaming default variable to assigned variable for tracing.

* changing visitors.

* renaming  to

* removing compiler package

* stash, needs debugging

* debugging tests

* removing credentials from submiss API.

* fixing issue with deserialization.

* refactor parser.

* stashing

* fixing builder code.

* adding braket route

* adding quera submission

* adding exceptions for non-implemented content.

* adding quera options.

* renaming `DumbMockBackend` to just `MockBackend`

* adding back kai's change.

* fixing parser

* fixing some minor bugs.

* removing lower module.

* fixing configs.

* fixing some traits.

* stash changes.

* fixing some tests.

* fixing all unit tests.

* bug fix for parser.

* adding init for docs.

* adding multiprocessing back to the local jobs. (#421)

* adding multiprocessing back to the local jobs.

* adding `self` as return value for `run` in order to capture results from the process.

* changing from `multiprocessing` to `concurrent.futures` for simpler API.

* adding multiprocessing options to emulator routine.

* Removing old modules. (#474)

* Temporary state file for tests (#476)

* replace submit with compile

* add temporary file for integration test using state_file.

* Removing prints. (#477)

* updating docstring.

* stashing changes

* more stashing

* chore: Update pdm.lock (#482)

Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>

* adding fix for missing data in report.  (#478)

* adding fix for missing data

* removing reference to `task_number` in report outputs and just returning a list of values for each task in the data frame.

* adding filter flag for imperfect sotring.

* fixing test.

* better information for report (#481)

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* Khwu/batch status (#485)

* fix behavior of task/batch to better reflect the task status

* add check for task_id existing

* updating filters to use generic implementations.

* adding kwarg required for initialization.

* update, add immediate fetch after submit

* update fetch behavior when task_id is not exist

* update fix bugs

* remove accidentally pull when repr metric

* update, make statuscode *args

* update test

* add partial to return result for quera task

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>

* Visitor for Location module.  (#483)

* adding base class for location visitor

* create visitor for serializer.

* assing location visitor for static assign.

* moving compiler pass for assigning record values to outside of schema generating pass.

* rename static assign to assign,

* fixing missing rename

* adding assigned `RunTimeVector` node. (#484)

* adding assigned `RunTimeVector` node.

* fixing names in serialization for `AssignedVariable`

* update Serialization

* adding assignment for `RunTimeVector`

* adding node to Schema generator.

* adding test.

* debugging tests.

* bump for CI.

* fix casting param

* fixing bug for multiple pass.

* adding test for potential bug.

* fixing tests.

* update, remove bitstrings from hover, fix bug in counts for report (#487)

* update, remove bitstrings from hover, fix bug in counts for report

* update, remove bitststrings from hovers

* update remove redundant breakline from bitstrings

* remove redundanat print, and fix cis

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Phillip Weinberg <weinbe58@gmail.com>

* renaming submodule.

* Khwu/docs alpha (#489)

* add more docs for builder and Routine

* enhance docstrings for users, including batch, backend, routines

---------

Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>

* renameing modules.

* adding sample state

* adding routine for emulator.

* adding init.

* modify IR to be easily cachable to cache operators across multiple tasks.

* basic cases work for compilation

* removing assignment as it should happen in compiler passes.

* making code compaptible with different compilatoin passes.

* making hash include class name.

* using combination of operator data and geometry for caching results.

* adding comments.

* renaming `Geometry` to `Register`

* renaming methods.

* adding annotations.

* adding `BloqadeTask`

* adding bloqade emulator execution

* integration into builder

* adding `project_hyperfine` options explicitly

* fixing bugs.

* switching to interaction picture to speed up calculation.

* fixing options.

* adding some tests.

* more tests.

* more tests.

* rename positions to sites.

* refactor modules.

* fixing bug in report

* fixing hash and fixing imports.

* integration.

* fixing bug with interaction picture.

* adding time-selection to AnalogGate.apply

* adding equality back for register.

* fixing bug with field position -> sites.

* renaming `geometry` to `register`

* renaming fields to be more consistent with BloqadeIR.

* renaming visitor methods.

* fixing transformation out of interaction picture.

* fixing sign.

* fixing names in codegen.

* adding integration test.

* renaming test.

* fixing name of test.

* fixing names in hamiltonian codegen.

* adding integration test with phase.

* adding builder hint.

* adding docs.

* fixing bug, updating docs.

* reusing array.

* fixing potential bug with subspace matrix element calculation.

* fixing typo

* moving compiled waveform into emulator IR.

* fixing tests.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: John Long <johnzl@protonmail.ch>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MBP.hsd1.ma.comcast.net>
Co-authored-by: Xiu-zhe (Roger) Luo <rogerluo.rl18@gmail.com>
Co-authored-by: Roger-luo <Roger-luo@users.noreply.github.com>
Co-authored-by: Kai-Hsin Wu <khwu@KHWus-MacBook-Pro.local>
Co-authored-by: Kai-Hsin Wu <kaihsinwu@gmail.com>
Co-authored-by: Kai-Hsin Wu <khwu@31-36-24.wireless.csail.mit.edu>
Co-authored-by: Phillip Weinberg <phillipweinberg@Phillips-MacBook-Pro.local>
  • Loading branch information
10 people authored Sep 11, 2023
1 parent 2b396ab commit b42ac56
Show file tree
Hide file tree
Showing 18 changed files with 1,674 additions and 777 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ job.json
out.txt
.DS_Store
tests/data/jobs/
main.html

# Byte-compiled / optimized / DLL files
__pycache__/
Expand Down
1,440 changes: 821 additions & 619 deletions pdm.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ dependencies = [
"juliacall>=0.9.12",
"numpy>=1.24.2",
"pydantic>=1.10.7",
"scipy>=1.9.3",
"pandas>=2.0.1",
"seaborn>=0.12.2",
"bokeh>=3.1.1",
Expand Down
13 changes: 11 additions & 2 deletions src/bloqade/builder/backend/bloqade.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,17 @@ def bloqade(self):


class BloqadeDeviceRoute(Builder):
def python(self, solver: str):
raise NotImplementedError
def python(self):
"""
- Specify bloqade python backend
- Possible Next:
-> `...python().run(shots, ...)`
:: Run the current program using bloqade python backend
"""
from bloqade.ir.routine.bloqade import BloqadeServiceOptions

return BloqadeServiceOptions(self).python()

def julia(self, solver: str, nthreads: int = 1):
raise NotImplementedError
32 changes: 14 additions & 18 deletions src/bloqade/emulate/codegen/emulator_ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,24 @@
from bloqade.emulate.ir.atom_type import ThreeLevelAtom, TwoLevelAtom
from bloqade.emulate.ir.emulator import (
DetuningOperatorData,
LevelCoupling,
RabiOperatorData,
RabiOperatorType,
DetuningTerm,
CompiledWaveform,
EmulatorProgram,
Register,
LaserCoupling,
Fields,
RabiTerm,
)

from dataclasses import dataclass
from typing import Any, Dict, Optional, Union, List
from numbers import Number, Real
from decimal import Decimal

ParamType = Union[Real, List[Real]]


@dataclass(frozen=True)
class CompiledWaveform:
assignments: Dict[str, Number]
source: waveform.Waveform

def __call__(self, t: float) -> float:
return self.source(t, **self.assignments)


class WaveformCompiler(WaveformVisitor):
# TODO: implement AST generator for waveforms.
def __init__(self, assignments: Dict[str, Number] = {}):
Expand All @@ -61,9 +53,9 @@ def __init__(
self.blockade_radius = Decimal(str(blockade_radius))
self.assignments = assignments
self.waveform_compiler = WaveformCompiler(assignments)
self.geometry = None
self.register = None
self.duration = 0.0
self.drives = {}
self.pulses = {}
self.level_couplings = set()

def visit_analog_circuit(self, ast: ir.AnalogCircuit):
Expand All @@ -80,21 +72,25 @@ def visit_register(self, ast: AtomArrangement) -> Any:
positions.append(position)

if sequence.hyperfine in self.level_couplings:
self.geometry = Register(
self.register = Register(
ThreeLevelAtom, positions, blockade_radius=self.blockade_radius
)
else:
self.geometry = Register(
self.register = Register(
TwoLevelAtom, positions, blockade_radius=self.blockade_radius
)

def visit_sequence(self, ast: sequence.SequenceExpr):
level_coupling_mapping = {
sequence.hyperfine: LevelCoupling.Hyperfine,
sequence.rydberg: LevelCoupling.Rydberg,
}
match ast:
case sequence.Sequence(pulses):
for level_coupling, sub_pulse in pulses.items():
self.level_couplings.add(level_coupling)
self.visit(sub_pulse)
self.drives[level_coupling] = LaserCoupling(
self.pulses[level_coupling_mapping[level_coupling]] = Fields(
detuning=self.detuning_terms,
rabi=self.rabi_terms,
)
Expand Down Expand Up @@ -324,7 +320,7 @@ def emit(self, circuit: ir.AnalogCircuit) -> EmulatorProgram:

self.visit(circuit)
return EmulatorProgram(
geometry=self.geometry,
register=self.register,
duration=self.duration,
drives=self.drives,
pulses=self.pulses,
)
207 changes: 207 additions & 0 deletions src/bloqade/emulate/codegen/rydberg_hamiltonian.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
from bloqade.constants import RB_C6
from bloqade.emulate.ir.emulator import (
DetuningOperatorData,
EmulatorProgram,
LevelCoupling,
Register,
Fields,
DetuningTerm,
RabiOperatorData,
RabiOperatorType,
RabiTerm,
Visitor,
)
from bloqade.emulate.ir.space import Space
from bloqade.emulate.ir.atom_type import (
TwoLevelAtomType,
ThreeLevelAtomType,
)
from bloqade.emulate.ir.state_vector import (
RabiOperator,
DetuningOperator,
RydbergHamiltonian,
)
from bloqade.emulate.sparse_operator import IndexMapping
from scipy.sparse import csr_matrix
import numpy as np
from numpy.typing import NDArray
from typing import Dict, Optional, Tuple, Union
from dataclasses import dataclass, field

OperatorData = Union[DetuningOperatorData, RabiOperatorData]
MatrixTypes = Union[csr_matrix, IndexMapping, NDArray]


@dataclass
class CompileCache:
"""This class is used to cache the results of the code generation."""

operator_cache: Dict[Tuple[Register, OperatorData], MatrixTypes] = field(
default_factory=dict
)
space_cache: Dict[Register, Tuple[Space, NDArray]] = field(default_factory=dict)


class RydbergHamiltonianCodeGen(Visitor):
def __init__(self, compile_cache: Optional[CompileCache] = None):
if compile_cache is None:
compile_cache = CompileCache()

self.rabi_ops = []
self.detuning_ops = []
self.level_coupling = None
self.level_couplings = set()
self.compile_cache = compile_cache

def visit_emulator_program(self, emulator_program: EmulatorProgram):
self.level_couplings = set(list(emulator_program.pulses.keys()))

self.visit(emulator_program.register)
for level_coupling, laser_coupling in emulator_program.pulses.items():
self.level_coupling = level_coupling
self.visit(laser_coupling)

def visit_register(self, register: Register):
self.register = register

if register in self.compile_cache.space_cache:
self.space, self.rydberg = self.compile_cache.space_cache[register]
return

self.space = Space.create(register)
sites = register.sites

# generate rydberg interaction elements
self.rydberg = np.zeros(self.space.size, dtype=np.float64)

for index_1, site_1 in enumerate(sites):
site_1 = np.asarray(list(map(float, site_1)))
is_rydberg_1 = self.space.is_rydberg_at(index_1)
for index_2, sites_2 in enumerate(sites[index_1 + 1 :], index_1 + 1):
sites_2 = np.asarray(list(map(float, sites_2)))
distance = np.linalg.norm(site_1 - sites_2)

rydberg_interaction = RB_C6 / (distance**6)

if rydberg_interaction <= np.finfo(np.float64).eps:
continue

mask = np.logical_and(is_rydberg_1, self.space.is_rydberg_at(index_2))
self.rydberg[mask] += rydberg_interaction

self.compile_cache.space_cache[register] = (self.space, self.rydberg)

def visit_fields(self, fields: Fields):
terms = fields.detuning + fields.rabi
for term in terms:
self.visit(term)

def visit_detuning_operator_data(self, detuning_data: DetuningOperatorData):
if (self.register, detuning_data) in self.compile_cache.operator_cache:
return self.compile_cache.operator_cache[(self.space, detuning_data)]

diagonal = np.zeros(self.space.size, dtype=np.float64)
match (self.space.atom_type, self.level_coupling):
case (TwoLevelAtomType(), LevelCoupling.Rydberg):
state = TwoLevelAtomType.State.Rydberg
case (ThreeLevelAtomType(), LevelCoupling.Rydberg):
state = ThreeLevelAtomType.State.Rydberg
case (ThreeLevelAtomType(), LevelCoupling.Hyperfine):
state = ThreeLevelAtomType.State.Hyperfine

for atom_index, value in detuning_data.target_atoms.items():
diagonal[self.space.is_state_at(atom_index, state)] += float(value)

self.compile_cache.operator_cache[(self.register, detuning_data)] = diagonal
return diagonal

def visit_rabi_operator_data(self, rabi_operator_data: RabiOperatorData):
if (self.register, rabi_operator_data) in self.compile_cache.operator_cache:
return self.compile_cache.operator_cache[
(self.register, rabi_operator_data)
]

# Get the from and to states for term
match (self.space.atom_type, self.level_coupling):
case (TwoLevelAtomType(), LevelCoupling.Rydberg):
to = TwoLevelAtomType.State.Ground
fro = TwoLevelAtomType.State.Rydberg
case (ThreeLevelAtomType(), LevelCoupling.Rydberg):
to = ThreeLevelAtomType.State.Hyperfine
fro = ThreeLevelAtomType.State.Rydberg
case (ThreeLevelAtomType(), LevelCoupling.Hyperfine):
to = ThreeLevelAtomType.State.Ground
fro = ThreeLevelAtomType.State.Hyperfine

# get matrix element generating function
if rabi_operator_data.operator_type is RabiOperatorType.RabiSymmetric:

def matrix_ele(atom_index):
return self.space.swap_state_at(atom_index, fro, to)

elif rabi_operator_data.operator_type is RabiOperatorType.RabiAsymmetric:

def matrix_ele(atom_index):
return self.space.transition_state_at(atom_index, fro, to)

# generate rabi operator
if len(rabi_operator_data.target_atoms) == 1:
((atom_index, _),) = rabi_operator_data.target_atoms.items()
operator = IndexMapping(self.space.size, *matrix_ele(atom_index))
else:
indptr = np.zeros(self.space.size + 1, dtype=self.space.index_type)

for atom_index in rabi_operator_data.target_atoms:
row_indices, col_indices = matrix_ele(atom_index)
indptr[1:][row_indices] += 1
np.cumsum(indptr, out=indptr)

indices = np.zeros(indptr[-1], dtype=self.space.index_type)
data = np.zeros(indptr[-1], dtype=np.float64)

for atom_index, value in rabi_operator_data.target_atoms.items():
row_indices, col_indices = matrix_ele(atom_index)
indices[indptr[:-1][row_indices]] = col_indices
data[indptr[:-1][row_indices]] = value
indptr[:-1][row_indices] += 1

indptr[1:] = indptr[:-1]
indptr[0] = 0

operator = csr_matrix(
(data, indices, indptr),
shape=(self.space.size, self.space.size),
)

self.compile_cache.operator_cache[
(self.register, rabi_operator_data)
] = operator
return operator

def visit_detuning_term(self, detuning_term: DetuningTerm):
self.detuning_ops.append(
DetuningOperator(
diagonal=self.visit(detuning_term.operator_data),
amplitude=detuning_term.amplitude,
)
)

def visit_rabi_term(self, rabi_term: RabiTerm):
self.rabi_ops.append(
RabiOperator(
op=self.visit(rabi_term.operator_data),
amplitude=rabi_term.amplitude,
phase=rabi_term.phase,
)
)

def emit(self, emulator_program: EmulatorProgram) -> RydbergHamiltonian:
self.visit(emulator_program)
hamiltonian = RydbergHamiltonian(
emulator_ir=emulator_program,
space=self.space,
rydberg=self.rydberg,
detuning_ops=self.detuning_ops,
rabi_ops=self.rabi_ops,
)
return hamiltonian
4 changes: 2 additions & 2 deletions src/bloqade/emulate/ir/atom_type.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from dataclasses import dataclass
from enum import Enum
import numpy as np
from numpy.typing import NDArray
import numpy as np
from enum import Enum


@dataclass(frozen=True)
Expand Down
Loading

0 comments on commit b42ac56

Please sign in to comment.