Style Guide

This section contains the style guide for the code.

General Guidelines

  • Do not use using namespace std;, or any other variant, unless it is localised inside a function body and significantly increases readability.

  • Try to pass large objects (such as std::vector<double> or other classes) by constant reference. Pass builtin types (e.g. int, double, etc.) by value.

Indenting and whitespace

Indents are 4 spaces.

The built-in constructions if, for, switch, etc. should be followed by one space.

Statements which call a function, or define a callable object, should not have a space. For example, if foo is a function of int, use foo(3), not foo (3). Function prototypes and definitions do not have a space after the function name.

Placement of braces

The opening brace for if statements, for loops, switch statements, etc. should be on the same line as the opening statement:

if (done == true) {
     return result;
}

Braces should always be used in these constructions, even if there is only one line in the body of the construction as above. Otherwise, adding new lines to the body might lead to bugs if you forget to add the newly required braces.

In contrast, the opening brace for classes, structs, namespaces, and functions should begin directly below the keyword on the next line, as follows:

void printInt(int a)
{
     std::cout << a << std::endl;
}

This automatically makes the function or class easier to read without needing to add an unnecessary empty line after the prototype line.

Class, function and variable names

Todo

Write me plz

Comments

Every file should contain a doxygen comment explaining what is inside the file, in the following format:

/**
 * \file foobar.cpp
 * \brief Contains function implementations for foo and bar
 *
 * Put an optional longer comment about the contents of the
 * file here.
 *
 */

Everything in a *.hpp file (function prototypes, class/struct definitions, namespace definitions, using statements, etc.) must be fully doxygen commented (using an extended doxygen comment block). Each comment must contain a \brief and a detailed description if necessary. The comment should be sufficient to understand what the object is used for. Implementation details should not be included, unless they are relevant to the use of the object.

If functions take arguments, each argument must be documented using \param. If the function does not return void, the returned value must be documented using \return.

Apart from the file doxygen comment at the top, *.cpp and *.tpp should not contain any comments outside function bodies. Function bodies can include single- or multi-line comments (constructed from repeated lines beginning with //). Do not use doxygen for general comments. Do not to use multiline comment blocks (/* */), because this can make commenting out large blocks of code difficult. Only write a comment if it adds information which is not (too) obvious from the C++ code.

The only exception to the above rules is \todo statements, which can be included anywhere in any source file. A \todo statement should be written in the following way:

///\todo What needs to be done

Laying out Classes and Structs

Class/struct definitions should follow this convention regarding the use of whitespace:

/**
 * \brief An example class
 *
 * Include a description about how to
 * use the class.
 *
 */
class Foo
{
     int a; ///< Brief inline variable description
     double b; ///< Another brief description

     /**
      * \brief A more complicated object
      *
      * Variables which required more description
      * should have their own doxygen comment like
      * this.
      *
      */
     Bar b;

     // Put private member functions here

public:

     const int c; ///< Public member variables should be const

    /**
     * \brief Constructors should be listed before
     * other public member function
     *
     * Member functions should always have an
     * extended doxygen comment, because it is
     * nearly always necessary to explain what
     * it does in more than one line!
     *
     */
     Foo();

     /**
     * \brief Get the Bar member
     * \return The internal Bar object
     */
     Bar getBar() const;
};

Observe the following guidelines about writing a class

  • Do not use the keyword private. Private members should be listed first anyway. Do not intermingle public and private members.

  • Do not include an empty newline before the first class member or after the final class member.

  • Public data members should be declared const. If a data member is not const, but must be accessible from outside the class, then write a get method for it. If it is accessible from outside the class, it might be accidentally changed.

  • All members of a class should be doxygen commented.

  • If you can make a member function const, you should. This allows the compiler to check that the member function does not modify anything in the class.

  • Do not include a member function definition in the class definition. Put them inside a corresponding .cpp file instead.

Structs can be used for objects where all the members are public, whose only purpose is to group data togther. Structs should be kept as small as possible, and have no member functions other than constructors. Structs should be laid out and commented as described above, and should not contain the keyword public.

Other names (namespaces, types, etc.)

Todo

Write me plz

File naming and file structure

File names should comprise a single lowercase word with no underscores, followed by .hpp for header files, .cpp for implementation files or .tpp for template implementations. No file should exceed 1000 lines.

Todo

Is ‘single lowercase word’ too restrictive?

Header files

Header files (.hpp) should contain class definitions and function prototypes, along with detailed documentation. In addition to exposing functions to .cpp files that use the functions, it should be possible for a user of the functions to read the documentation and understand what all the functions and classes do. Unrelated functions should be placed in different header files, and the filename should give some indication about what is in the file. The contents of the header file file.hpp should be wrapped in a header guard as follows:

#ifndef FILE_HPP
#define FILE_HPP

// File contents here

#endif

Implementation files

Implentation files (.cpp) should contain definitions of the class member functions and standalone functions defined in the header files. Implementation files should be split up into multiple files if they become too large. Implementation files do not need extensive comments.

Template files

Template files (.tpp) should contain implementations of template functions, analogously to .cpp files. However, they should be wrapped in header guards and included at the end of their corresponding header file. Template files do not need extensive comments.

Release Planning

Change proposals

This section contains unsorted proposals. Things here should be moved into the the sections for each version according to when it would be best incorporated.

Interface Improvements

  • Do something about the really long type names! (general redesign required)

  • Allow copy-construction and copy-assignment between different simulator types (if they make sense).

  • Consider making postselect and measure both return the outcome (even though it is redundant in the former case) to avoid possible mistakes mixing up returned value (outcome vs. probability). Might not be worth it though.

  • Overload qsl::norm, qsl::distance, etc. to take simulators as arguments. Allow different types of simulators to be compared

  • Finish off the integration of concepts

  • Make good use of language helper features – for example, attributes like nodiscard, check everything is const if it can be, check if any arguments can be made explicit, passed by reference, etc.

  • Consider renaming qsl::fubiniStudy to qsl::distance, since we only have one distance, and probably won’t add more.

  • Consider renaming qsl::makeRandomState to qsl::randomState.

  • Consider changing getNumQubits() to size(). The disadvantage is it might be confused with getDimension(). At the least, those member functions could probably do without the get.

Functionality Improvements

  • Add the ability to perform a read-only measureOut operation in the resize simulator, that returns the state which would be obtained by the measureOut, but which does not modify the simulator state (or number of qubits). (This function should work a bit like the sample functions.)

  • Add an easy way to turn on a debugging mode which throws exceptions for out-of-bounds indices, etc., which does not introduce a performance penalty when it is not required.

  • Add measurement in an arbitrary basis. For example, specify the Euler angles, or have a few specific measurement types (e.g. measureX, measureY maybe). Maybe have some way to perform multi-qubit measurements? Needs a bit of thinking about.

  • Add arbitrary one- and two-qubit gates.

Implementation Improvements

  • Add SSE, AVX and GPU support to the simulators.

  • Investigate whether the parallelisation (using openmp) is optimal.

  • Check if binary search from standard library can replace manual version.

Unbreak Immediately!

  • We have a sampleAll and a sampleAll2 function!

Version 0.1

The following changes should be included in the release.

  • Change qsl::complex struct to std::complex throughout program. Test there is no performance reduction.

  • Add some more access functions e.g. getAmplitude, etc.

Notes

Any general notes from the development should go here. They can be categorised properly later.

  • Apparently GCC 10 produces much faster executables than GCC 7 (try compiling test in commit 42d491babc with both and see).

Todos

Important

Todo

Write sorting method for sampling, figure out exactly when it is faster than the binary search method, and write a function to swap between the two.

Todo

Split up Qubits .cpp file into multiple chunks (e.g. for gates, for measurement, etc.)

Todo

Fix cmake build.

Todo

Find out why it takes longer to apply gates to qubit 0. Firstly, check that it does actually take longer (and is not an artifact due to 0 being the first qubit that is manipulated). In theory, it should be faster to apply the gates to low qubits.

Todo

Redo the variable names in the two qubit gates so that they are consistent with the rest of the code

Todo

Decide what to do when function prototypes line wrap (due to long arguments, long return types, templates, etc.)

Todo

Move the comments from benchmark1 and benchmark2 to Compare class, and delete benchmark1 and benchmark2 prototypes. Do the same with the other old benchmark functions

Todo

Rename Time class to something else (it conflicts with Timer)

Todo

Check whether SingleSim can be implemented as a special case of MultiSim, with the length = 1 (i.e. check that it is not slower to use the vector). If it is fine, then the code for SingleSim could be realised as a special case of MultiSim.

Todo

Figure out what graphs we want to plot in python

Todo

Check that the mean and variance in the Results class give the right answers.

Todo

Simplify the implementation of the functions in the Results class

Less important

Todo

Find the proper way to include todos

Todo

Sort out the Fp_type type inside the Qubits class. Is there a way to eliminate it completely?

Todo

Add more gates to the simulators.

Todo

Write functions to measure, postselect and sample groups of qubits.

Todo

Write a simulator that contains error checking (like bounds checking) for debugging, etc.

Todo

Somehow reduce the code repetition in Compare and Time classes

Todo

Implement the other functions in the Results class (but before that, decide whether the structure of the Results class is right. This will be obvious after trying to use them e.g. to plot graphs in python).

page todo

Namespace qsl

At the moment this is only required because of the use of fubiniStudy in the template function below. Maybe the fubiniStudy function should be moved somewhere else.

Find a good structure for including these files

Global qsl::abs  (const complex< Fp > &a)

Maybe it would be good to add an absSquared?

Global qsl::benchmark1  (Gate< F, ArgsF... > fn, Gate< G, ArgsG... > gn, unsigned nqubits, int test_len)

Move this compare to Compare<MultiSim>

Global qsl::benchmark1SampleAll  (unsigned nqubits, int nsamples, int test_len=1)

Move this to Compare<MultiSim>::sampleAll

Global qsl::benchmark2  (Gate< F, ArgsF... > fn, Gate< G, ArgsG... > gn, unsigned nqubits, int test_len)

Move this comment to Compare<SingleSim>

Class qsl::Compare< T, Sim1, Sim2 >

Get rid of all the Restrictions stuff. A much better method for adding in number preserving states would be to allow the state vector to be passed into the Time class from the outside. This would make it the user’s responsibility to pick the right state vector.

Global qsl::convertState  (const std::vector< complex< From >> &state)

At the moment, template type checking is performed using SFINAE based on std::enable_if (checking if From is convertible to To). Find a more modern alternative

Global qsl::fubiniStudy  (const S1 &s1, const S2 &s2)

Maybe this should go in utils?

Global qsl::Gate

Maybe these typedefs are a bad idea?

Class qsl::GateChecker< Sim1, Sim2 >

Find a way to control the phases, etc.

Global qsl::GateChecker< Sim1, Sim2 >::check  (std::ostream &os, OneQubitGate< Sim1, typename Sim1::Fp_type > fn, OneQubitGate< Sim2, typename Sim2::Fp_type > gn)

Should be float?

Global qsl::GateChecker< Sim1, Sim2 >::check  (std::ostream &os, TwoQubitGate< Sim1, typename Sim1::Fp_type > fn, TwoQubitGate< Sim2, typename Sim2::Fp_type > gn)

Should be float or Fp_type?

Global qsl::GateChecker< Sim1, Sim2 >::check  (std::ostream &os, OneQubitGate< Sim1 > fn, OneQubitGate< Sim2 > gn)

Should be float?

Global qsl::makeRandomNPState  (unsigned nqubits)

This needs testing

Global qsl::makeRandomNPState  (unsigned nqubits, unsigned nones)

This needs testing

Global qsl::maxRelativeError  (BinomialCI a, BinomialCI b)

What if both are zero?

Global qsl::MeasureChecker< Sim1, Sim2 >::checkAll  (std::ostream &os)

Count up how many times the distances are zero

Global qsl::MeasureChecker< Sim1, Sim2 >::configureChecker  (std::size_t nsamples_in, double ci_in)

Work out the right name for the variable ci (confidence level?)

Global qsl::MeasureChecker< Sim1, Sim2 >::ResultData

Add check that the state vectors are the same as well

Global qsl::PostselectChecker< Sim1, Sim2 >::ResultData

Should also check the norms here

Global qsl::printBin  (const std::string &name, unsigned int x)

The length of the bitstring is hardcoded, fix it

Global qsl::Qubits< Type::Default, Fp >::getState  () const

Return std::vector<std::complex<Fp>> instead

Global qsl::Qubits< Type::Default, Fp >::Qubits  (unsigned nqubits)

Is there a less bad way to do this?

Global qsl::Qubits< Type::Default, Fp >::setState  (const std::vector< complex< Fp >> &state)

Take std::vector<std::complex<Fp>> instead

Global qsl::Qubits< Type::NP, Fp >::Qubits  (unsigned nqubits, unsigned nones=1)

Is there a less bad way to do this?

Global qsl::Qubits< Type::Omp, Fp >::Qubits  (unsigned nqubits, unsigned nthreads=4)

Is there a less bad way to do this?

Global qsl::Qubits< Type::OmpNP, Fp >::Qubits  (unsigned nqubits, unsigned nones=1, unsigned nthreads=4)

Is there a less bad way to do this?

Global qsl::Qubits< Type::Resize, Fp >::Qubits  (unsigned nqubits)

Is there a less bad way to do this?

Global qsl::Random< Fp >::Random  (Fp a, Fp b)

Is std::random_device OK?

Global qsl::SampleAllChecker< Sim1, Sim2 >::checkAll  (std::ostream &os)

Need to make the proportion of common outcomes symmetrical with respect to sample2.

Fix so it is symmetrical with respect to sample2

Global qsl::SampleAllChecker< Sim1, Sim2 >::configureChecker  (std::size_t nsamples_in, double ci_in)

Work out the right name for the variable ci (confidence level?)

Global qsl::SampleChecker< Sim1, Sim2 >::checkAll  (std::ostream &os)

For this to be legitimate with low sample numbers, it is necessary to repeatedly sample the sample function (which is not what happens at the moment).

Global qsl::SampleChecker< Sim1, Sim2 >::configureChecker  (std::size_t nsamples_in, double ci_in)

Work out the right name for the variable ci (confidence level?)

Global qsl::StateGenerator

Need to add something about the floating point type it returns, so as to make it compatible with the simulators

Global qsl::Test

Write documentation

Class qsl::Verify< Sim1, Sim2, Gen, Checkers >

This causes a bug at the moment in the checkers

Global TEST  (SampleAll2Test, ResizeDouble)

Find a legitimate statistical test.

Global TEST  (SampleAll2Test, DefaultDouble)

Find a legitimate statistical test.

Global TEST  (SampleAll2Test, NPDouble)

Find a legitimate statistical test.

Global TYPED_TEST  (NPMeasurements, SampleTest)

We need to figure out a legitimate way to test whether the probability is correct.

Global TYPED_TEST  (Measurements, MeasureAllTest)

Find a legitimate statistical test.

Global TYPED_TEST  (NPMeasurements, MeasureTest)

We need to figure out a legitimate way to test whether the probability is correct.

Global TYPED_TEST  (Measurements, SampleAllTest)

Find a legitimate statistical test.

Global TYPED_TEST  (FpUtilities, RandomClassTest)

How to check that the distribution is uniform and random?

Global TYPED_TEST  (NPMeasurements, MeasureAllTest)

Find a legitimate statistical test.

Global TYPED_TEST  (NPMeasurements, SampleAllTest)

Find a legitimate statistical test.

Global TYPED_TEST  (Measurements, MeasureTest)

We need to figure out a legitimate way to test whether the probability is correct.

Global TYPED_TEST  (ResizeTests, MeasureOutTest)

We need to figure out a legitimate way to test whether the probability is correct.

Global TYPED_TEST  (Measurements, SampleTest)

We need to figure out a legitimate way to test whether the probability is correct.

License

The code and documentation is covered by the Apache 2.0 License below.

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.