Giter VIP home page Giter VIP logo

libqasm's Introduction

libQASM: Library to parse cQASM v3.0 files

CI PyPI

File organization

For development, see:

  • include: public headers.
  • src: source files.
  • test: test files.
  • python: SWIG interface.
  • res: resource files, for testing.

For build process, continuous integration, and documentation:

  • conan: Conan profiles.
  • emscripten: bindings and test for the emscripten binaries.
  • scripts: helper scripts used during the build process.
  • .github: GitHub Actions configuration files.
  • doc: documentation.

Build outputs may go into:

  • build/<build type>: the C++ library output files generated by Conan.
  • pybuild: the Python library output files generated by setup.py.

Dependencies

  • C++ compiler with C++20 support (gcc 11, clang 14, msvc 17)
  • CMake >= 3.12
  • git
  • Python 3.x plus pip, with the following package:
    • conan >= 2.0

ARM specific dependencies

We are having problems when using the zulu-opendjk Conan package on an ARMv8 architecture. zulu-openjdk provides the Java JRE required by the ANTLR generator. So, for the time being, we are installing Java manually for this platform.

  • Java JRE >= 11

Build

This version of libqasm can only be compiled via the Conan package manager. You'll need to create a default profile before using it for the first time.

The installation of dependencies, as well as the compilation, can be done in one go.

git clone https://github.com/QuTech-Delft/libqasm.git
cd libqasm
conan profile detect
conan build . -pr:a=conan/profiles/tests-debug -b missing

Notice:

  • the conan profile command only has to be run only once, and not before every build.
  • the conan build command is building libqasm in Debug mode with tests using the tests-debug profile.
  • the -b missing parameter asks conan to build packages from sources in case it cannot find the binary packages for the current configuration (platform, OS, compiler, build type...).

Build profiles

A group of predefined profiles is provided under the conan/profiles folder.
They follow the [tests](-build_type)(-compiler)(-os)(-arch)[-shared] naming convention:

  • tests: if tests are being built.
  • build_type: can be debug or release.
  • compiler: apple-clang, clang, gcc, msvc.
  • os: emscripten, linux, macos, windows.
  • arch: arm64, wasm, x64.
  • shared: if the library is being built in shared mode.

All the profiles set the C++ standard to 20.
All the tests, except for linux-x64 profiles, enable Address Sanitizer.

Build options

Profiles are a shorthand for command line options. The command above could be written, similarly, as:

conan build . -s:a compiler.cppstd=20 -s:a libqasm/*:build_type=Debug -o libqasm/*:build_tests=True -o libqasm/*:asan_enabled=True -b missing

This is the list of options that could be specified either in a profile or in the command line:

  • libqasm/*:asan_enabled={True,False}: enables Address Sanitizer.
  • libqasm/*:build_type={Debug,Release}: builds in debug or release mode.
  • libqasm/*:shared={True,False}: builds a shared object library instead of a static library, if applicable.

Tests are enabled by default. To disable them, use -c tools.build:skip_test=True.

Install

From Python

Install from the project root directory as follows:

python3 -m pip install --verbose .

You can test if it works by running:

python3 -m pytest

From C++

The CMakeLists.txt file in the root directory includes install targets:

conan create --version 0.6.6 . -pr:a=tests-debug -b missing

You can test if it works by doing:

cd test/Debug
ctest -C Debug --output-on-failure

Use from another project

From Python

The libqasm module should provide access to the V3xAnalyzer API:

  • parse_file,
  • parse_string,
  • analyze_file, and
  • analyzer_string.

The cqasm.v3x module is also available for a more fine-grained use of the library.

import cqasm.v3x.ast
import cqasm.v3x.instruction
import cqasm.v3x.primitives
import cqasm.v3x.semantic
import cqasm.v3x.types
import cqasm.v3x.values

From C++

libqasm can be requested as a Conan package from a conanfile.py.

def build_requirements(self):
    self.tool_requires("libqasm/0.6.5")
def requirements(self):
    self.requires("libqasm/0.6.5")

And then linked against from a CMakeLists.txt:

target_link_libraries(<your target> PUBLIC libqasm::libqasm)

Note that the following dependency is required for libqasm to build:

  • Java JRE >= 11

The header file cqasm.hpp should provide access to the following API:

  • cqasm::v3x::analyze_file, and
  • cqasm::v3x::analyze_string.

Again, other header files are available for a more fine-grained use of the library.

Docker

This tests the library in a container with the bare minimum requirements for libqasm.

docker build .

Note for Windows users: The above might fail on Windows due to the autocrlf transformation that git does. If you are having trouble with this just create new clone of this repository using:

git clone --config core.autocrlf=input [email protected]:QuTech-Delft/libqasm.git

Emscripten

The generation of emscripten binaries has been tested as a cross-compilation from an ubuntu/x64 platform.

conan build . -pr=conan/profiles/release-clang-emscripten-wasm -pr:b=conan/profiles/release -b missing

The output of this build lives in build/Release/emscripten:

  • cqasm_emscripten.js.
  • cqasm_emscripten.wasm.

Note that cqasm_emscripten.js is an ES6 module. An example of how to use it would be:

cd build/Release/emscripten
mv cqasm_emscripten.js cqasm_emscripten.mjs
cd ../../../emscripten
deno run -A test_libqasm.ts

libqasm's People

Contributors

abousias avatar alxhotel avatar ammar92 avatar elenbaasc avatar imranashraf avatar jvansomeren avatar jvanstraten avatar kel85uk avatar koffie avatar mbrobbel avatar oschusler avatar pablolh avatar qfer avatar quantumkoen avatar razvnane avatar rknegjens avatar rturrado avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

libqasm's Issues

Memory leak in src/library/libQasm.hpp

Fer Grooteman reported a memory leak on libqasm, and pointed us to the code he thought this memory leak was coming from, a newed memory in src/library/libQasm.hpp that was never released.

Add support for more than one numerical parameter

When specifying the error model, it would be very helpful we can have optionally more than one numerical parameter.

For instance, something like this:
error_model depolarizing_channel,0.003
error_model depolarizing_channel,0.003,0.004,0.003
error_model pauli_twirling_aprox,45,33

This would allow the use of several error models using the exact same syntax and it is compatible with the current syntax.

Semantic checker incomplete

Need to account for negative value of the iteration count of the subcircuits. -1 now gives a ridiculously large number due to the datatype.

Mac OS support

since we use libqasm for openql testing, which is supported on Win, Linux and Mac. It is desirable to add support for Mac to libqasm as well

Python usage of libqasm

Hello!

I was wondering how I could use libqasm to get the a QASM circuit in a python data structure which I could access and operate on.

I tried:

`
from libQasm import libQasm as lq

a = lq("./test/bell.qasm") #while on the qasm_flex_bison folder
b = a.getQasmRepresentation()
`

So far so good.
But they I try to access it's methods, like numQubits, etc I can't:
b.numQubits() doesn't work, for example... The only attributes of 'b' appear to be:
b.acquire( b.append( b.disown( b.next( b.own(

Any ideas?

Warning about deprecated SWIG_ADD_MODULE

In the develop branch, cmake outputs:

CMake Deprecation Warning at /usr/share/cmake-3.10/Modules/UseSWIG.cmake:231 (message):
  SWIG_ADD_MODULE is deprecated.  Use SWIG_ADD_LIBRARY instead.
Call Stack (most recent call first):
  CMakeLists.txt:48 (SWIG_ADD_MODULE)

Parser error on correct multiple binary conditions

The following code (from line 13 in code example 3 in the cqasm 1.0 paper):

version 1.0 

qubits 5

c-x b[0],b[1],q[4]

Results in a syntax error:


  =================================================================================================== 
        _______                                                                                       
       /  ___   \   _  __      ____   ____   __  ___  __  __   __    ___  ______  ____    ___         
      /  /   /  |  | |/_/     / __/  /  _/  /  |/  / / / / /  / /   / _ |/_  __/ / __ \  / _ \        
     /  /___/  /  _>  <      _\ \   _/ /   / /|_/ / / /_/ /  / /__ / __ | / /   / /_/ / / , _/        
     \______/\__\ /_/|_|    /___/  /___/  /_/  /_/  \____/  /____//_/ |_|/_/    \____/ /_/|_|         
                                                                                                      
     version 0.2 beta - QuTech - 2018 - report bugs and suggestions to: [email protected]
  =================================================================================================== 

[+] loading circuit from '../../code.qasm' ...
error while parsing file ../../code.qasm: 
syntax error, unexpected BITHEAD, expecting NAME or QBITHEAD | Token 299 on Line: 5

Flex_bison input files

We need to create the lexer input files as well as the grammar input for flex and bison respectively.

  • Create .l file for flex and fill
  • Create .y file for bison and fill

Improve user experience

libqasm's equivalent to this OpenQL issue.

Current build line looks something like:

conan build . -s:h compiler.cppstd=20 -s:h libqasm/*:build_type=Release -o libqasm/*:build_tests=True -o openql/*:compat=False -b missing

As a result of the conversation for this issue that I opened, I've found out that we could turn it into something like:

conan build . -pr=conan/profiles/tests-release -b missing

Explanation (see also here):

  1. If you set CMAKE_CXX_STANDARD in your project, you don't need to pass the compiler version as a command line parameter. I've noticed we were not doing that in OpenQL.
  2. There is a way of not working with command line options at all, but defining them in a profile. For example, we could provide a conan/profiles folder together with the code, including a set of predefined profiles, e.g. tests-release, which would look something like:
include(default)

[settings]
libqasm/*:build_type=Release
[options]
libqasm/*:asan_enabled=False
libqasm/*:build_tests=True
libqasm/*:compat=False

And then just compile with conan build . -pr=conan/profiles/tests-release.

Or, these profiles may be copied to the ~./conan2/profiles folder, e.g. for this case, with a name such as libqasm-tests-release, and then build with conan build . -pr=libqasm-tests-release.

Confusing qubits get function name

getQubitsInvolved is confusing as it only applies to single qubit operations. Check to see if function name can be overloaded depending on the return type (unlikely). If not possible, then change the function name to reflect appropriately.

Add load_state support

See this related issue as a trigger for this: QuTech-Delft/qx-simulator#32

The keyword load_state is useful and should be supported by the parser since a user might not want to have to recreate the entire state from the different qubit operations. It's easier to just load from a file.

`test-v1-parsing` fails to run in WSL due to line endings handling

At the moment:

  1. *.cq and *.golden.txt have CRLF endings, and
  2. *.actual.txt files are written out in text mode (see libqasm/src/tests/v1-parsing.cpp, write_file method. That means that, depending on the OS, LF or CRLF will be written out as line endings (for Unix or Windows respectively).
  3. It is important to notice that some *.cq files are used as input when writing out *.actual.txt files.

test-v1-parsing basically:

  • Builds a string, and writes it out as an *.actual.txt file,
  • then reads a *.golden.txt file into another string, and, finally
  • checks whether both strings are the same.

Line endings shouldn't be a problem because, independently from the OS, an LF or CRLF should be read in as a \n. I understand that's why tests are currently working in Linux/macos (which use LF).

However, when running the tests in a WSL environment, the comparisons fail.

I have a fix for this which consists of:

  1. Writing out *.actual.txt in binary mode (so LF is always written).
  2. Changing all *.cq and *.golden.txt files to LF line endings.

But, before carrying on with the fix, I have to understand what's the issue with WSL.

Sub-circuit termination

A suggestion for a future version of QASM (from our front-end team):

When you define a sub circuit it can only be terminated by defining a new sub circuit. This is a strange restriction. A more obvious choice would be to 1) indent the commands that are part of the subcircuit or 2) to use accolades {…} to define the sub circuit.

Add integration tests

With the cQASM paper, there are many code examples which should be valid. They can be part of a test suite to ensure that the library is parsing correctly.

This will be done only after the library is completed.

Line termination

A suggestion for a future version of QASM (from our front-end team):

• I personally would prefer lines to end with semicolons ; especially because it makes long lines that span multiple rows in a small window (like our editor) better readable

clearing state across multiple runs

compiler::SubCircuits subcircuits_object holds the state which is declared globally in grammar.y. This results in the stateful behavior which causes problem when library is used to load cqasm file multiple times.

Better error handling in Semantic checker

The semantic checker is far from complete. We need to make sure the semantic checker does:

  • Check that operations are having correct vector lengths.
  • Check that keywords are not used as maps.
  • Provide clearer exception messages for the user.

Create the grammar BNF file

Need to make sure there's a grammar file so that developers in the future can look into this document and have the syntax settled. Helps create the parser via flex, bison.

Ensure that Windows also builds fine

We know that the library builds ok with Linux systems, but still need to test it with Windows. We'll know for sure once we have a unit testing framework.

Parse error on comment after qubits line

On the develop branch, this input:

version 1.0

qubits 2 # foo

gives this output:

Path to QASM file = test.qc
Error syntax error, unexpected WS, expecting NEWLINE | Token 272 on Line: 3

Removing the # foo results in a parseable file again.

Comments should be allowed after a qubits line.

python interface for the libqasm

One of the use cases of libqasm it to verify if a file generated by a tool (for instance openql) conforms to the specifications. A convenient way to do that will be to have a simple interface to libqasm where it can be installed as a package and provides a simple API, for instance libqasm.assemble(qasmfile) which can be used to test if a given file can be assembled or not.

P.S. it might be useful to have a look at openql, or qxelerator to see how they provide the python interface. A more specific example can be qisa-as which has a similar API and is being used in unit-tests by openql to verify the generated QISA files for CCLight.

CMake support

Many people in the QCA group are running CentOS 6 or 7 systems, which provide CMake 2.8.12. Requiring 3.12 as per #117 is therefore not reasonable.

Float parser doesn't recognize `1.`

This code:

version 1.0
# cqasm generated by QI backend for QisKit
qubits 2
Rz q[0], 1.
.measurement
   measure q[0]

results in:


  =================================================================================================== 
        _______                                                                                       
       /  ___   \   _  __      ____   ____   __  ___  __  __   __    ___  ______  ____    ___         
      /  /   /  |  | |/_/     / __/  /  _/  /  |/  / / / / /  / /   / _ |/_  __/ / __ \  / _ \        
     /  /___/  /  _>  <      _\ \   _/ /   / /|_/ / / /_/ /  / /__ / __ | / /   / /_/ / / , _/        
     \______/\__\ /_/|_|    /___/  /___/  /_/  /_/  \____/  /____//_/ |_|/_/    \____/ /_/|_|         
                                                                                                      
     version 0.1 beta - QuTech - 2016 - report bugs and suggestions to: [email protected]     
  =================================================================================================== 

[+] loading circuit from 'test3.qc' ...
Error while parsing file test3.qc: 
syntax error, unexpected INTEGER, expecting FLOAT | Token 260 on Line: 4

The expression 1. is by most programming languages etc considered to be a valid float specification.

measure q[0,1,2,3] seems to only measure q[0], not q[1], q[2], q[3]

Same for x[0,1,2,3] etc.. it seems to only work in the first one in the range. Consider this code:

version 1.0

qubits 5

prep_z q[0:4]

x q[0,1,2,3]

measure_all
display

The measurement result is:

[>>] measurement register  :  | 0 | 0 | 0 | 0 | 1 |

While we would expect 01111 instead. Also tested with measure q[0,1,2,3], which only measures q[0]

B as alias is not parsed

This code from the qx simulator test suite is not parsed:

version 1.0 

# file   : full_adder.qc
# author : Nader Khammassi
# brief  : quantum full adder (carry-save addition)

# define 4 qubits
qubits 4

# rename qubits
map q[0],A 
map q[1],B
map q[2],C
map q[3],D


# init inputs to some values
.init
  x A 
  x C 

  display_binary  #  initial input value


# perform addition
.add

  toffoli B,C,D
  cnot    B,C 
  toffoli A,C,D
  cnot    A,C 

  display_binary #  result

.reverse_add

  cnot    A,C 
  toffoli A,C,D
  cnot    B,C 
  toffoli B,C,D

  display_binary #  result

# error_model depolarizing_channel, 0.1 

Reports:

[+] loading circuit from 'tests/circuits/full_adder.qc' ...
Error while parsing file tests/circuits/full_adder.qc: 
syntax error, unexpected BITHEAD, expecting NAME

remove bin directory

please remove bin directory from commits. it will be nice to make clean your code which should remove this bin directory and other temporary files to avoid adding them to commit. It is also a good practive to add .gitignore file to your project.

Including the Location of Errors in the Syntax/Semantic Error Messages

In case of syntax/semantic errors, the error message indicates the type of the error but not its location. it would be very helpful to indicate the location of the error (line and position) whenever the parsing fails to help debugging the QASM code and testing QX.

For example, in this message, we see the type of the error but not its location:

[+] loading circuit from 'test.qc' ...
error while parsing file test.qc: 
syntax error, unexpected QBITHEAD, expecting NAME or BITHEAD

add README.md file

It will be useful to add README.md file expaling a bit the tool, its setup and basic usage.

Multiple comment lines between ```version``` and ```qubits``` results in syntax error

Consider this input:

version 1.0 

# foo 
# bar

qubits 2

.entangle
  H q[0]
  CNOT q[0], q[1]
  measure_all
.ma3ae5408346341c4ac42640e358fbacb
display

This results in this output:


  =================================================================================================== 
        _______                                                                                       
       /  ___   \   _  __      ____   ____   __  ___  __  __   __    ___  ______  ____    ___         
      /  /   /  |  | |/_/     / __/  /  _/  /  |/  / / / / /  / /   / _ |/_  __/ / __ \  / _ \        
     /  /___/  /  _>  <      _\ \   _/ /   / /|_/ / / /_/ /  / /__ / __ | / /   / /_/ / / , _/        
     \______/\__\ /_/|_|    /___/  /___/  /_/  /_/  \____/  /____//_/ |_|/_/    \____/ /_/|_|         
                                                                                                      
     version 0.1 beta - QuTech - 2016 - report bugs and suggestions to: [email protected]     
  =================================================================================================== 

[+] loading circuit from '/tmp/test2.qc' ...
Error syntax error, unexpected COMMENT, expecting QUBITS | Token 274 on Line: 6

Removing line 4 fixes the error.

Create test-suite

I'd expect to be able to run something like make test to run an automated test-suite (using some c++ unit testing framework) that checks that valid qasm compiles, and invalid qasm results in syntax errors. This can then also be part of the CI/CD to have a quality gate for PR's.

install problem

cmake fails with:
CMake Error at /usr/share/cmake-3.10/Modules/UseSWIG.cmake:247 (message):
SWIG_ADD_LIBRARY: Missing LANGUAGE argument

this can be resolved by changing line 83 to:
SWIG_ADD_LIBRARY(libQasm LANGUAGE python SOURCES libqasm_swig.i)

Then you start seeing problem:
#include "doctest/doctest.h"
^
compilation terminated.
CMakeFiles/testqc.dir/build.make:62: recipe for target 'CMakeFiles/testqc.dir/home/iashraf/repositories/quantRepos/libqasm/qasm_flex_bison/test/testqc.cpp.o' failed
make[2]: *** [CMakeFiles/testqc.dir/home/iashraf/repositories/quantRepos/libqasm/qasm_flex_bison/test/testqc.cpp.o] Error 1
CMakeFiles/Makefile2:104: recipe for target 'CMakeFiles/testqc.dir/all' failed
make[1]: *** [CMakeFiles/testqc.dir/all] Error 2
Makefile:94: recipe for target 'all' failed
make: *** [all] Error 2

Add custom gate support

Discussions with Nader today created a need for custom unitary gate support. E.g.:

U q[0], mat00_real, mat00_imag, mat01..., mat10,... mat11

On develop branch, error_model is no longer accepted

Consider this input:

version 1.0

qubits 2

error_model depolarizing_channel, 0.001

Results in a syntax error:

Path to QASM file = test.qc
Error syntax error, unexpected NAME, expecting $end | Token 259 on Line: 5

It should be parsed and supported by qx simulator (and ignored by openql as was previously the case).

#pragma-like construction for implementation-specific instructions

QX simulator parses things like error_model depolarizing_channel, 0.001, which is illegal in QASM 1.0 according to the definition. It would be good to extend the language with a #pragma-like construction (as seen in c/c++), that can be used to define syntactically valid implementation-specific instructions. If an implementation does not support the particular pragma, it can safely ignore it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.