Example #1
0
def test_about(capfd):
    """
	about: Tests if the about string prints correct.
	"""
    pennylane.about()
    out, err = capfd.readouterr()
    assert (type(out) == str)
Example #2
0
def about():
    with StringIO() as buffer, redirect_stdout(buffer):
        qml.about()
        about = buffer.getvalue()
    message_dict = {}
    message_dict["message"] = about
    message_dict["schema"] = "message"

    with open("about.json", "w") as f:
        f.write(json.dumps(message_dict, indent=2))
Example #3
0
def test_about(capfd):
    """
    about: Tests if the about string prints correct.
    """
    pennylane.about()
    out, err = capfd.readouterr()
    assert "Version:" in out
    pl_version_match = re.search(r"Version:\s+([\S]+)\n", out).group(1)
    assert pennylane.version().replace("-", ".") in pl_version_match
    assert "Numpy version" in out
    assert "Scipy version" in out
    assert "default.qubit" in out
    assert "default.gaussian" in out
Example #4
0
def test_about():
    """
    about: Tests if the about string prints correct.
    """
    f = io.StringIO()
    with contextlib.redirect_stdout(f):
        qml.about()
    out = f.getvalue().strip()

    assert "Version:" in out
    pl_version_match = re.search(r"Version:\s+([\S]+)\n", out).group(1)
    assert qml.version().replace("-", ".") in pl_version_match
    assert "Numpy version" in out
    assert "Scipy version" in out
    assert "default.qubit" in out
    assert "default.gaussian" in out
print("Learned weights")
for i in range(num_layers):
    print("Layer {}: {}".format(i, params[i]))

fig, axes = plt.subplots(1, 3, figsize=(10, 3))
plot_data(X_test, initial_predictions, fig, axes[0])
plot_data(X_test, predicted_test, fig, axes[1])
plot_data(X_test, y_test, fig, axes[2])
axes[0].set_title("Predictions with random weights")
axes[1].set_title("Predictions after training")
axes[2].set_title("True test data")
plt.show()

##############################################################################
# This tutorial was generated using the following Pennylane version:

qml.about()

##############################################################################
# References
# ----------
# [1] Pérez-Salinas, Adrián, et al. “Data re-uploading for a universal
# quantum classifier.” arXiv preprint arXiv:1907.02085 (2019).
#
# [2] Kingma, Diederik P., and Ba, J. "Adam: A method for stochastic
# optimization." arXiv preprint arXiv:1412.6980 (2014).
#
# [3] Liu, Dong C., and Nocedal, J. "On the limited memory BFGS
# method for large scale optimization." Mathematical programming
# 45.1-3 (1989): 503-528.
Example #6
0
def cli():
    """Parse the command line arguments, perform the requested action.
    """
    parser = argparse.ArgumentParser(description="PennyLane benchmarking tool")
    parser.add_argument("--noinfo",
                        action="store_true",
                        help="suppress information output")
    parser.add_argument("--version", action="version", version=__version__)
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        help="verbose mode")
    parser.add_argument(
        "-d",
        "--device",
        type=lambda x: x.split(","),
        default="default.qubit",
        help=
        "comma-separated list of devices to run the benchmark on (default: %(default)s)",
    )
    parser.add_argument(
        "-q",
        "--qnode",
        type=lambda x: x.split(","),
        default="QNode",
        help=
        "comma-separated list of QNode subclasses to run the benchmark on (default: %(default)s)",
    )
    parser.add_argument(
        "-w",
        "--wires",
        type=int,
        default=3,
        help="number of wires to run the benchmark on (default: %(default)s)",
    )
    parser.add_argument("cmd",
                        choices=["time", "plot", "profile"],
                        help="function to perform")
    parser.add_argument("benchmark",
                        help="benchmark module name (without .py)")

    args = parser.parse_args()

    # look up information about the current HEAD Git commit
    res = subprocess.run(
        ["git", "log", "-1", "--pretty=%h %s"],
        stdout=subprocess.PIPE,
        encoding="utf-8",
        check=True,
    )
    title = res.stdout
    short_hash = title.split(" ", maxsplit=1)[0]

    print("Benchmarking PennyLane", qml.version())

    if args.verbose:
        print("Verbose mode on, results may not be representative.")

    if not args.noinfo:
        print("Commit:", col(title, "red"))
        qml.about()
        print()

    # import the requested benchmark module
    mod = importlib.import_module(args.benchmark)

    # execute the command
    if args.cmd == "plot":
        print("Performance plot: '{}' benchmark on {}, {}".format(
            mod.Benchmark.name, args.device, args.qnode))
        bms = [
            mod.Benchmark(qml.device(d, wires=args.wires),
                          qnode_type=q,
                          verbose=args.verbose) for d in args.device
            for q in args.qnode
        ]
        for k in bms:
            k.setup()
        plot(
            title,
            [k.benchmark for k in bms],
            [
                f"{args.benchmark} {k.device.short_name} {k.qnode_type}"
                for k in bms
            ],
            mod.Benchmark.n_vals,
        )
        for k in bms:
            k.teardown()
        return

    for d in args.device:
        for q in args.qnode:
            dev = qml.device(d, wires=args.wires)
            bm = mod.Benchmark(dev, qnode_type=q, verbose=args.verbose)
            bm.setup()
            text = col(f"'{bm.name}'", "blue") + " benchmark on " + col(
                f"{d}, {q}", "magenta")
            if args.cmd == "time":
                print("Timing:", text)
                timing(bm.benchmark)
            elif args.cmd == "profile":
                print("Profiling:", text)
                profile(bm.benchmark, identifier="_".join([short_hash, d, q]))
            else:
                raise ValueError("Unknown command.")
            bm.teardown()